Browse Source

Merge branch 'lts-4.4' into feature/ai-websocket-channel

pull/16336/head
Igor Kulikov 2 months ago
parent
commit
07f6140756
  1. 10
      application/src/main/data/json/demo/dashboards/firmware.json
  2. 10
      application/src/main/data/json/demo/dashboards/software.json
  3. 4
      application/src/main/data/json/demo/dashboards/thermostats.json
  4. 2
      application/src/main/data/json/system/widget_types/asset_admin_table.json
  5. 2
      application/src/main/data/json/system/widget_types/device_admin_table.json
  6. 6
      application/src/main/data/resources/dashboards/gateways_dashboard.json
  7. 78
      application/src/main/java/org/thingsboard/server/controller/SignUpController.java
  8. 91
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
  9. 51
      application/src/test/java/org/thingsboard/server/controller/SignUpControllerSqlTest.java
  10. 12
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
  11. 5
      common/data/src/main/java/org/thingsboard/server/common/data/DataConstants.java
  12. 30
      common/data/src/main/java/org/thingsboard/server/common/data/User.java
  13. 13
      common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DashboardInstalledItemDescriptor.java
  14. 1
      common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/IotHubInstalledItemDescriptor.java
  15. 188
      common/data/src/test/java/org/thingsboard/server/common/data/UserTest.java
  16. 3
      common/edge-api/src/main/proto/edge.proto
  17. 4
      msa/black-box-tests/pom.xml
  18. 45
      ui-ngx/src/app/core/http/iot-hub-api.service.ts
  19. 2
      ui-ngx/src/app/core/http/white-labeling.service.ts
  20. 37
      ui-ngx/src/app/core/services/resources.service.ts
  21. 195
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.html
  22. 79
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts
  23. 5
      ui-ngx/src/app/modules/home/components/entity/entity-chips.component.html
  24. 6
      ui-ngx/src/app/modules/home/components/entity/entity-chips.component.scss
  25. 30
      ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss
  26. 3
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html
  27. 38
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts
  28. 45
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.html
  29. 39
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.scss
  30. 66
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts
  31. 3
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts
  32. 31
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html
  33. 63
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.scss
  34. 60
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.ts
  35. 1
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss
  36. 1
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts
  37. 5
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html
  38. 14
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts
  39. 20
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html
  40. 4
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.scss
  41. 47
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.ts
  42. 4
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.html
  43. 4
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.scss
  44. 12
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.ts
  45. 160
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.html
  46. 160
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss
  47. 297
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts
  48. 4
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html
  49. 11
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.ts
  50. 26
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-utils.ts
  51. 4
      ui-ngx/src/app/modules/home/components/widget/lib/settings/common/action/custom-sample-html.raw
  52. 4
      ui-ngx/src/app/modules/home/components/widget/lib/settings/common/action/mobile-action-editor.models.ts
  53. 2
      ui-ngx/src/app/modules/home/components/widget/lib/settings/common/action/place-map-item-sample-html.raw
  54. 2
      ui-ngx/src/app/modules/home/pages/admin/white-labeling.component.html
  55. 15
      ui-ngx/src/app/modules/home/pages/admin/white-labeling.component.ts
  56. 8
      ui-ngx/src/app/modules/home/pages/customer/customer.component.html
  57. 4
      ui-ngx/src/app/modules/home/pages/customer/customer.component.ts
  58. 10
      ui-ngx/src/app/modules/home/pages/customer/customers-table-config.resolver.ts
  59. 3
      ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html
  60. 1
      ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-deep-link.utils.ts
  61. 83
      ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html
  62. 128
      ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss
  63. 120
      ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts
  64. 7
      ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.ts
  65. 13
      ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-routing.module.ts
  66. 99
      ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-search-page.component.scss
  67. 2
      ui-ngx/src/app/modules/home/pages/reporting/report/manage-report-public-access-modal.component.html
  68. 188
      ui-ngx/src/app/shared/directives/photoswipe-gallery.directive.ts
  69. 10
      ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts
  70. 58
      ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts
  71. 100
      ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts
  72. 2
      ui-ngx/src/assets/help/en_US/widget/action/examples/custom_pretty_create_dialog_html.md
  73. 2
      ui-ngx/src/assets/help/en_US/widget/action/examples/custom_pretty_edit_dialog_html.md
  74. 2
      ui-ngx/src/assets/help/en_US/widget/action/examples_custom_pretty/custom_pretty_clone_device_html.md
  75. 2
      ui-ngx/src/assets/help/en_US/widget/action/examples_custom_pretty/custom_pretty_create_dialog_html.md
  76. 2
      ui-ngx/src/assets/help/en_US/widget/action/examples_custom_pretty/custom_pretty_create_user_html.md
  77. 2
      ui-ngx/src/assets/help/en_US/widget/action/examples_custom_pretty/custom_pretty_create_user_js.md
  78. 2
      ui-ngx/src/assets/help/en_US/widget/action/examples_custom_pretty/custom_pretty_edit_dialog_html.md
  79. 12
      ui-ngx/src/assets/help/en_US/widget/action/examples_custom_pretty/custom_pretty_edit_image_html.md
  80. 4
      ui-ngx/src/assets/help/en_US/widget/action/mobile_process_image_fn.md
  81. 2
      ui-ngx/src/assets/help/en_US/widget/action/place_map_item/create_dialog_html.md
  82. 102
      ui-ngx/src/assets/iot-hub/items-page-dashboards-hero.svg
  83. 16
      ui-ngx/src/assets/locale/locale.constant-en_US.json
  84. 8
      ui-ngx/structure.md

10
application/src/main/data/json/demo/dashboards/firmware.json

@ -279,7 +279,7 @@
"name": "Edit firmware",
"icon": "edit",
"type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar class=\"flex flex-row\" color=\"primary\">\n <h2>Edit firmware {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"firmwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit firmware {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"firmwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": "form {\n min-width: 300px !important;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n firmwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n firmwareId: vm.entity.firmwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.firmwareId = formValues.firmwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}",
"customResources": [],
@ -1142,7 +1142,7 @@
"name": "Edit firmware",
"icon": "edit",
"type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar class=\"flex flex-row\" color=\"primary\">\n <h2>Edit firmware {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"firmwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit firmware {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"firmwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": "form {\n min-width: 300px !important;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n firmwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n firmwareId: vm.entity.firmwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.firmwareId = formValues.firmwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}",
"customResources": [],
@ -1448,7 +1448,7 @@
"name": "Edit firmware",
"icon": "edit",
"type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar class=\"flex flex-row\" color=\"primary\">\n <h2>Edit firmware {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"firmwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit firmware {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"firmwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": "form {\n min-width: 300px !important;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n firmwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n firmwareId: vm.entity.firmwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.firmwareId = formValues.firmwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}",
"customResources": [],
@ -1754,7 +1754,7 @@
"name": "Edit firmware",
"icon": "edit",
"type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar class=\"flex flex-row\" color=\"primary\">\n <h2>Edit firmware {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"firmwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit firmware {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"firmwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": "form {\n min-width: 300px !important;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n firmwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n firmwareId: vm.entity.firmwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.firmwareId = formValues.firmwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}",
"customResources": [],
@ -2060,7 +2060,7 @@
"name": "Edit firmware",
"icon": "edit",
"type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar class=\"flex flex-row\" color=\"primary\">\n <h2>Edit firmware {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"firmwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit firmware {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"firmwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": "form {\n min-width: 300px !important;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n firmwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n firmwareId: vm.entity.firmwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.firmwareId = formValues.firmwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}",
"customResources": [],

10
application/src/main/data/json/demo/dashboards/software.json

@ -279,7 +279,7 @@
"name": "Edit software",
"icon": "edit",
"type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar class=\"flex flex-row\" color=\"primary\">\n <h2>Edit software {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n type=\"SOFTWARE\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"softwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit software {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n type=\"SOFTWARE\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"softwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": "form {\n min-width: 300px !important;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n softwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n softwareId: vm.entity.softwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.softwareId = formValues.softwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}",
"customResources": [],
@ -1142,7 +1142,7 @@
"name": "Edit software",
"icon": "edit",
"type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar class=\"flex flex-row\" color=\"primary\">\n <h2>Edit software {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n type=\"SOFTWARE\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"softwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit software {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n type=\"SOFTWARE\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"softwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": "form {\n min-width: 300px !important;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n softwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n softwareId: vm.entity.softwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.softwareId = formValues.softwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}",
"customResources": [],
@ -1448,7 +1448,7 @@
"name": "Edit software",
"icon": "edit",
"type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar class=\"flex flex-row\" color=\"primary\">\n <h2>Edit software {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n type=\"SOFTWARE\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"softwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit software {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n type=\"SOFTWARE\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"softwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": "form {\n min-width: 300px !important;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n softwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n softwareId: vm.entity.softwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.softwareId = formValues.softwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}",
"customResources": [],
@ -1754,7 +1754,7 @@
"name": "Edit software",
"icon": "edit",
"type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar class=\"flex flex-row\" color=\"primary\">\n <h2>Edit software {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n type=\"SOFTWARE\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"softwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit software {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n type=\"SOFTWARE\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"softwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": "form {\n min-width: 300px !important;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n softwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n softwareId: vm.entity.softwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.softwareId = formValues.softwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}",
"customResources": [],
@ -2060,7 +2060,7 @@
"name": "Edit software",
"icon": "edit",
"type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar class=\"flex flex-row\" color=\"primary\">\n <h2>Edit software {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n type=\"SOFTWARE\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"softwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit software {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n type=\"SOFTWARE\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"softwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": "form {\n min-width: 300px !important;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n softwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n softwareId: vm.entity.softwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.softwareId = formValues.softwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}",
"customResources": [],

4
application/src/main/data/json/demo/dashboards/thermostats.json

@ -167,7 +167,7 @@
"name": "Add",
"icon": "add",
"type": "customPretty",
"customHtml": "<form #addEntityForm=\"ngForm\" [formGroup]=\"addEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"add-entity-form\">\n <mat-toolbar color=\"primary\">\n <h2>Add thermostat</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div mat-dialog-content class=\"flex flex-col\">\n <mat-form-field class=\"mat-block flex-1\">\n <mat-label>Thermostat name</mat-label>\n <input matInput formControlName=\"entityName\" required>\n <mat-error *ngIf=\"addEntityFormGroup.get('entityName').hasError('required')\">\n Thermostat name is required.\n </mat-error>\n </mat-form-field>\n <div formGroupName=\"attributes\" class=\"flex flex-col\">\n <mat-slide-toggle formControlName=\"temperatureAlarmFlag\">\n High temperature alarm\n </mat-slide-toggle>\n <mat-form-field class=\"mat-block flex-1\">\n <mat-label>High temperature threshold, °C</mat-label>\n <input type=\"number\" step=\"any\" matInput\n [required] = \"addEntityFormGroup.get('attributes').get('temperatureAlarmFlag').value\"\n formControlName=\"temperatureAlarmThreshold\">\n <mat-error *ngIf=\"addEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').hasError('required')\">\n High temperature threshold is required.\n </mat-error>\n </mat-form-field>\n\n <mat-slide-toggle formControlName=\"humidityAlarmFlag\">\n Low humidity alarm\n </mat-slide-toggle>\n\n <mat-form-field class=\"mat-block flex-1\">\n <mat-label>Low humidity threshold, %</mat-label>\n <input type=\"number\" step=\"any\" matInput\n [required] = \"addEntityFormGroup.get('attributes').get('humidityAlarmFlag').value\"\n formControlName=\"humidityAlarmThreshold\">\n <mat-error *ngIf=\"addEntityFormGroup.get('attributes').get('humidityAlarmThreshold').hasError('required')\">\n Low humidity threshold is required.\n </mat-error>\n </mat-form-field>\n </div>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || addEntityForm.invalid || !addEntityForm.dirty\">\n Create\n </button>\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n </div>\n</form>",
"customHtml": "<form #addEntityForm=\"ngForm\" [formGroup]=\"addEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"add-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Add thermostat</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div mat-dialog-content class=\"flex flex-col\">\n <mat-form-field class=\"mat-block flex-1\">\n <mat-label>Thermostat name</mat-label>\n <input matInput formControlName=\"entityName\" required>\n <mat-error *ngIf=\"addEntityFormGroup.get('entityName').hasError('required')\">\n Thermostat name is required.\n </mat-error>\n </mat-form-field>\n <div formGroupName=\"attributes\" class=\"flex flex-col\">\n <mat-slide-toggle formControlName=\"temperatureAlarmFlag\">\n High temperature alarm\n </mat-slide-toggle>\n <mat-form-field class=\"mat-block flex-1\">\n <mat-label>High temperature threshold, °C</mat-label>\n <input type=\"number\" step=\"any\" matInput\n [required] = \"addEntityFormGroup.get('attributes').get('temperatureAlarmFlag').value\"\n formControlName=\"temperatureAlarmThreshold\">\n <mat-error *ngIf=\"addEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').hasError('required')\">\n High temperature threshold is required.\n </mat-error>\n </mat-form-field>\n\n <mat-slide-toggle formControlName=\"humidityAlarmFlag\">\n Low humidity alarm\n </mat-slide-toggle>\n\n <mat-form-field class=\"mat-block flex-1\">\n <mat-label>Low humidity threshold, %</mat-label>\n <input type=\"number\" step=\"any\" matInput\n [required] = \"addEntityFormGroup.get('attributes').get('humidityAlarmFlag').value\"\n formControlName=\"humidityAlarmThreshold\">\n <mat-error *ngIf=\"addEntityFormGroup.get('attributes').get('humidityAlarmThreshold').hasError('required')\">\n Low humidity threshold is required.\n </mat-error>\n </mat-form-field>\n </div>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || addEntityForm.invalid || !addEntityForm.dirty\">\n Create\n </button>\n </div>\n</form>",
"customCss": ".add-entity-form{\n width: 300px;\n}\n",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\nlet attributeService = $injector.get(widgetContext.servicesMap.get('attributeService'));\n\nopenAddEntityDialog();\n\nfunction openAddEntityDialog() {\n customDialog.customDialog(htmlTemplate, AddEntityDialogController).subscribe();\n}\n\nfunction AddEntityDialogController(instance) {\n let vm = instance;\n \n vm.addEntityFormGroup = vm.fb.group({\n entityName: ['', [vm.validators.required]],\n attributes: vm.fb.group({\n temperatureAlarmFlag: [false],\n temperatureAlarmThreshold: [{value: null, disabled: true}],\n humidityAlarmFlag: [false],\n humidityAlarmThreshold: [{value: null, disabled: true}]\n })\n });\n \n vm.addEntityFormGroup.get('attributes').get('temperatureAlarmFlag').valueChanges\n .subscribe(activate => {\n if (activate) {\n vm.addEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').enable();\n } else {\n vm.addEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').disable();\n }\n });\n \n vm.addEntityFormGroup.get('attributes').get('humidityAlarmFlag').valueChanges\n .subscribe(activate => {\n if (activate) {\n vm.addEntityFormGroup.get('attributes').get('humidityAlarmThreshold').enable();\n } else {\n vm.addEntityFormGroup.get('attributes').get('humidityAlarmThreshold').disable();\n }\n });\n\n vm.save = function() {\n vm.addEntityFormGroup.markAsPristine();\n saveEntityObservable().subscribe(\n function (entity) {\n saveAttributes(entity.id).subscribe(\n function () {\n widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n }\n );\n };\n \n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n \n function saveEntityObservable() {\n const formValues = vm.addEntityFormGroup.value;\n let entity = {\n name: formValues.entityName,\n type: \"thermostat\"\n };\n return deviceService.saveDevice(entity);\n }\n \n function saveAttributes(entityId) {\n let attributes = vm.addEntityFormGroup.get('attributes').value;\n let attributesArray = [];\n for (let key in attributes) {\n if(attributes[key] !== null) {\n attributesArray.push({key: key, value: attributes[key]});\n }\n }\n if (attributesArray.length > 0) {\n return attributeService.saveEntityAttributes(entityId, \"SERVER_SCOPE\", attributesArray);\n } else {\n return widgetContext.rxjs.of([]);\n }\n }\n}",
"customResources": [],
@ -187,7 +187,7 @@
"name": "Edit",
"icon": "edit",
"type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"primary\">\n <h2>Edit thermostat {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div mat-dialog-content class=\"flex flex-col\">\n <mat-form-field class=\"mat-block flex-1\">\n <mat-label>Thermostat name</mat-label>\n <input matInput formControlName=\"entityName\" readonly>\n </mat-form-field>\n <div formGroupName=\"attributes\" class=\"flex flex-col\">\n <mat-slide-toggle formControlName=\"temperatureAlarmFlag\">\n High temperature alarm\n </mat-slide-toggle>\n <mat-form-field class=\"mat-block flex-1\">\n <mat-label>High temperature threshold, °C</mat-label>\n <input type=\"number\" step=\"any\" matInput\n [required] = \"editEntityFormGroup.get('attributes').get('temperatureAlarmFlag').value\"\n formControlName=\"temperatureAlarmThreshold\">\n <mat-error *ngIf=\"editEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').hasError('required')\">\n High temperature threshold is required.\n </mat-error>\n </mat-form-field>\n\n <mat-slide-toggle formControlName=\"humidityAlarmFlag\">\n Low humidity alarm\n </mat-slide-toggle>\n\n <mat-form-field class=\"mat-block flex-1\">\n <mat-label>Low humidity threshold, %</mat-label>\n <input type=\"number\" step=\"any\" matInput\n [required] = \"editEntityFormGroup.get('attributes').get('humidityAlarmFlag').value\"\n formControlName=\"humidityAlarmThreshold\">\n <mat-error *ngIf=\"editEntityFormGroup.get('attributes').get('humidityAlarmThreshold').hasError('required')\">\n Low humidity threshold is required.\n </mat-error>\n </mat-form-field>\n </div>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n </div>\n</form>",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit thermostat {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div mat-dialog-content class=\"flex flex-col\">\n <mat-form-field class=\"mat-block flex-1\">\n <mat-label>Thermostat name</mat-label>\n <input matInput formControlName=\"entityName\" readonly>\n </mat-form-field>\n <div formGroupName=\"attributes\" class=\"flex flex-col\">\n <mat-slide-toggle formControlName=\"temperatureAlarmFlag\">\n High temperature alarm\n </mat-slide-toggle>\n <mat-form-field class=\"mat-block flex-1\">\n <mat-label>High temperature threshold, °C</mat-label>\n <input type=\"number\" step=\"any\" matInput\n [required] = \"editEntityFormGroup.get('attributes').get('temperatureAlarmFlag').value\"\n formControlName=\"temperatureAlarmThreshold\">\n <mat-error *ngIf=\"editEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').hasError('required')\">\n High temperature threshold is required.\n </mat-error>\n </mat-form-field>\n\n <mat-slide-toggle formControlName=\"humidityAlarmFlag\">\n Low humidity alarm\n </mat-slide-toggle>\n\n <mat-form-field class=\"mat-block flex-1\">\n <mat-label>Low humidity threshold, %</mat-label>\n <input type=\"number\" step=\"any\" matInput\n [required] = \"editEntityFormGroup.get('attributes').get('humidityAlarmFlag').value\"\n formControlName=\"humidityAlarmThreshold\">\n <mat-error *ngIf=\"editEntityFormGroup.get('attributes').get('humidityAlarmThreshold').hasError('required')\">\n Low humidity threshold is required.\n </mat-error>\n </mat-form-field>\n </div>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": ".edit-entity-form{\n width: 300px;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet attributeService = $injector.get(widgetContext.servicesMap.get('attributeService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n \n vm.entityId = entityId;\n vm.entityName = entityName;\n vm.attributes = {};\n \n vm.editEntityFormGroup = vm.fb.group({\n entityName: [''],\n attributes: vm.fb.group({\n temperatureAlarmFlag: [false],\n temperatureAlarmThreshold: [{value: null, disabled: true}],\n humidityAlarmFlag: [false],\n humidityAlarmThreshold: [{value: null, disabled: true}]\n })\n });\n \n vm.editEntityFormGroup.get('attributes').get('temperatureAlarmFlag').valueChanges\n .subscribe(activate => {\n if (activate) {\n vm.editEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').enable();\n } else {\n vm.editEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').disable();\n }\n });\n \n vm.editEntityFormGroup.get('attributes').get('humidityAlarmFlag').valueChanges\n .subscribe(activate => {\n if (activate) {\n vm.editEntityFormGroup.get('attributes').get('humidityAlarmThreshold').enable();\n } else {\n vm.editEntityFormGroup.get('attributes').get('humidityAlarmThreshold').disable();\n }\n });\n \n \n getEntityInfo();\n \n \n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveAttributes(entityId).subscribe(\n function () {\n vm.dialogRef.close(null);\n }\n );\n };\n \n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n \n function getEntityAttributes(attributes) {\n for (var i = 0; i < attributes.length; i++) {\n vm.attributes[attributes[i].key] = attributes[i].value;\n }\n }\n \n function getEntityInfo() {\n attributeService.getEntityAttributes(entityId, 'SERVER_SCOPE').subscribe(\n function (attributes) {\n getEntityAttributes(attributes);\n vm.editEntityFormGroup.patchValue({\n entityName: vm.entityName,\n attributes: vm.attributes\n });\n // if(vm.attributes.temperatureAlarmFlag) {\n // vm.editEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').enable();\n // }\n // if(vm.attributes.humidityAlarmFlag) {\n // vm.editEntityFormGroup.get('attributes').get('humidityAlarmThreshold').enable();\n // }\n }\n );\n }\n \n function saveAttributes(entityId) {\n let attributes = vm.editEntityFormGroup.get('attributes').value;\n let attributesArray = [];\n for (let key in attributes) {\n if (attributes[key] !== vm.attributes[key]) {\n attributesArray.push({key: key, value: attributes[key]});\n }\n }\n if (attributesArray.length > 0) {\n return attributeService.saveEntityAttributes(entityId, \"SERVER_SCOPE\", attributesArray);\n } else {\n return widgetContext.rxjs.of([]);\n }\n }\n}",
"customResources": [],

2
application/src/main/data/json/system/widget_types/asset_admin_table.json

File diff suppressed because one or more lines are too long

2
application/src/main/data/json/system/widget_types/device_admin_table.json

File diff suppressed because one or more lines are too long

6
application/src/main/data/resources/dashboards/gateways_dashboard.json

@ -160,7 +160,7 @@
"useShowWidgetActionFunction": null,
"showWidgetActionFunction": "return true;",
"type": "customPretty",
"customHtml": "<div class=\"container\">\n <mat-toolbar class=\"flex flex-row items-center\" color=\"primary\">\n <h2>{{ 'gateway.launch-command' | translate }}</h2>\n <span class=\"flex-1\"></span>\n <div [tb-help]=\"'gatewayInstall'\"></div>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <tb-gateway-command [deviceId]=\"entityId\"></tb-gateway-command>\n <div mat-dialog-actions class=\"flex flex-row justify-end items-center\">\n <button mat-button color=\"primary\" type=\"button\" (click)=\"cancel()\" cdkFocusInitial>\n {{ 'action.close' | translate }}\n </button>\n </div>\n</div>\n",
"customHtml": "<div class=\"container\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row items-center\">\n <h2>{{ 'gateway.launch-command' | translate }}</h2>\n <span class=\"flex-1\"></span>\n <div [tb-help]=\"'gatewayInstall'\"></div>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <tb-gateway-command [deviceId]=\"entityId\"></tb-gateway-command>\n <div mat-dialog-actions class=\"flex flex-row justify-end items-center\">\n <button mat-button color=\"primary\" type=\"button\" (click)=\"cancel()\" cdkFocusInitial>\n {{ 'action.close' | translate }}\n </button>\n </div>\n</div>\n",
"customCss": ".container {\n display: grid;\n grid-template-rows: min-content minmax(auto, 1fr) min-content;\n height: 100%;\n max-height: 100vh;\n width: 600px;\n max-width: 100%;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\n\nopenCommands();\n\nfunction openCommands() {\n customDialog.customDialog(htmlTemplate, CommandsDialogController, {panelClass: \"test\"}).subscribe();\n}\n\nfunction CommandsDialogController(instance) {\n let vm = instance;\n \n vm.entityId = entityId.id;\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n}\n",
"customResources": [
@ -257,7 +257,7 @@
"useShowWidgetActionFunction": null,
"showWidgetActionFunction": "return true;",
"type": "customPretty",
"customHtml": "<form #addEntityForm=\"ngForm\" [formGroup]=\"addEntityFormGroup\"\r\n (ngSubmit)=\"save($event)\" class=\"add-entity-form\">\r\n <mat-toolbar class=\"flex flex-row items-center\" color=\"primary\">\r\n <h2>Add gateway</h2>\r\n <span class=\"flex-1\"></span>\r\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\r\n <mat-icon class=\"material-icons\">close</mat-icon>\r\n </button>\r\n </mat-toolbar>\r\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\r\n </mat-progress-bar>\r\n <div class=\"h-1\" *ngIf=\"!(isLoading$ | async)\"></div>\r\n <div mat-dialog-content class=\"flex flex-col\">\r\n <div class=\"flex flex-row gap-2 flex-wrap\" >\r\n <mat-form-field class=\"w-full sm:w-auto\" appearance=\"outline\">\r\n <mat-label>Name</mat-label>\r\n <input matInput formControlName=\"entityName\" required>\r\n <mat-error *ngIf=\"addEntityFormGroup.get('entityName').hasError('required') || addEntityFormGroup.get('entityName').hasError('pattern')\">\r\n Gateway name is required.\r\n </mat-error>\r\n </mat-form-field>\r\n </div>\r\n <div class=\"flex flex-row gap-2 flex-wrap\">\r\n <tb-entity-subtype-autocomplete\r\n class=\"w-full sm:w-auto\"\r\n formControlName=\"type\"\r\n [required]=\"true\"\r\n [entityType]=\"'DEVICE'\"\r\n appearance=\"outline\"\r\n ></tb-entity-subtype-autocomplete>\r\n </div>\r\n </div>\r\n <div mat-dialog-actions class=\"flex flex-row justify-end items-center\">\r\n <button mat-button color=\"primary\"\r\n type=\"button\"\r\n [disabled]=\"(isLoading$ | async)\"\r\n (click)=\"cancel()\" cdkFocusInitial>\r\n Cancel\r\n </button>\r\n <button mat-button mat-raised-button color=\"primary\"\r\n type=\"submit\"\r\n [disabled]=\"(isLoading$ | async) || addEntityForm.invalid || !addEntityForm.dirty\">\r\n Create\r\n </button>\r\n </div>\r\n</form>\r\n",
"customHtml": "<form #addEntityForm=\"ngForm\" [formGroup]=\"addEntityFormGroup\"\r\n (ngSubmit)=\"save($event)\" class=\"add-entity-form\">\r\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row items-center\">\r\n <h2>Add gateway</h2>\r\n <span class=\"flex-1\"></span>\r\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\r\n <mat-icon class=\"material-icons\">close</mat-icon>\r\n </button>\r\n </mat-toolbar>\r\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\r\n </mat-progress-bar>\r\n <div class=\"h-1\" *ngIf=\"!(isLoading$ | async)\"></div>\r\n <div mat-dialog-content class=\"flex flex-col\">\r\n <div class=\"flex flex-row gap-2 flex-wrap\" >\r\n <mat-form-field class=\"w-full sm:w-auto\" appearance=\"outline\">\r\n <mat-label>Name</mat-label>\r\n <input matInput formControlName=\"entityName\" required>\r\n <mat-error *ngIf=\"addEntityFormGroup.get('entityName').hasError('required') || addEntityFormGroup.get('entityName').hasError('pattern')\">\r\n Gateway name is required.\r\n </mat-error>\r\n </mat-form-field>\r\n </div>\r\n <div class=\"flex flex-row gap-2 flex-wrap\">\r\n <tb-entity-subtype-autocomplete\r\n class=\"w-full sm:w-auto\"\r\n formControlName=\"type\"\r\n [required]=\"true\"\r\n [entityType]=\"'DEVICE'\"\r\n appearance=\"outline\"\r\n ></tb-entity-subtype-autocomplete>\r\n </div>\r\n </div>\r\n <div mat-dialog-actions class=\"flex flex-row justify-end items-center\">\r\n <button mat-button color=\"primary\"\r\n type=\"button\"\r\n [disabled]=\"(isLoading$ | async)\"\r\n (click)=\"cancel()\" cdkFocusInitial>\r\n Cancel\r\n </button>\r\n <button mat-button mat-raised-button color=\"primary\"\r\n type=\"submit\"\r\n [disabled]=\"(isLoading$ | async) || addEntityForm.invalid || !addEntityForm.dirty\">\r\n Create\r\n </button>\r\n </div>\r\n</form>\r\n",
"customCss": ".add-entity-form {\r\n min-width: 400px !important;\r\n}\r\n\r\n.add-entity-form .boolean-value-input {\r\n padding-left: 5px;\r\n}\r\n\r\n.add-entity-form .boolean-value-input .checkbox-label {\r\n margin-bottom: 8px;\r\n color: rgba(0,0,0,0.54);\r\n font-size: 12px;\r\n}\r\n\r\n.relations-list .header {\r\n padding-right: 5px;\r\n padding-bottom: 5px;\r\n padding-left: 5px;\r\n}\r\n\r\n.relations-list .header .cell {\r\n padding-right: 5px;\r\n padding-left: 5px;\r\n font-size: 12px;\r\n font-weight: 700;\r\n color: rgba(0, 0, 0, .54);\r\n white-space: nowrap;\r\n}\r\n\r\n.relations-list .mat-form-field-infix {\r\n width: auto !important;\r\n}\r\n\r\n.relations-list .body {\r\n padding-right: 5px;\r\n padding-bottom: 15px;\r\n padding-left: 5px;\r\n}\r\n\r\n.relations-list .body .row {\r\n padding-top: 5px;\r\n}\r\n\r\n.relations-list .body .cell {\r\n padding-right: 5px;\r\n padding-left: 5px;\r\n}\r\n\r\n.relations-list .body .md-button {\r\n margin: 0;\r\n}\r\n\r\n",
"customFunction": "let $injector = widgetContext.$scope.$injector;\r\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\r\nlet assetService = $injector.get(widgetContext.servicesMap.get('assetService'));\r\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\r\nlet attributeService = $injector.get(widgetContext.servicesMap.get('attributeService'));\r\nlet entityRelationService = $injector.get(widgetContext.servicesMap.get('entityRelationService'));\r\nlet userSettingsService = $injector.get(widgetContext.servicesMap.get('userSettingsService'));\r\n\r\nopenAddEntityDialog();\r\n\r\nfunction openAddEntityDialog() {\r\n customDialog.customDialog(htmlTemplate, AddEntityDialogController).subscribe();\r\n}\r\n\r\nfunction AddEntityDialogController(instance) {\r\n let vm = instance;\r\n let userSettings;\r\n userSettingsService.loadUserSettings().subscribe(settings=> {\r\n userSettings = settings;\r\n if (!userSettings.createdGatewaysCount) userSettings.createdGatewaysCount = 0;\r\n });\r\n \r\n\r\n vm.addEntityFormGroup = vm.fb.group({\r\n entityName: ['', [vm.validators.required, vm.validators.pattern(/.*\\S.*/)]],\r\n entityType: ['DEVICE'],\r\n entityLabel: [''],\r\n type: ['', [vm.validators.required]],\r\n });\r\n\r\n vm.cancel = function() {\r\n vm.dialogRef.close(null);\r\n };\r\n\r\n\r\n vm.save = function($event) {\r\n vm.addEntityFormGroup.markAsPristine();\r\n saveEntityObservable().subscribe(\r\n function (device) {\r\n widgetContext.updateAliases();\r\n userSettingsService.putUserSettings({ createdGatewaysCount: ++userSettings.createdGatewaysCount }).subscribe(_=>{\r\n });\r\n vm.dialogRef.close(null);\r\n openCommandDialog(device, $event);\r\n }\r\n );\r\n };\r\n \r\n function openCommandDialog(device, $event) {\r\n vm.device = device;\r\n let openCommandAction = widgetContext.actionsApi.getActionDescriptors(\"actionCellButton\").find(action => action.name == \"Launch command\");\r\n setTimeout(() => {\r\n widgetContext.actionsApi.handleWidgetAction($event, openCommandAction, device.id, device.name, {newDevice: true});\r\n });\r\n goToConfigState();\r\n }\r\n\r\n \r\n function goToConfigState() {\r\n const stateParams = {};\r\n stateParams.entityId = vm.device.id;\r\n stateParams.entityName = vm.device.name;\r\n const newStateParams = {\r\n targetEntityParamName: 'default',\r\n new_gateway: {\r\n entityId: vm.device.id,\r\n entityName: vm.device.name\r\n }\r\n }\r\n const params = {...stateParams, ...newStateParams};\r\n widgetContext.stateController.openState('gateway_details', params, false);\r\n }\r\n\r\n function saveEntityObservable() {\r\n const formValues = vm.addEntityFormGroup.value;\r\n let entity = {\r\n name: formValues.entityName.trim(),\r\n type: formValues.type,\r\n label: formValues.entityLabel,\r\n additionalInfo: {\r\n gateway: true\r\n }\r\n };\r\n return deviceService.saveDevice(entity);\r\n }\r\n}\r\n",
"customResources": [],
@ -1536,7 +1536,7 @@
"useShowWidgetActionFunction": null,
"showWidgetActionFunction": "return true;",
"type": "customPretty",
"customHtml": "<div class=\"container\">\n <mat-toolbar class=\"flex flex-row items-center\" color=\"primary\">\n <h2>{{ 'gateway.launch-command' | translate }}</h2>\n <span class=\"flex-1\"></span>\n <div [tb-help]=\"'gatewayInstall'\"></div>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <tb-gateway-command [deviceId]=\"entityId\"></tb-gateway-command>\n <div mat-dialog-actions class=\"flex flex-row justify-end items-center\">\n <button mat-button color=\"primary\"\n type=\"button\"\n (click)=\"cancel()\" cdkFocusInitial>\n {{ 'action.close' | translate }}\n </button>\n </div>\n</div>\n",
"customHtml": "<div class=\"container\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row items-center\">\n <h2>{{ 'gateway.launch-command' | translate }}</h2>\n <span class=\"flex-1\"></span>\n <div [tb-help]=\"'gatewayInstall'\"></div>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <tb-gateway-command [deviceId]=\"entityId\"></tb-gateway-command>\n <div mat-dialog-actions class=\"flex flex-row justify-end items-center\">\n <button mat-button color=\"primary\"\n type=\"button\"\n (click)=\"cancel()\" cdkFocusInitial>\n {{ 'action.close' | translate }}\n </button>\n </div>\n</div>\n",
"customCss": ".container {\n display: grid;\n grid-template-rows: min-content minmax(auto, 1fr) min-content;\n height: 100%;\n max-height: 100vh;\n width: 600px;\n max-width: 100%;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\n\nopenCommands();\n\nfunction openCommands() {\n customDialog.customDialog(htmlTemplate, CommandsDialogController, {panelClass: \"test\"}).subscribe();\n}\n\nfunction CommandsDialogController(instance) {\n let vm = instance;\n \n vm.entityId = entityId.id;\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n}\n",
"customResources": [

78
application/src/main/java/org/thingsboard/server/controller/SignUpController.java

@ -2,7 +2,6 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.controller;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.ServiceAccountCredentials;
@ -117,10 +116,6 @@ public class SignUpController extends BaseController {
private static final String MOBILE_APP_BUNDLE_WAS_NOT_FOUND = "Mobile app bundle was not found";
private static final String PRIVACY_POLICY_ACCEPTED = "privacyPolicyAccepted";
private static final String TERMS_OF_USE_ACCEPTED = "termsOfUseAccepted";
private RestTemplate restTemplate;
@Autowired
@ -402,8 +397,9 @@ public class SignUpController extends BaseController {
String encodedPassword = userCredentials.getPassword();
UserCredentials credentials = userService.activateUserCredentials(TenantId.SYS_TENANT_ID, emailCode, encodedPassword);
User user = userService.findUserById(TenantId.SYS_TENANT_ID, credentials.getUserId());
setPrivacyPolicyAccepted(user);
setTermsOfUseAccepted(user);
long acceptedTs = System.currentTimeMillis();
user.setPrivacyPolicyAccepted(acceptedTs);
user.setTermsOfUseAccepted(acceptedTs);
user = userService.saveUser(tenantId, user);
UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
SecurityUser securityUser = new SecurityUser(user, credentials.isEnabled(), principal, getMergedUserPermissions(user, false));
@ -428,23 +424,6 @@ public class SignUpController extends BaseController {
return tokenFactory.createTokenPair(securityUser);
}
private void setPrivacyPolicyAccepted(User user) {
JsonNode additionalInfo = user.getAdditionalInfo();
if (!(additionalInfo instanceof ObjectNode)) {
additionalInfo = JacksonUtil.newObjectNode();
}
((ObjectNode) additionalInfo).put(PRIVACY_POLICY_ACCEPTED, true);
user.setAdditionalInfo(additionalInfo);
}
private boolean isPrivacyPolicyAccepted(User user) {
JsonNode additionalInfo = user.getAdditionalInfo();
if (additionalInfo != null && additionalInfo.has(PRIVACY_POLICY_ACCEPTED)) {
return additionalInfo.get(PRIVACY_POLICY_ACCEPTED).asBoolean();
}
return false;
}
@ApiOperation(value = "Check privacy policy (privacyPolicyAccepted)",
notes = "Checks that current user accepted the privacy policy.")
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@ -453,43 +432,23 @@ public class SignUpController extends BaseController {
Boolean privacyPolicyAccepted() throws ThingsboardException {
SecurityUser securityUser = getCurrentUser();
User user = userService.findUserById(securityUser.getTenantId(), securityUser.getId());
return isPrivacyPolicyAccepted(user);
return user.isPrivacyPolicyAccepted();
}
@ApiOperation(value = "Accept privacy policy (acceptPrivacyPolicy)",
notes = "Accept privacy policy by the current user.")
notes = "Accept privacy policy by the current user. " +
"Stores the acceptance flag 'privacyPolicyAccepted' and the acceptance time 'privacyPolicyAcceptedTs' (epoch milliseconds) " +
"in the user's additional info. Repeated acceptance overwrites the stored time.")
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@PostMapping(value = "/signup/acceptPrivacyPolicy")
public JsonNode acceptPrivacyPolicy() throws ThingsboardException {
public JwtPair acceptPrivacyPolicy() throws ThingsboardException {
SecurityUser securityUser = getCurrentUser();
User user = userService.findUserById(securityUser.getTenantId(), securityUser.getId());
setPrivacyPolicyAccepted(user);
user.setPrivacyPolicyAccepted();
user = userService.saveUser(securityUser.getTenantId(), user);
UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
securityUser = new SecurityUser(user, true, principal, getMergedUserPermissions(user, false));
JwtPair tokenPair = tokenFactory.createTokenPair(securityUser);
ObjectNode tokenObject = JacksonUtil.newObjectNode();
tokenObject.put("token", tokenPair.getToken());
tokenObject.put("refreshToken", tokenPair.getRefreshToken());
return tokenObject;
}
private void setTermsOfUseAccepted(User user) {
JsonNode additionalInfo = user.getAdditionalInfo();
if (!(additionalInfo instanceof ObjectNode)) {
additionalInfo = JacksonUtil.newObjectNode();
}
((ObjectNode) additionalInfo).put(TERMS_OF_USE_ACCEPTED, true);
user.setAdditionalInfo(additionalInfo);
}
private boolean isTermsOfUseAccepted(User user) {
JsonNode additionalInfo = user.getAdditionalInfo();
if (additionalInfo != null && additionalInfo.has(TERMS_OF_USE_ACCEPTED)) {
return additionalInfo.get(TERMS_OF_USE_ACCEPTED).asBoolean();
}
return false;
return tokenFactory.createTokenPair(securityUser);
}
@ApiOperation(value = "Check Terms Of User (termsOfUseAccepted)",
@ -500,26 +459,23 @@ public class SignUpController extends BaseController {
Boolean termsOfUseAccepted() throws ThingsboardException {
SecurityUser securityUser = getCurrentUser();
User user = userService.findUserById(securityUser.getTenantId(), securityUser.getId());
return isTermsOfUseAccepted(user);
return user.isTermsOfUseAccepted();
}
@ApiOperation(value = "Accept Terms of Use (acceptTermsOfUse)",
notes = "Accept Terms of Use by the current user.")
notes = "Accept Terms of Use by the current user. " +
"Stores the acceptance flag 'termsOfUseAccepted' and the acceptance time 'termsOfUseAcceptedTs' (epoch milliseconds) " +
"in the user's additional info. Repeated acceptance overwrites the stored time.")
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@PostMapping(value = "/signup/acceptTermsOfUse")
public JsonNode acceptTermsOfUse() throws ThingsboardException {
public JwtPair acceptTermsOfUse() throws ThingsboardException {
SecurityUser securityUser = getCurrentUser();
User user = userService.findUserById(securityUser.getTenantId(), securityUser.getId());
setTermsOfUseAccepted(user);
user.setTermsOfUseAccepted();
user = userService.saveUser(securityUser.getTenantId(), user);
UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
securityUser = new SecurityUser(user, true, principal, getMergedUserPermissions(user, false));
JwtPair tokenPair = tokenFactory.createTokenPair(securityUser);
ObjectNode tokenObject = JacksonUtil.newObjectNode();
tokenObject.put("token", tokenPair.getToken());
tokenObject.put("refreshToken", tokenPair.getRefreshToken());
return tokenObject;
return tokenFactory.createTokenPair(securityUser);
}
private void validateReCaptcha(String userResponse, String ipAddress, String recaptchaSecretKey) throws ThingsboardException {

91
application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java

@ -11,7 +11,6 @@ import org.springframework.stereotype.Service;
import org.thingsboard.common.util.ExceptionUtil;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.asset.AssetProfile;
@ -35,7 +34,6 @@ import org.thingsboard.server.common.data.id.RuleChainId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.iot_hub.AlarmRuleInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.CalculatedFieldInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.DashboardInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItemDescriptor;
@ -100,7 +98,6 @@ public class DefaultIotHubService implements IotHubService {
private static final String SECTION_RULE_CHAIN_METADATA = "rule chain metadata";
private static final String ITEM_TYPE_WIDGET = "widget";
private static final String ITEM_TYPE_DASHBOARD = "dashboard";
private static final String ITEM_TYPE_CALCULATED_FIELD = "calculated field";
private static final String ITEM_TYPE_ALARM_RULE = "alarm rule";
private static final String ITEM_TYPE_RULE_CHAIN = "rule chain";
@ -183,7 +180,6 @@ public class DefaultIotHubService implements IotHubService {
IotHubInstalledItemDescriptor descriptor = switch (itemType) {
case "WIDGET" -> installWidget(user, tenantId, fileData);
case "DASHBOARD" -> installDashboard(user, tenantId, fileData, data);
case "CALCULATED_FIELD" -> installCalculatedField(user, tenantId, fileData, data);
case "ALARM_RULE" -> installAlarmRule(user, tenantId, fileData, data);
case "RULE_CHAIN" -> installRuleChain(user, tenantId, fileData, data);
@ -244,58 +240,6 @@ public class DefaultIotHubService implements IotHubService {
return descriptor;
}
private DashboardInstalledItemDescriptor installDashboard(SecurityUser user, TenantId tenantId, byte[] fileData, JsonNode data) throws Exception {
Dashboard dashboard;
try {
dashboard = JacksonUtil.fromString(new String(fileData), Dashboard.class, true);
} catch (Exception e) {
throw parseFailure(ACTION_INSTALL, ITEM_TYPE_DASHBOARD, e);
}
dashboard.setId(null);
dashboard.setTenantId(tenantId);
if (data != null && data.hasNonNull("customerId") && data.get("customerId").isTextual()) {
String strCustomerId = data.get("customerId").asText();
if (!strCustomerId.isEmpty()) {
CustomerId customerId = new CustomerId(UUID.fromString(strCustomerId));
Customer customer = customerService.findCustomerById(tenantId, customerId);
if (customer == null) {
throw new IllegalArgumentException("Customer with id [" + customerId + "] is not found");
}
if (!tenantId.equals(customer.getTenantId())) {
throw new IllegalArgumentException("Customer [" + customerId + "] does not belong to the current tenant");
}
dashboard.setCustomerId(customerId);
}
}
List<EntityGroup> entityGroups = null;
if (data != null && data.hasNonNull("entityGroupId") && data.get("entityGroupId").isTextual()) {
String strEntityGroupId = data.get("entityGroupId").asText();
if (!strEntityGroupId.isEmpty()) {
EntityGroupId entityGroupId = new EntityGroupId(UUID.fromString(strEntityGroupId));
EntityGroupInfo entityGroup = checkEntityGroup(user, entityGroupId);
if (entityGroup.getType() != EntityType.DASHBOARD) {
throw new IllegalArgumentException("Entity group [" + entityGroupId + "] is not a dashboard group (type: " + entityGroup.getType() + ")");
}
entityGroups = List.of(entityGroup);
// If the entity group is owned by a customer, align the dashboard owner with the group owner
// (mirrors BaseController.saveGroupEntity logic for new entities).
if (dashboard.getCustomerId() == null || dashboard.getCustomerId().isNullUid()) {
if (entityGroup.getOwnerId().getEntityType() == EntityType.CUSTOMER) {
dashboard.setOwnerId(new CustomerId(entityGroup.getOwnerId().getId()));
}
}
}
}
Dashboard saved = tbDashboardService.save(dashboard, entityGroups, user);
log.debug("[{}] Dashboard installed: {}", tenantId, saved.getTitle());
DashboardInstalledItemDescriptor descriptor = new DashboardInstalledItemDescriptor();
descriptor.setDashboardId(saved.getId());
return descriptor;
}
private EntityGroupInfo checkEntityGroup(SecurityUser user, EntityGroupId entityGroupId) throws ThingsboardException {
EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoById(user.getTenantId(), entityGroupId);
if (entityGroup == null) {
@ -466,7 +410,6 @@ public class DefaultIotHubService implements IotHubService {
}
String itemType = installedItem.getItemType();
IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor();
// Skip checksum validation for solution templates
@ -508,7 +451,6 @@ public class DefaultIotHubService implements IotHubService {
switch (itemType) {
case "WIDGET" -> updateWidget(user, tenantId, (WidgetInstalledItemDescriptor) descriptor, fileData);
case "DASHBOARD" -> updateDashboard(user, tenantId, (DashboardInstalledItemDescriptor) descriptor, fileData);
case "CALCULATED_FIELD" -> updateCalculatedField(user, tenantId, (CalculatedFieldInstalledItemDescriptor) descriptor, fileData);
case "ALARM_RULE" -> updateAlarmRule(user, tenantId, (AlarmRuleInstalledItemDescriptor) descriptor, fileData);
case "RULE_CHAIN" -> updateRuleChain(tenantId, (RuleChainInstalledItemDescriptor) descriptor, fileData);
@ -567,22 +509,6 @@ public class DefaultIotHubService implements IotHubService {
tbWidgetTypeService.save(existing, false, user);
}
private void updateDashboard(SecurityUser user, TenantId tenantId, DashboardInstalledItemDescriptor descriptor, byte[] fileData) throws Exception {
Dashboard newDashboard;
try {
newDashboard = JacksonUtil.fromString(new String(fileData), Dashboard.class, true);
} catch (Exception e) {
throw parseFailure(ACTION_UPDATE, ITEM_TYPE_DASHBOARD, e);
}
Dashboard existing = dashboardService.findDashboardById(tenantId, descriptor.getDashboardId());
if (existing == null) {
throw new Exception("Dashboard not found for update");
}
existing.setTitle(newDashboard.getTitle());
existing.setConfiguration(newDashboard.getConfiguration());
tbDashboardService.save(existing, (List<EntityGroup>) null, user);
}
private void updateCalculatedField(SecurityUser user, TenantId tenantId, CalculatedFieldInstalledItemDescriptor descriptor, byte[] fileData) throws Exception {
CalculatedField newCf;
try {
@ -649,8 +575,6 @@ public class DefaultIotHubService implements IotHubService {
IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor();
if (descriptor instanceof WidgetInstalledItemDescriptor wd) {
return calculateWidgetChecksum(tenantId, wd);
} else if (descriptor instanceof DashboardInstalledItemDescriptor dd) {
return calculateDashboardChecksum(tenantId, dd);
} else if (descriptor instanceof CalculatedFieldInstalledItemDescriptor cd) {
return calculateCalculatedFieldChecksum(tenantId, cd.getCalculatedFieldId());
} else if (descriptor instanceof AlarmRuleInstalledItemDescriptor ad) {
@ -672,16 +596,6 @@ public class DefaultIotHubService implements IotHubService {
return sha256(content);
}
private String calculateDashboardChecksum(TenantId tenantId, DashboardInstalledItemDescriptor descriptor) {
Dashboard dashboard = dashboardService.findDashboardById(tenantId, descriptor.getDashboardId());
if (dashboard == null) {
return null;
}
String content = (dashboard.getTitle() != null ? dashboard.getTitle() : "") +
(dashboard.getConfiguration() != null ? dashboard.getConfiguration().toString() : "");
return sha256(content);
}
private String calculateWidgetChecksum(TenantId tenantId, WidgetInstalledItemDescriptor descriptor) {
WidgetTypeDetails widgetType = widgetTypeService.findWidgetTypeDetailsById(tenantId, descriptor.getWidgetTypeId());
if (widgetType == null) {
@ -865,11 +779,6 @@ public class DefaultIotHubService implements IotHubService {
if (widgetType != null) {
tbWidgetTypeService.delete(widgetType, user);
}
} else if (descriptor instanceof DashboardInstalledItemDescriptor dd) {
Dashboard dashboard = dashboardService.findDashboardById(tenantId, dd.getDashboardId());
if (dashboard != null) {
tbDashboardService.delete(dashboard, user);
}
} else if (descriptor instanceof CalculatedFieldInstalledItemDescriptor cd) {
CalculatedField calculatedField = calculatedFieldService.findById(tenantId, cd.getCalculatedFieldId());
if (calculatedField != null) {

51
application/src/test/java/org/thingsboard/server/controller/SignUpControllerSqlTest.java

@ -14,6 +14,7 @@ import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.CustomerInfo;
import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.DataConstants;
import org.thingsboard.server.common.data.EntityInfo;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.StringUtils;
@ -35,11 +36,11 @@ import org.thingsboard.server.common.data.oauth2.PlatformType;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.selfregistration.DefaultDashboardParams;
import org.thingsboard.server.common.data.selfregistration.HomeDashboardParams;
import org.thingsboard.server.common.data.selfregistration.V2CaptchaParams;
import org.thingsboard.server.common.data.selfregistration.MobileRedirectParams;
import org.thingsboard.server.common.data.selfregistration.MobileSelfRegistrationParams;
import org.thingsboard.server.common.data.selfregistration.SignUpField;
import org.thingsboard.server.common.data.selfregistration.SignUpFieldId;
import org.thingsboard.server.common.data.selfregistration.V2CaptchaParams;
import org.thingsboard.server.common.data.selfregistration.WebSelfRegistrationParams;
import org.thingsboard.server.common.data.signup.SignUpRequest;
import org.thingsboard.server.common.data.signup.SignUpResult;
@ -200,6 +201,38 @@ public class SignUpControllerSqlTest extends AbstractControllerTest {
removeCreatedUser(user);
}
@Test
public void testActivationByEmailCodeStoresPolicyAcceptanceTimestamps() throws Exception {
createWebSelfRegistrationSettings();
doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL));
User user = userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL);
String activateToken = userService.findUserCredentialsByUserId(tenantId, user.getId()).getActivateToken();
doPost("/api/noauth/activateByEmailCode", JsonNode.class, "emailCode", activateToken);
User activatedUser = userService.findUserById(tenantId, user.getId());
assertPrivacyPolicyAccepted(activatedUser);
assertTermsOfUseAccepted(activatedUser);
removeCreatedUser(activatedUser);
}
@Test
public void testAcceptPrivacyPolicyStoresAcceptanceTimestamp() {
doPost("/api/signup/acceptPrivacyPolicy", JsonNode.class);
User user = userService.findUserById(tenantId, tenantAdminUserId);
assertPrivacyPolicyAccepted(user);
}
@Test
public void testAcceptTermsOfUseStoresAcceptanceTimestamp() {
doPost("/api/signup/acceptTermsOfUse", JsonNode.class);
User user = userService.findUserById(tenantId, tenantAdminUserId);
assertTermsOfUseAccepted(user);
}
@Test
public void testSelfRegistrationCreateMessageInRuleChain() throws Exception {
createWebSelfRegistrationSettings();
@ -263,6 +296,22 @@ public class SignUpControllerSqlTest extends AbstractControllerTest {
return signUpRequest;
}
private void assertPrivacyPolicyAccepted(User user) {
assertThat(user.isPrivacyPolicyAccepted()).isTrue();
assertAcceptedTsIsPositive(user, DataConstants.PRIVACY_POLICY_ACCEPTED_TS);
}
private void assertTermsOfUseAccepted(User user) {
assertThat(user.isTermsOfUseAccepted()).isTrue();
assertAcceptedTsIsPositive(user, DataConstants.TERMS_OF_USE_ACCEPTED_TS);
}
private void assertAcceptedTsIsPositive(User user, String acceptedTsKey) {
JsonNode acceptedTs = user.getAdditionalInfo().path(acceptedTsKey);
assertThat(acceptedTs.isNumber()).isTrue();
assertThat(acceptedTs.asLong()).isPositive();
}
protected SignUpRequest createMobileSignUpRequest(String email, String pkgName, String appSecret, PlatformType platformType) {
var signUpRequest = new SignUpRequest();
signUpRequest.setFields(Map.of(SignUpFieldId.EMAIL, email,

12
application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java

@ -15,8 +15,8 @@ import org.mockito.junit.jupiter.MockitoExtension;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.iot_hub.DashboardInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem;
import org.thingsboard.server.common.data.iot_hub.RuleChainInstalledItemDescriptor;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
import org.thingsboard.server.service.security.model.SecurityUser;
@ -89,7 +89,7 @@ class DefaultIotHubServiceTest {
mockTenant();
String versionId = UUID.randomUUID().toString();
String itemId = UUID.randomUUID().toString();
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(version(versionId, itemId, "DASHBOARD", "Root", "1.0"));
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(version(versionId, itemId, "RULE_CHAIN", "Root", "1.0"));
when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of());
InstallPlan plan = service.resolveInstallPlan(user, versionId);
@ -107,7 +107,7 @@ class DefaultIotHubServiceTest {
String versionId = UUID.randomUUID().toString();
String rootItemId = UUID.randomUUID().toString();
String relatedItemId = UUID.randomUUID().toString();
ObjectNode root = version(versionId, rootItemId, "DASHBOARD", "Root", "1.0");
ObjectNode root = version(versionId, rootItemId, "RULE_CHAIN", "Root", "1.0");
root.putArray("relatedItems").add(relatedItemId);
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(root);
when(iotHubRestClient.getPublishedVersionByItemId(relatedItemId))
@ -129,7 +129,7 @@ class DefaultIotHubServiceTest {
String versionId = UUID.randomUUID().toString();
String rootItemId = UUID.randomUUID().toString();
String relatedItemId = UUID.randomUUID().toString();
ObjectNode root = version(versionId, rootItemId, "DASHBOARD", "Root", "1.0");
ObjectNode root = version(versionId, rootItemId, "RULE_CHAIN", "Root", "1.0");
root.putArray("relatedItems").add(relatedItemId);
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(root);
when(iotHubRestClient.getPublishedVersionByItemId(relatedItemId)).thenReturn(null);
@ -149,7 +149,7 @@ class DefaultIotHubServiceTest {
String versionId = UUID.randomUUID().toString();
String rootItemId = UUID.randomUUID().toString();
String relatedItemId = UUID.randomUUID().toString();
ObjectNode root = version(versionId, rootItemId, "DASHBOARD", "Root", "1.0");
ObjectNode root = version(versionId, rootItemId, "RULE_CHAIN", "Root", "1.0");
root.putArray("relatedItems").add(relatedItemId);
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(root);
when(iotHubRestClient.getPublishedVersionByItemId(relatedItemId)).thenThrow(new RuntimeException("boom"));
@ -280,7 +280,7 @@ class DefaultIotHubServiceTest {
when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of());
IotHubInstalledItem depItem = installedItem(UUID.randomUUID());
IotHubInstalledItem rootItem = installedItem(UUID.randomUUID());
DashboardInstalledItemDescriptor rootDescriptor = new DashboardInstalledItemDescriptor();
RuleChainInstalledItemDescriptor rootDescriptor = new RuleChainInstalledItemDescriptor();
rootItem.setDescriptor(rootDescriptor);
doReturn(depItem).when(service).doInstallVersion(eq(user), eq(depVersionId), any(), any());
doReturn(rootItem).when(service).doInstallVersion(eq(user), eq(rootVersionId), any(), any());

5
common/data/src/main/java/org/thingsboard/server/common/data/DataConstants.java

@ -160,6 +160,11 @@ public class DataConstants {
public static final String CF_QUEUE_NAME = "CalculatedFields";
public static final String CF_STATES_QUEUE_NAME = "CalculatedFieldStates";
public static final String PRIVACY_POLICY_ACCEPTED = "privacyPolicyAccepted";
public static final String PRIVACY_POLICY_ACCEPTED_TS = "privacyPolicyAcceptedTs";
public static final String TERMS_OF_USE_ACCEPTED = "termsOfUseAccepted";
public static final String TERMS_OF_USE_ACCEPTED_TS = "termsOfUseAcceptedTs";
public static final String LATEST_TELEMETRY_SCOPE = "LATEST_TELEMETRY";
}

30
common/data/src/main/java/org/thingsboard/server/common/data/User.java

@ -6,6 +6,8 @@ package org.thingsboard.server.common.data;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.BooleanNode;
import com.fasterxml.jackson.databind.node.LongNode;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.EqualsAndHashCode;
import lombok.Getter;
@ -251,6 +253,34 @@ public class User extends BaseDataWithAdditionalInfo<UserId> implements GroupEnt
return !isSystemAdmin() && !isTenantAdmin();
}
@JsonIgnore
public boolean isPrivacyPolicyAccepted() {
return getAdditionalInfoField(DataConstants.PRIVACY_POLICY_ACCEPTED, JsonNode::asBoolean, false);
}
public void setPrivacyPolicyAccepted() {
setPrivacyPolicyAccepted(System.currentTimeMillis());
}
public void setPrivacyPolicyAccepted(long acceptedTs) {
setAdditionalInfoField(DataConstants.PRIVACY_POLICY_ACCEPTED, BooleanNode.TRUE);
setAdditionalInfoField(DataConstants.PRIVACY_POLICY_ACCEPTED_TS, LongNode.valueOf(acceptedTs));
}
@JsonIgnore
public boolean isTermsOfUseAccepted() {
return getAdditionalInfoField(DataConstants.TERMS_OF_USE_ACCEPTED, JsonNode::asBoolean, false);
}
public void setTermsOfUseAccepted() {
setTermsOfUseAccepted(System.currentTimeMillis());
}
public void setTermsOfUseAccepted(long acceptedTs) {
setAdditionalInfoField(DataConstants.TERMS_OF_USE_ACCEPTED, BooleanNode.TRUE);
setAdditionalInfoField(DataConstants.TERMS_OF_USE_ACCEPTED_TS, LongNode.valueOf(acceptedTs));
}
@JsonIgnore
public String getLocale() {
return getAdditionalInfoField("lang", JsonNode::asText, Locale.US.toString());

13
common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DashboardInstalledItemDescriptor.java

@ -1,13 +0,0 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.common.data.iot_hub;
import lombok.Data;
import org.thingsboard.server.common.data.id.DashboardId;
@Data
public class DashboardInstalledItemDescriptor implements IotHubInstalledItemDescriptor {
private DashboardId dashboardId;
}

1
common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/IotHubInstalledItemDescriptor.java

@ -15,7 +15,6 @@ import java.io.Serializable;
property = "type")
@JsonSubTypes({
@Type(name = "WIDGET", value = WidgetInstalledItemDescriptor.class),
@Type(name = "DASHBOARD", value = DashboardInstalledItemDescriptor.class),
@Type(name = "CALCULATED_FIELD", value = CalculatedFieldInstalledItemDescriptor.class),
@Type(name = "ALARM_RULE", value = AlarmRuleInstalledItemDescriptor.class),
@Type(name = "RULE_CHAIN", value = RuleChainInstalledItemDescriptor.class),

188
common/data/src/test/java/org/thingsboard/server/common/data/UserTest.java

@ -0,0 +1,188 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.common.data;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import java.util.function.Consumer;
import java.util.function.ObjLongConsumer;
import java.util.function.Predicate;
import static org.assertj.core.api.Assertions.assertThat;
class UserTest {
private static final long TS = 1_700_000_000_000L;
@Getter
@RequiredArgsConstructor
enum PolicyDocument {
PRIVACY_POLICY(DataConstants.PRIVACY_POLICY_ACCEPTED, DataConstants.PRIVACY_POLICY_ACCEPTED_TS,
User::setPrivacyPolicyAccepted, User::setPrivacyPolicyAccepted, User::isPrivacyPolicyAccepted),
TERMS_OF_USE(DataConstants.TERMS_OF_USE_ACCEPTED, DataConstants.TERMS_OF_USE_ACCEPTED_TS,
User::setTermsOfUseAccepted, User::setTermsOfUseAccepted, User::isTermsOfUseAccepted);
private final String acceptedKey;
private final String acceptedTsKey;
private final Consumer<User> accept;
private final ObjLongConsumer<User> acceptAt;
private final Predicate<User> accepted;
PolicyDocument other() {
return this == PRIVACY_POLICY ? TERMS_OF_USE : PRIVACY_POLICY;
}
}
@ParameterizedTest
@EnumSource(PolicyDocument.class)
void shouldCreateAdditionalInfo_whenAdditionalInfoIsNull(PolicyDocument document) {
// GIVEN
User user = new User();
// WHEN
document.getAcceptAt().accept(user, TS);
// THEN
assertAcceptedAt(user, document, TS);
}
@ParameterizedTest
@EnumSource(PolicyDocument.class)
void shouldReplaceAdditionalInfo_whenAdditionalInfoIsNotObject(PolicyDocument document) {
// GIVEN
User user = new User();
user.setAdditionalInfo(TextNode.valueOf("not an object"));
// WHEN
document.getAcceptAt().accept(user, TS);
// THEN
assertAcceptedAt(user, document, TS);
}
@ParameterizedTest
@EnumSource(PolicyDocument.class)
void shouldPreserveExistingFields_whenAdditionalInfoIsObject(PolicyDocument document) {
// GIVEN
User user = new User();
ObjectNode additionalInfo = JsonNodeFactory.instance.objectNode();
additionalInfo.put("lang", "en_US");
user.setAdditionalInfo(additionalInfo);
// WHEN
document.getAcceptAt().accept(user, TS);
// THEN
assertAcceptedAt(user, document, TS);
assertThat(user.getAdditionalInfo().get("lang").asText()).isEqualTo("en_US");
}
@ParameterizedTest
@EnumSource(PolicyDocument.class)
void shouldOverwriteTimestamp_whenAcceptedAgain(PolicyDocument document) {
// GIVEN
User user = new User();
document.getAcceptAt().accept(user, TS);
// WHEN
document.getAcceptAt().accept(user, TS + 1);
// THEN
assertAcceptedAt(user, document, TS + 1);
}
@ParameterizedTest
@EnumSource(PolicyDocument.class)
void shouldNotTouchOtherDocument(PolicyDocument document) {
// GIVEN
User user = new User();
// WHEN
document.getAcceptAt().accept(user, TS);
// THEN
PolicyDocument other = document.other();
assertThat(user.getAdditionalInfo().has(other.getAcceptedKey())).isFalse();
assertThat(user.getAdditionalInfo().has(other.getAcceptedTsKey())).isFalse();
assertThat(other.getAccepted().test(user)).isFalse();
}
@ParameterizedTest
@EnumSource(PolicyDocument.class)
void shouldStampCurrentTime_whenAcceptedWithoutTimestamp(PolicyDocument document) {
// GIVEN
User user = new User();
long before = System.currentTimeMillis();
// WHEN
document.getAccept().accept(user);
// THEN
long after = System.currentTimeMillis();
assertThat(document.getAccepted().test(user)).isTrue();
assertThat(user.getAdditionalInfo().get(document.getAcceptedTsKey()).asLong()).isBetween(before, after);
}
@ParameterizedTest
@EnumSource(PolicyDocument.class)
void shouldReportAccepted_whenMarked(PolicyDocument document) {
// GIVEN
User user = new User();
document.getAcceptAt().accept(user, TS);
// WHEN-THEN
assertThat(document.getAccepted().test(user)).isTrue();
}
@ParameterizedTest
@EnumSource(PolicyDocument.class)
void shouldReportNotAccepted_whenAdditionalInfoIsNull(PolicyDocument document) {
// GIVEN
User user = new User();
// WHEN-THEN
assertThat(document.getAccepted().test(user)).isFalse();
}
@ParameterizedTest
@EnumSource(PolicyDocument.class)
void shouldReportNotAccepted_whenFlagIsAbsent(PolicyDocument document) {
// GIVEN
User user = new User();
user.setAdditionalInfo(JsonNodeFactory.instance.objectNode());
// WHEN-THEN
assertThat(document.getAccepted().test(user)).isFalse();
}
@ParameterizedTest
@EnumSource(PolicyDocument.class)
void shouldReportNotAccepted_whenFlagIsFalse(PolicyDocument document) {
// GIVEN
User user = new User();
ObjectNode additionalInfo = JsonNodeFactory.instance.objectNode();
additionalInfo.put(document.getAcceptedKey(), false);
user.setAdditionalInfo(additionalInfo);
// WHEN-THEN
assertThat(document.getAccepted().test(user)).isFalse();
}
private static void assertAcceptedAt(User user, PolicyDocument document, long expectedTs) {
JsonNode additionalInfo = user.getAdditionalInfo();
assertThat(additionalInfo).isInstanceOf(ObjectNode.class);
assertThat(additionalInfo.get(document.getAcceptedKey()).asBoolean()).isTrue();
assertThat(additionalInfo.get(document.getAcceptedTsKey()).asLong()).isEqualTo(expectedTs);
assertThat(document.getAccepted().test(user)).isTrue();
}
}

3
common/edge-api/src/main/proto/edge.proto

@ -41,6 +41,7 @@ enum EdgeVersion {
V_4_2_2_4 = 4224;
V_4_2_2_5 = 4225;
V_4_2_2_6 = 4226;
V_4_2_2_7 = 4227;
V_4_3_0_1 = 15;
V_4_3_1 = 4310;
V_4_3_1_1 = 4311;
@ -49,7 +50,9 @@ enum EdgeVersion {
V_4_3_1_4 = 4314;
V_4_3_1_5 = 4315;
V_4_3_1_6 = 4316;
V_4_3_1_7 = 4317;
V_4_4_0 = 4400;
V_4_4_0_1 = 4401;
V_LATEST = 99999;
}

4
msa/black-box-tests/pom.xml

@ -128,10 +128,6 @@
<artifactId>awaitility</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.californium</groupId>
<artifactId>californium-core</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>

45
ui-ngx/src/app/core/http/iot-hub-api.service.ts

@ -7,7 +7,11 @@ import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { PageData } from '@shared/models/page/page-data';
import { PageLink } from '@shared/models/page/page-link';
import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models';
import {
MpItemVersionQuery,
MpItemVersionQueryOptions,
MpItemVersionView
} from '@shared/models/iot-hub/iot-hub-version.models';
import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models';
import { IotHubInstalledItem, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { ItemType, ItemTypeFilterInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models';
@ -70,36 +74,47 @@ export class IotHubApiService {
}
public getPublishedVersions(query: MpItemVersionQuery, config?: IotHubRequestConfig): Observable<PageData<MpItemVersionView>> {
if (query.options.tbVersion == null) {
query.options.tbVersion = tbVersionToInt(env.tbVersion);
}
if (query.options.ceOnly == null) {
query.options.ceOnly = false;
}
this.applyPlatformFilters(query.options);
return this.http.get<PageData<MpItemVersionView>>(
`${this.baseUrl}/api/versions/published${query.toQuery()}`,
{ params: this.buildParams(config) }
);
}
/** What this platform can install: items of every edition, nothing built for a newer ThingsBoard. */
private platformScope(): { ceOnly: boolean; tbVersion: number } {
return { ceOnly: false, tbVersion: tbVersionToInt(env.tbVersion) };
}
/** Fills in the platform scope wherever the caller did not set it. */
private applyPlatformFilters(options: MpItemVersionQueryOptions): void {
const scope = this.platformScope();
options.tbVersion ??= scope.tbVersion;
options.ceOnly ??= scope.ceOnly;
}
private platformScopeParams(): string[] {
const scope = this.platformScope();
return [`ceOnly=${scope.ceOnly}`, `tbVersion=${scope.tbVersion}`];
}
public getFilterInfo(itemType: ItemType, config?: IotHubRequestConfig): Observable<ItemTypeFilterInfo> {
const url = `${this.baseUrl}/api/item-listing/filterInfo/${itemType}`
+ `?ceOnly=false&tbVersion=${tbVersionToInt(env.tbVersion)}`;
const url = `${this.baseUrl}/api/item-listing/filterInfo/${itemType}?${this.platformScopeParams().join('&')}`;
return this.http.get<ItemTypeFilterInfo>(url, { params: this.buildParams(config) });
}
public getWidgetCategories(textSearch?: string, scadaFirst?: boolean,
public getWidgetCategories(textSearch?: string, scadaFirst?: boolean, creatorVerified?: boolean,
config?: IotHubRequestConfig): Observable<WidgetCategory[]> {
const queryParams: string[] = [
`ceOnly=false`,
`tbVersion=${tbVersionToInt(env.tbVersion)}`
];
const queryParams: string[] = this.platformScopeParams();
if (textSearch?.trim()) {
queryParams.push(`textSearch=${encodeURIComponent(textSearch.trim())}`);
}
if (scadaFirst != null) {
queryParams.push(`scadaFirst=${scadaFirst}`);
}
if (creatorVerified) {
queryParams.push(`creatorVerified=true`);
}
const url = `${this.baseUrl}/api/item-listing/widgetCategories?${queryParams.join('&')}`;
return this.http.get<WidgetCategory[]>(url, { params: this.buildParams(config) });
}
@ -133,7 +148,7 @@ export class IotHubApiService {
public getListingItemVersion(slug: string, config?: IotHubRequestConfig): Observable<MpItemVersionView> {
const queryParams = [
'ce=false',
`tbVersion=${tbVersionToInt(env.tbVersion)}`
`tbVersion=${this.platformScope().tbVersion}`
];
return this.http.get<MpItemVersionView>(
`${this.baseUrl}/api/listings/public/by-slug/${encodeURIComponent(slug)}/item-version?${queryParams.join('&')}`,

2
ui-ngx/src/app/core/http/white-labeling.service.ts

@ -210,7 +210,7 @@ export class WhiteLabelingService {
}
public isPrimaryColorPanels(): boolean {
return this.getCurrentWlParams() ? this.getCurrentWlParams().primaryColorPanels : false;
return !!this.getCurrentWlParams()?.primaryColorPanels;
}
public isPrimaryColorPanels$(): Observable<boolean> {

37
ui-ngx/src/app/core/services/resources.service.ts

@ -17,7 +17,7 @@ import {
DOCUMENT
} from '@angular/core';
import { forkJoin, from, Observable, ReplaySubject, throwError } from 'rxjs';
import { forkJoin, from, Observable, of, ReplaySubject, throwError } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { IModulesMap } from '@modules/common/modules-map.models';
import { TbResourceId } from '@shared/models/id/tb-resource-id';
@ -26,7 +26,7 @@ import { AuthService } from '@core/auth/auth.service';
import { select, Store } from '@ngrx/store';
import { selectIsAuthenticated } from '@core/auth/auth.selectors';
import { AppState } from '@core/core.state';
import { map, tap } from 'rxjs/operators';
import { catchError, map, switchMap, tap } from 'rxjs/operators';
import { RequestConfig } from '@core/http/http-utils';
import { isJSResource, removeTbResourcePrefix } from '@shared/models/resource.models';
@ -96,6 +96,22 @@ const resourceFileType = (url: string, baseUrl: string): string => {
return /^(css|js)\d*$/.exec(segment)?.[1];
};
// The file type of a resource served under a URL that does not tell it, as Google Fonts' /icon, from the Content-Type
// of a HEAD response. Works only for same-origin URLs and servers that allow cross-origin requests.
const resourceFileTypeFromContentType = (url: string): Observable<string> =>
from(fetch(url, {method: 'HEAD'})).pipe(
map(response => {
const mimeType = response.headers.get('content-type')?.split(';')[0].trim().toLowerCase();
if (mimeType === 'text/css') {
return 'css';
} else if (/^(text|application)\/(x-)?(javascript|ecmascript)$/.test(mimeType)) {
return 'js';
}
return undefined;
}),
catchError(() => of(undefined))
);
const matchesSelector = (selectors: ɵCssSelectorList, selector: string) =>
selectors.some(s => s.some(s1 => typeof s1 === 'string' && s1 === selector));
@ -160,12 +176,17 @@ export class ResourcesService {
}
const fileType = resourceFileType(url, this.document.baseURI);
if (!fileType) {
return throwError(() => new Error(`Unable to detect file type from url: ${url}`));
} else if (fileType !== 'css' && fileType !== 'js') {
return throwError(() => new Error(`Unsupported file type: ${fileType}`));
}
return this.loadResourceByType(fileType, url);
const fileType$ = fileType ? of(fileType) : resourceFileTypeFromContentType(url);
return fileType$.pipe(
switchMap(type => {
if (!type) {
return throwError(() => new Error(`Unable to detect file type from url: ${url}`));
} else if (type !== 'css' && type !== 'js') {
return throwError(() => new Error(`Unsupported file type: ${type}`));
}
return this.loadedResources[url] ? this.loadedResources[url].asObservable() : this.loadResourceByType(type, url);
})
);
}
public downloadResource(downloadUrl: string, config?: RequestConfig): Observable<any> {

195
ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.html

@ -85,12 +85,12 @@
}
@if (selectWidgetMode === 'iotHub' && iotHubSubMode !== 'default') {
<button mat-button type="button" class="tb-widget-select-sort" [matMenuTriggerFor]="sortMenu">
{{ iotHubSortOptions[iotHubSelectedSortIndex].label | translate }}
{{ iotHubSelectedSort.label | translate }}
<mat-icon iconPositionEnd>arrow_drop_down</mat-icon>
</button>
<mat-menu #sortMenu="matMenu">
@for (option of iotHubSortOptions; track option.value; let i = $index) {
<button mat-menu-item (click)="onIotHubSortChange(i)">{{ option.label | translate }}</button>
@for (option of iotHubSortOptions; track option.value) {
<button mat-menu-item (click)="onIotHubSortChange(option)">{{ option.label | translate }}</button>
}
</mat-menu>
}
@ -462,120 +462,129 @@
</div>
}
} @else {
<mat-expansion-panel [expanded]="true">
<mat-expansion-panel-header>
<mat-panel-title>
{{ 'iot-hub.type' | translate }}
@if (iotHubAppliedWidgetTypes.size) {
<span class="tb-iot-hub-filter-badge">{{ iotHubAppliedWidgetTypes.size }}</span>
}
</mat-panel-title>
</mat-expansion-panel-header>
@if (iotHubWidgetTypeOptions.length >= 10) {
<div class="tb-iot-hub-filter-search">
<mat-icon>search</mat-icon>
<input [placeholder]="'iot-hub.search' | translate"
[ngModel]="iotHubFilterSearch['widgetType']"
(ngModelChange)="iotHubFilterSearch['widgetType'] = $event">
@if (iotHubFilterSearch['widgetType']) {
<button mat-icon-button class="tb-iot-hub-filter-search-clear" (click)="iotHubFilterSearch['widgetType'] = ''">
<mat-icon>close</mat-icon>
</button>
}
</div>
}
<div class="tb-iot-hub-filter-items" [class.scrollable]="getFilteredIotHubItems(iotHubWidgetTypeOptions, 'widgetType').length > 8"
(mouseenter)="getFilteredIotHubItems(iotHubWidgetTypeOptions, 'widgetType').length > 8 && (iotHubFilterItemsHovered = true)"
(mouseleave)="iotHubFilterItemsHovered = false">
@for (opt of getFilteredIotHubItems(iotHubWidgetTypeOptions, 'widgetType'); track opt.key) {
<div class="tb-iot-hub-filter-option">
<mat-checkbox [checked]="iotHubAppliedWidgetTypes.has(opt.key)"
(change)="toggleIotHubWidgetType(opt.key)">
{{ getIotHubWidgetTypeLabel(opt.key) }}
</mat-checkbox>
</div>
}
</div>
</mat-expansion-panel>
@if (!hideCategoriesFilterSection) {
<div class="tb-iot-hub-filter-option">
<mat-checkbox [checked]="iotHubVerifiedCreatorsOnly"
(change)="toggleIotHubVerifiedCreators()">
{{ 'iot-hub.verified-creators-only' | translate }}
</mat-checkbox>
</div>
@if (iotHubSubMode !== 'default') {
<mat-divider></mat-divider>
<mat-expansion-panel [expanded]="false">
<mat-expansion-panel [expanded]="true">
<mat-expansion-panel-header>
<mat-panel-title>
{{ 'iot-hub.category' | translate }}
@if (iotHubAppliedCategories.size) {
<span class="tb-iot-hub-filter-badge">{{ iotHubAppliedCategories.size }}</span>
{{ 'iot-hub.type' | translate }}
@if (iotHubAppliedWidgetTypes.size) {
<span class="tb-iot-hub-filter-badge">{{ iotHubAppliedWidgetTypes.size }}</span>
}
</mat-panel-title>
</mat-expansion-panel-header>
@if (iotHubCategoryOptions.length >= 10) {
@if (iotHubWidgetTypeOptions.length >= 10) {
<div class="tb-iot-hub-filter-search">
<mat-icon>search</mat-icon>
<input [placeholder]="'iot-hub.search' | translate"
[ngModel]="iotHubFilterSearch['category']"
(ngModelChange)="iotHubFilterSearch['category'] = $event">
@if (iotHubFilterSearch['category']) {
<button mat-icon-button class="tb-iot-hub-filter-search-clear" (click)="iotHubFilterSearch['category'] = ''">
[ngModel]="iotHubFilterSearch['widgetType']"
(ngModelChange)="iotHubFilterSearch['widgetType'] = $event">
@if (iotHubFilterSearch['widgetType']) {
<button mat-icon-button class="tb-iot-hub-filter-search-clear" (click)="iotHubFilterSearch['widgetType'] = ''">
<mat-icon>close</mat-icon>
</button>
}
</div>
}
<div class="tb-iot-hub-filter-items" [class.scrollable]="getFilteredIotHubItems(iotHubCategoryOptions, 'category').length > 8"
(mouseenter)="getFilteredIotHubItems(iotHubCategoryOptions, 'category').length > 8 && (iotHubFilterItemsHovered = true)"
<div class="tb-iot-hub-filter-items" [class.scrollable]="getFilteredIotHubItems(iotHubWidgetTypeOptions, 'widgetType').length > 8"
(mouseenter)="getFilteredIotHubItems(iotHubWidgetTypeOptions, 'widgetType').length > 8 && (iotHubFilterItemsHovered = true)"
(mouseleave)="iotHubFilterItemsHovered = false">
@for (opt of getFilteredIotHubItems(iotHubCategoryOptions, 'category'); track opt.key) {
@for (opt of getFilteredIotHubItems(iotHubWidgetTypeOptions, 'widgetType'); track opt.key) {
<div class="tb-iot-hub-filter-option">
<mat-checkbox [checked]="iotHubAppliedCategories.has(opt.key)"
(change)="toggleIotHubCategory(opt.key)">
{{ opt.key }}
<mat-checkbox [checked]="iotHubAppliedWidgetTypes.has(opt.key)"
(change)="toggleIotHubWidgetType(opt.key)">
{{ getIotHubWidgetTypeLabel(opt.key) }}
</mat-checkbox>
</div>
}
</div>
</mat-expansion-panel>
}
<mat-divider></mat-divider>
<mat-expansion-panel [expanded]="false">
<mat-expansion-panel-header>
<mat-panel-title>
{{ 'iot-hub.use-case' | translate }}
@if (iotHubAppliedUseCases.size) {
<span class="tb-iot-hub-filter-badge">{{ iotHubAppliedUseCases.size }}</span>
}
</mat-panel-title>
</mat-expansion-panel-header>
@if (iotHubUseCaseOptions.length >= 10) {
<div class="tb-iot-hub-filter-search">
<mat-icon>search</mat-icon>
<input [placeholder]="'iot-hub.search' | translate"
[ngModel]="iotHubFilterSearch['useCase']"
(ngModelChange)="iotHubFilterSearch['useCase'] = $event">
@if (iotHubFilterSearch['useCase']) {
<button mat-icon-button class="tb-iot-hub-filter-search-clear" (click)="iotHubFilterSearch['useCase'] = ''">
<mat-icon>close</mat-icon>
</button>
}
</div>
}
<div class="tb-iot-hub-filter-items" [class.scrollable]="getFilteredIotHubItems(iotHubUseCaseOptions, 'useCase').length > 8"
(mouseenter)="getFilteredIotHubItems(iotHubUseCaseOptions, 'useCase').length > 8 && (iotHubFilterItemsHovered = true)"
(mouseleave)="iotHubFilterItemsHovered = false">
@for (group of getGroupedIotHubFilterItems(iotHubUseCaseOptions, 'useCase'); track group.label) {
@if (group.label) {
<div class="tb-iot-hub-filter-group-label">{{ group.label | translate }}</div>
}
@for (opt of group.items; track opt.key) {
<div class="tb-iot-hub-filter-option">
<mat-checkbox [checked]="iotHubAppliedUseCases.has(opt.key)"
(change)="toggleIotHubUseCase(opt.key)">
{{ opt.key }}
</mat-checkbox>
@if (!hideCategoriesFilterSection) {
<mat-divider></mat-divider>
<mat-expansion-panel [expanded]="false">
<mat-expansion-panel-header>
<mat-panel-title>
{{ 'iot-hub.category' | translate }}
@if (iotHubAppliedCategories.size) {
<span class="tb-iot-hub-filter-badge">{{ iotHubAppliedCategories.size }}</span>
}
</mat-panel-title>
</mat-expansion-panel-header>
@if (iotHubCategoryOptions.length >= 10) {
<div class="tb-iot-hub-filter-search">
<mat-icon>search</mat-icon>
<input [placeholder]="'iot-hub.search' | translate"
[ngModel]="iotHubFilterSearch['category']"
(ngModelChange)="iotHubFilterSearch['category'] = $event">
@if (iotHubFilterSearch['category']) {
<button mat-icon-button class="tb-iot-hub-filter-search-clear" (click)="iotHubFilterSearch['category'] = ''">
<mat-icon>close</mat-icon>
</button>
}
</div>
}
<div class="tb-iot-hub-filter-items" [class.scrollable]="getFilteredIotHubItems(iotHubCategoryOptions, 'category').length > 8"
(mouseenter)="getFilteredIotHubItems(iotHubCategoryOptions, 'category').length > 8 && (iotHubFilterItemsHovered = true)"
(mouseleave)="iotHubFilterItemsHovered = false">
@for (opt of getFilteredIotHubItems(iotHubCategoryOptions, 'category'); track opt.key) {
<div class="tb-iot-hub-filter-option">
<mat-checkbox [checked]="iotHubAppliedCategories.has(opt.key)"
(change)="toggleIotHubCategory(opt.key)">
{{ opt.key }}
</mat-checkbox>
</div>
}
</div>
</mat-expansion-panel>
}
<mat-divider></mat-divider>
<mat-expansion-panel [expanded]="false">
<mat-expansion-panel-header>
<mat-panel-title>
{{ 'iot-hub.use-case' | translate }}
@if (iotHubAppliedUseCases.size) {
<span class="tb-iot-hub-filter-badge">{{ iotHubAppliedUseCases.size }}</span>
}
</mat-panel-title>
</mat-expansion-panel-header>
@if (iotHubUseCaseOptions.length >= 10) {
<div class="tb-iot-hub-filter-search">
<mat-icon>search</mat-icon>
<input [placeholder]="'iot-hub.search' | translate"
[ngModel]="iotHubFilterSearch['useCase']"
(ngModelChange)="iotHubFilterSearch['useCase'] = $event">
@if (iotHubFilterSearch['useCase']) {
<button mat-icon-button class="tb-iot-hub-filter-search-clear" (click)="iotHubFilterSearch['useCase'] = ''">
<mat-icon>close</mat-icon>
</button>
}
</div>
}
</div>
</mat-expansion-panel>
<div class="tb-iot-hub-filter-items" [class.scrollable]="getFilteredIotHubItems(iotHubUseCaseOptions, 'useCase').length > 8"
(mouseenter)="getFilteredIotHubItems(iotHubUseCaseOptions, 'useCase').length > 8 && (iotHubFilterItemsHovered = true)"
(mouseleave)="iotHubFilterItemsHovered = false">
@for (group of getGroupedIotHubFilterItems(iotHubUseCaseOptions, 'useCase'); track group.label) {
@if (group.label) {
<div class="tb-iot-hub-filter-group-label">{{ group.label | translate }}</div>
}
@for (opt of group.items; track opt.key) {
<div class="tb-iot-hub-filter-option">
<mat-checkbox [checked]="iotHubAppliedUseCases.has(opt.key)"
(change)="toggleIotHubUseCase(opt.key)">
{{ opt.key }}
</mat-checkbox>
</div>
}
}
</div>
</mat-expansion-panel>
}
}
</div>
</div>

79
ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts

@ -35,7 +35,14 @@ import {
MpItemVersionView,
widgetTypeTranslations
} from '@shared/models/iot-hub/iot-hub-version.models';
import { FilterParamInfo, ItemType, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models';
import {
FilterParamInfo,
IOT_HUB_SORT_OPTIONS,
ItemType,
RELEVANCE_SORT_PROPERTY,
SortOption,
WidgetCategory
} from '@shared/models/iot-hub/iot-hub-item.models';
import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service';
@ -54,16 +61,13 @@ import { getCurrentAuthUser } from '@core/auth/auth.selectors';
import { Authority } from '@shared/models/authority.enum';
import { WhiteLabelingService } from '@core/http/white-labeling.service';
/** The Installed list is sorted locally, and only the Hub can rank by relevance. */
const INSTALLED_SORT_OPTIONS = IOT_HUB_SORT_OPTIONS.filter(o => o.value !== RELEVANCE_SORT_PROPERTY);
type selectWidgetMode = 'installed' | 'iotHub';
type installedSubMode = 'default' | 'allWidgets';
type iotHubSubMode = 'default' | 'allWidgets' | 'installed' | 'category';
interface WidgetSelectSortOption {
value: string;
label: string;
direction: Direction;
}
const LOGICAL_ALL_WIDGETS = '__logical_all_widgets__';
const LOGICAL_INSTALLED_FROM_IOT_HUB = '__logical_installed_from_iot_hub__';
@ -111,12 +115,7 @@ export class DashboardWidgetSelectComponent {
includeDeprecated = false;
searchFocused = false;
iotHubSortOptions: WidgetSelectSortOption[] = [
{ value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC },
{ value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC },
{ value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC }
];
iotHubSelectedSortIndex = 0;
private iotHubSelectedSortValue = IOT_HUB_SORT_OPTIONS[0].value;
@Input()
aliasController: IAliasController;
@ -160,6 +159,7 @@ export class DashboardWidgetSelectComponent {
this.iotHubAppliedWidgetTypes.clear();
this.iotHubAppliedCategories.clear();
this.iotHubAppliedUseCases.clear();
this.iotHubVerifiedCreatorsOnly = false;
this.iotHubFilterCount = 0;
}
}
@ -283,6 +283,7 @@ export class DashboardWidgetSelectComponent {
iotHubAppliedWidgetTypes = new Set<string>();
iotHubAppliedCategories = new Set<string>();
iotHubAppliedUseCases = new Set<string>();
iotHubVerifiedCreatorsOnly = false;
iotHubWidgetTypeOptions: FilterParamInfo[] = [];
iotHubCategoryOptions: FilterParamInfo[] = [];
@ -330,7 +331,7 @@ export class DashboardWidgetSelectComponent {
this.iotHubWidgetsFetchFunction = (pageSize, page, filter) => {
const search = typeof filter === 'string' ? filter.split('|')[0] : filter;
const sort = this.iotHubSortOptions[this.iotHubSelectedSortIndex];
const sort = this.iotHubSelectedSort;
const sortOrder: SortOrder = { property: sort.value, direction: sort.direction };
const pageLink = new PageLink(pageSize, page, search || null, sortOrder);
const effectiveCategories = this.iotHubSelectedCategory
@ -341,7 +342,8 @@ export class DashboardWidgetSelectComponent {
categories: effectiveCategories,
useCases: this.iotHubAppliedUseCases.size > 0 ? Array.from(this.iotHubAppliedUseCases) : undefined,
widgetTypes: this.iotHubAppliedWidgetTypes.size > 0 ? Array.from(this.iotHubAppliedWidgetTypes) : undefined,
scadaFirst: this.scadaFirst ? true : undefined
scadaFirst: this.scadaFirst ? true : undefined,
creatorVerified: this.iotHubVerifiedCreatorsOnly
});
return this.iotHubApiService.getPublishedVersions(query, { ignoreLoading: true });
};
@ -364,7 +366,8 @@ export class DashboardWidgetSelectComponent {
this.iotHubDefaultFetchFunction = (pageSize, page, filter) => {
const search = typeof filter === 'string' ? filter.split('|')[0] : filter;
return this.iotHubApiService.getWidgetCategories(search || undefined,
this.scadaFirst ? true : undefined, { ignoreLoading: true }).pipe(
this.scadaFirst ? true : undefined,
this.iotHubVerifiedCreatorsOnly, { ignoreLoading: true }).pipe(
map(categories => ({
data: categories.slice(page * pageSize, page * pageSize + pageSize),
totalPages: Math.ceil(categories.length / pageSize),
@ -581,11 +584,19 @@ export class DashboardWidgetSelectComponent {
this.onIotHubFiltersChanged();
}
toggleIotHubVerifiedCreators(): void {
this.iotHubVerifiedCreatorsOnly = !this.iotHubVerifiedCreatorsOnly;
this.loadWidgetCategories();
this.onIotHubFiltersChanged();
}
clearIotHubFilters(): void {
this.iotHubAppliedWidgetTypes.clear();
this.iotHubAppliedCategories.clear();
this.iotHubAppliedUseCases.clear();
this.iotHubVerifiedCreatorsOnly = false;
this.iotHubFilterSearch = {};
this.loadWidgetCategories();
this.onIotHubFiltersChanged();
}
@ -593,13 +604,27 @@ export class DashboardWidgetSelectComponent {
this.iotHubFilterCount =
this.iotHubAppliedWidgetTypes.size +
(this.iotHubSelectedCategory ? 0 : this.iotHubAppliedCategories.size) +
this.iotHubAppliedUseCases.size;
this.iotHubAppliedUseCases.size +
(this.iotHubVerifiedCreatorsOnly ? 1 : 0);
this.reloadIotHubWidgets();
}
onIotHubSortChange(index: number): void {
if (this.iotHubSelectedSortIndex !== index) {
this.iotHubSelectedSortIndex = index;
get iotHubSortOptions(): SortOption[] {
return this.iotHubSubMode === 'installed' ? INSTALLED_SORT_OPTIONS : IOT_HUB_SORT_OPTIONS;
}
/** The chosen sort, or the list's first option where the chosen one is not offered. */
get iotHubSelectedSort(): SortOption {
const options = this.iotHubSortOptions;
return options.find(o => o.value === this.iotHubSelectedSortValue) ?? options[0];
}
onIotHubSortChange(option: SortOption): void {
// Store the choice even when it is already the effective sort (the Installed list's fallback
// for relevance), so it survives a switch back to the IoT Hub list; reload only on a change.
const effective = this.iotHubSelectedSort.value;
this.iotHubSelectedSortValue = option.value;
if (effective !== option.value) {
this.installedWidgetVersions = null;
this.reloadIotHubWidgets();
}
@ -609,6 +634,9 @@ export class DashboardWidgetSelectComponent {
if (this.selectWidgetMode === 'installed') {
return (this.filterWidgetTypes?.length ?? 0) + (this.includeDeprecated ? 1 : 0);
}
if (this.iotHubSubMode === 'default') {
return this.iotHubVerifiedCreatorsOnly ? 1 : 0;
}
return this.iotHubFilterCount;
}
@ -618,7 +646,8 @@ export class DashboardWidgetSelectComponent {
}
return this.iotHubAppliedWidgetTypes.size > 0
|| this.iotHubAppliedCategories.size > 0
|| this.iotHubAppliedUseCases.size > 0;
|| this.iotHubAppliedUseCases.size > 0
|| this.iotHubVerifiedCreatorsOnly;
}
clearAllFilters(): void {
@ -657,7 +686,8 @@ export class DashboardWidgetSelectComponent {
isFilterVisible(): boolean {
if (this.selectWidgetMode === 'iotHub') {
return this.iotHubSubMode !== 'default';
// The category landing honours only the verified filter, so the button stays while it is on
return this.iotHubSubMode !== 'default' || this.iotHubVerifiedCreatorsOnly;
}
return this.installedSubMode === 'allWidgets' || this.widgetsBundle !== null;
}
@ -869,6 +899,9 @@ export class DashboardWidgetSelectComponent {
if (this.iotHubAppliedUseCases.size > 0) {
filtered = filtered.filter(v => v.useCases?.some(u => this.iotHubAppliedUseCases.has(u)));
}
if (this.iotHubVerifiedCreatorsOnly) {
filtered = filtered.filter(v => v.creatorVerified);
}
filtered = this.sortInstalledVersions(filtered);
const start = page * pageSize;
const data = filtered.slice(start, start + pageSize);
@ -876,7 +909,7 @@ export class DashboardWidgetSelectComponent {
}
private sortInstalledVersions(versions: MpItemVersionView[]): MpItemVersionView[] {
const sort = this.iotHubSortOptions[this.iotHubSelectedSortIndex];
const sort = this.iotHubSelectedSort;
const sign = sort.direction === Direction.ASC ? 1 : -1;
const copy = [...versions];
copy.sort((a, b) => {

5
ui-ngx/src/app/modules/home/components/entity/entity-chips.component.html

@ -1,11 +1,12 @@
<!--
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
-->
@for (subEntity of subEntities; track subEntity) {
<a class="tb-entity-chip"
<a class="tb-entity-chip" [tbTruncateWithTooltip]="subEntity.name | customTranslate"
routerLink="{{entityDetailsPrefixUrl}}/{{subEntity.id.id}}" (click)="$event.stopPropagation();">
{{ subEntity.name | customTranslate }}
</a>

6
ui-ngx/src/app/modules/home/components/entity/entity-chips.component.scss

@ -1,11 +1,15 @@
// 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
:host {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 4px 0;
width: 0;
min-width: 100%;
a.tb-entity-chip {
max-width: 100%;
padding: 4px 8px;
border-radius: 12px;
line-height: 16px;

30
ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss

@ -119,3 +119,33 @@
pointer-events: none;
}
}
// Scroll area whose thumb shows only while the container is hovered (the filter panels').
@mixin tb-iot-hub-hover-scrollbar {
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background-color: transparent;
}
&::-webkit-scrollbar-thumb {
background-color: transparent;
border-radius: 3px;
}
&:hover {
&::-webkit-scrollbar-track {
background-color: rgba(0, 0, 0, 0.04);
}
&::-webkit-scrollbar-thumb {
background-color: rgba(0, 0, 0, 0.2);
&:hover {
background-color: rgba(0, 0, 0, 0.35);
}
}
}
}

3
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html

@ -199,7 +199,8 @@
<div mat-dialog-content>
<mat-stepper #installStepper
[linear]="true"
labelPosition="bottom">
labelPosition="bottom"
(selectionChange)="onStepSelectionChange($event)">
<ng-template matStepperIcon="edit">
<mat-icon>done</mat-icon>
</ng-template>

38
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts

@ -9,6 +9,7 @@ import { AppState } from '@core/core.state';
import { DialogComponent } from '@shared/components/dialog.component';
import { UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms';
import { MatStepper } from '@angular/material/stepper';
import { StepperSelectionEvent } from '@angular/cdk/stepper';
import { firstValueFrom } from 'rxjs';
import { TranslateService } from '@ngx-translate/core';
import { PageLink } from '@shared/models/page/page-link';
@ -252,10 +253,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
connectivityStep.completed = true;
this.cdr.detectChanges();
// Wait for new mat-step children to register before advancing.
setTimeout(() => {
this.stepper?.next();
this.onStepActivated();
}, 0);
setTimeout(() => this.stepper?.next(), 0);
return;
}
this.startWizard();
@ -306,12 +304,9 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
if (!step) {
return;
}
if (step.type === 'form') {
if (step.formGroup?.invalid) {
step.formGroup.markAllAsTouched();
return;
}
Object.assign(this.formValues, step.formGroup.getRawValue());
if (step.type === 'form' && step.formGroup?.invalid) {
step.formGroup.markAllAsTouched();
return;
}
if (this.isLastWizardStep) {
this.done();
@ -320,7 +315,22 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
step.completed = true;
this.cdr.detectChanges();
this.stepper.next();
this.onStepActivated();
}
onStepSelectionChange(event: StepperSelectionEvent): void {
if (event.selectedIndex <= event.previouslySelectedIndex) {
return;
}
// Forward moves can come from the stepper header, which bypasses nextStep(),
// so commit every step being passed over here.
for (let i = event.previouslySelectedIndex; i < event.selectedIndex; i++) {
const ws = this.wizardSteps[i];
if (ws.type === 'form') {
Object.assign(this.formValues, ws.formGroup.getRawValue());
}
ws.completed = true;
}
this.onStepActivated(this.wizardSteps[event.selectedIndex]);
}
get primaryEntityAction(): { url: string; label: string } | null {
@ -736,13 +746,14 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
return field.defaultValue ?? (field.type === FormFieldType.BOOLEAN ? false : '');
}
private onStepActivated(): void {
const step = this.currentWizardStep;
private onStepActivated(step = this.currentWizardStep): void {
if (!step) {
return;
}
if (step.type === 'instruction') {
step.markdown = this.zipFiles.get(step.rawSteps[0].file) || '';
// Nothing to validate here, so the linear stepper header may move past it right away.
step.completed = true;
} else if (step.type === 'progress' && !step.progressDone) {
if (this.reviewMode) {
this.showCompletedEntitySteps(step);
@ -858,7 +869,6 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
await this.delay(500);
this.stepper.next();
this.cdr.detectChanges();
this.onStepActivated();
}
}

45
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.html

@ -25,6 +25,13 @@
<!-- Filter panel template (reused in sidebar and drawer) -->
<ng-template #filterPanelContent>
<div class="tb-iot-hub-filters-inner">
<mat-checkbox class="tb-iot-hub-filter-standalone"
[checked]="verifiedCreatorsOnly"
(change)="onVerifiedCreatorsToggle()">
{{ 'iot-hub.verified-creators-only' | translate }}
</mat-checkbox>
<div class="tb-iot-hub-filter-divider"></div>
@if (!fixedSubType && subtypeOptions.length > 0 && activeType !== ItemType.ALARM_RULE) {
<mat-expansion-panel [expanded]="true" class="tb-iot-hub-filter-panel">
<mat-expansion-panel-header>
@ -43,8 +50,8 @@
}
</div>
}
<div class="tb-iot-hub-filter-items" [class.scrollable]="getFilteredItems(subtypeOptions, 'subtype').length > 8"
(mouseenter)="getFilteredItems(subtypeOptions, 'subtype').length > 8 && (filterItemsHovered = true)"
<div class="tb-iot-hub-filter-items" [class.scrollable]="getFilteredItems(subtypeOptions, 'subtype').length > scrollThreshold"
(mouseenter)="getFilteredItems(subtypeOptions, 'subtype').length > scrollThreshold && (filterItemsHovered = true)"
(mouseleave)="filterItemsHovered = false">
@for (opt of getFilteredItems(subtypeOptions, 'subtype'); track opt.key) {
<mat-checkbox [checked]="isSubtypeActive(opt.key)"
@ -78,8 +85,8 @@
}
</div>
}
<div class="tb-iot-hub-filter-items" [class.scrollable]="getFilteredItems(vendorOptions, 'vendor').length > 8"
(mouseenter)="getFilteredItems(vendorOptions, 'vendor').length > 8 && (filterItemsHovered = true)"
<div class="tb-iot-hub-filter-items" [class.scrollable]="getFilteredItems(vendorOptions, 'vendor').length > scrollThreshold"
(mouseenter)="getFilteredItems(vendorOptions, 'vendor').length > scrollThreshold && (filterItemsHovered = true)"
(mouseleave)="filterItemsHovered = false">
@for (group of getGroupedFilterItems(vendorOptions, 'vendor'); track group.label) {
@if (group.label) {
@ -114,8 +121,8 @@
}
</div>
}
<div class="tb-iot-hub-filter-items" [class.scrollable]="getFilteredItems(hardwareTypeOptions, 'hardwareType').length > 8"
(mouseenter)="getFilteredItems(hardwareTypeOptions, 'hardwareType').length > 8 && (filterItemsHovered = true)"
<div class="tb-iot-hub-filter-items" [class.scrollable]="getFilteredItems(hardwareTypeOptions, 'hardwareType').length > scrollThreshold"
(mouseenter)="getFilteredItems(hardwareTypeOptions, 'hardwareType').length > scrollThreshold && (filterItemsHovered = true)"
(mouseleave)="filterItemsHovered = false">
@for (ht of getFilteredItems(hardwareTypeOptions, 'hardwareType'); track ht.key) {
<mat-checkbox [checked]="isHardwareTypeActive(ht.key)"
@ -145,8 +152,8 @@
}
</div>
}
<div class="tb-iot-hub-filter-items" [class.scrollable]="allConnectivityCount > 8"
(mouseenter)="allConnectivityCount > 8 && (filterItemsHovered = true)"
<div class="tb-iot-hub-filter-items" [class.scrollable]="allConnectivityCount > scrollThreshold"
(mouseenter)="allConnectivityCount > scrollThreshold && (filterItemsHovered = true)"
(mouseleave)="filterItemsHovered = false">
@for (group of getFilteredConnectivityGroups('connectivity'); track group.group) {
<div class="tb-iot-hub-filter-group-label">{{ group.group }}</div>
@ -182,8 +189,8 @@
}
</div>
}
<div class="tb-iot-hub-filter-items" [class.scrollable]="getFilteredItems(categoryOptions, 'category').length > 8"
(mouseenter)="getFilteredItems(categoryOptions, 'category').length > 8 && (filterItemsHovered = true)"
<div class="tb-iot-hub-filter-items" [class.scrollable]="getFilteredItems(categoryOptions, 'category').length > scrollThreshold"
(mouseenter)="getFilteredItems(categoryOptions, 'category').length > scrollThreshold && (filterItemsHovered = true)"
(mouseleave)="filterItemsHovered = false">
@for (cat of getFilteredItems(categoryOptions, 'category'); track cat.key) {
<mat-checkbox [checked]="isCategoryActive(cat.key)"
@ -217,8 +224,8 @@
}
</div>
}
<div class="tb-iot-hub-filter-items" [class.scrollable]="getFilteredItems(useCaseOptions, 'useCase').length > 8"
(mouseenter)="getFilteredItems(useCaseOptions, 'useCase').length > 8 && (filterItemsHovered = true)"
<div class="tb-iot-hub-filter-items" [class.scrollable]="getFilteredItems(useCaseOptions, 'useCase').length > scrollThreshold"
(mouseenter)="getFilteredItems(useCaseOptions, 'useCase').length > scrollThreshold && (filterItemsHovered = true)"
(mouseleave)="filterItemsHovered = false">
@for (group of getGroupedFilterItems(useCaseOptions, 'useCase'); track group.label) {
@if (group.label) {
@ -253,6 +260,12 @@
<div class="tb-iot-hub-filter-divider" style="margin-bottom: 8px"></div>
<div class="tb-iot-hub-filter-drawer-chips flex flex-wrap items-center gap-2">
<mat-chip-set>
@if (verifiedCreatorsOnly) {
<mat-chip (removed)="onVerifiedCreatorsToggle()">
{{ 'iot-hub.verified-creators-only' | translate }}
<mat-icon matChipRemove>close</mat-icon>
</mat-chip>
}
@for (key of getActiveSubtypesArray(); track key) {
<mat-chip (removed)="onSubtypeToggle(key)">
{{ getSubtypeLabel(key) }}
@ -305,6 +318,8 @@
<!-- Left sidebar filters (visible on large screens) -->
<div class="tb-iot-hub-filters tb-iot-hub-filters-desktop">
<div class="tb-iot-hub-filters-wrapper" [class.filter-items-hovered]="filterItemsHovered">
<div class="tb-iot-hub-filters-header">{{ 'iot-hub.filter' | translate }}</div>
<div class="tb-iot-hub-filter-divider"></div>
<ng-container *ngTemplateOutlet="filterPanelContent"></ng-container>
</div>
</div>
@ -347,6 +362,12 @@
<!-- Active filter chips (hidden on small screens) -->
@if (hasActiveDropdownFilters()) {
<mat-chip-set class="tb-iot-hub-active-filters">
@if (verifiedCreatorsOnly) {
<mat-chip (removed)="onVerifiedCreatorsToggle()">
{{ 'iot-hub.verified-creators-only' | translate }}
<mat-icon matChipRemove>close</mat-icon>
</mat-chip>
}
@for (key of getActiveSubtypesArray(); track key) {
<mat-chip (removed)="onSubtypeToggle(key)">
{{ getSubtypeLabel(key) }}

39
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.scss

@ -98,6 +98,17 @@
}
}
.tb-iot-hub-filters-header {
padding: 16px 16px 12px 56px;
font-size: 18px;
font-weight: 500;
color: rgba(0, 0, 0, 0.87);
}
.tb-iot-hub-filters-desktop .tb-iot-hub-filters-inner {
padding-top: 8px;
}
.tb-iot-hub-filters-wrapper {
position: sticky;
max-height: calc(100vh - var(--mat-toolbar-standard-height, 64px));
@ -168,6 +179,10 @@
padding: 0;
}
.tb-iot-hub-filter-standalone {
margin-left: 13px;
}
.tb-iot-hub-filter-panel.mat-expansion-panel {
.mat-expansion-panel-header {
padding-left: 24px;
@ -200,6 +215,21 @@
background: rgba(0, 0, 0, 0.12);
}
// 56px section-title inset minus the checkbox's own 11px
.tb-iot-hub-filter-standalone {
margin-left: 45px;
}
.tb-iot-hub-filter-panel.mat-expansion-panel mat-checkbox,
.tb-iot-hub-filter-standalone {
display: block;
overflow: hidden;
&:hover {
background: rgba(0, 0, 0, 0.04);
}
}
// Filter expansion panels — Design: no shadow, pl-40 for content
.tb-iot-hub-filter-panel.mat-expansion-panel {
box-shadow: none;
@ -222,15 +252,6 @@
padding: 0 8px 0 0;
}
mat-checkbox {
display: block;
overflow: hidden;
&:hover {
background: rgba(0, 0, 0, 0.04);
}
}
.tb-iot-hub-filter-items {
padding-left: 44px;
max-height: 340px;

66
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts

@ -4,23 +4,29 @@ import { AfterViewInit, Component, ElementRef, EventEmitter, Input, NgZone, OnDe
import { Subject } from 'rxjs';
import { debounceTime, takeUntil } from 'rxjs/operators';
import { PageLink } from '@shared/models/page/page-link';
import { Direction, SortOrder } from '@shared/models/page/sort-order';
import { SortOrder } from '@shared/models/page/sort-order';
import { PageData } from '@shared/models/page/page-data';
import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models';
import { ItemType, FilterParamInfo, CREATOR_VISIBLE_ITEM_TYPES } from '@shared/models/iot-hub/iot-hub-item.models';
import {
CREATOR_VISIBLE_ITEM_TYPES,
FilterParamInfo,
IOT_HUB_SORT_OPTIONS,
isCompactItemType,
ItemType
} from '@shared/models/iot-hub/iot-hub-item.models';
import { widgetTypeTranslations, cfTypeTranslations, ruleChainTypeTranslations } from '@shared/models/iot-hub/iot-hub-version.models';
import { IotHubInstalledItem, DeviceInstalledItemDescriptor } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { TranslateService } from '@ngx-translate/core';
import { ActivatedRoute, Router } from '@angular/router';
import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service';
import { filterIotHubItemsBySearch, groupIotHubFilterItems, IotHubFilterGroup } from '@home/components/iot-hub/iot-hub-utils';
interface SortOption {
value: string;
label: string;
direction: Direction;
}
import {
filterIotHubItemsBySearch,
groupIotHubFilterItems,
IOT_HUB_FILTER_SCROLL_THRESHOLD,
IotHubFilterGroup,
measureGridColumns
} from '@home/components/iot-hub/iot-hub-utils';
@Component({
selector: 'tb-iot-hub-browse',
@ -34,7 +40,6 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy
private static typeTabLabel(t: ItemType): string {
switch (t) {
case ItemType.WIDGET: return 'item.type-widget-plural';
case ItemType.DASHBOARD: return 'item.type-dashboard-plural';
case ItemType.SOLUTION_TEMPLATE: return 'item.type-solution-template-plural';
case ItemType.CALCULATED_FIELD: return 'item.type-calculated-field-plural';
case ItemType.ALARM_RULE: return 'item.type-alarm-rule-plural';
@ -44,6 +49,7 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy
}
readonly ItemType = ItemType;
readonly scrollThreshold = IOT_HUB_FILTER_SCROLL_THRESHOLD;
@Input() creatorId: string;
@Input() embedded = false;
@ -79,15 +85,12 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy
}
get isCompactType(): boolean {
return this._activeType === ItemType.CALCULATED_FIELD
|| this._activeType === ItemType.ALARM_RULE
|| this._activeType === ItemType.RULE_CHAIN;
return isCompactItemType(this._activeType);
}
get searchPlaceholderKey(): string {
switch (this._activeType) {
case ItemType.WIDGET: return 'iot-hub.search-widgets';
case ItemType.DASHBOARD: return 'iot-hub.search-dashboards';
case ItemType.SOLUTION_TEMPLATE: return 'iot-hub.search-solution-templates';
case ItemType.CALCULATED_FIELD: return 'iot-hub.search-calculated-fields';
case ItemType.ALARM_RULE: return 'iot-hub.search-alarm-rules';
@ -130,12 +133,9 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy
activeConnectivity = new Set<string>();
activeHardwareTypes = new Set<string>();
activeVendors = new Set<string>();
verifiedCreatorsOnly = false;
sortOptions: SortOption[] = [
{ value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC },
{ value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC },
{ value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC }
];
readonly sortOptions = IOT_HUB_SORT_OPTIONS;
typeTabs: { type: ItemType; label: string }[] = CREATOR_VISIBLE_ITEM_TYPES.map(t => ({
type: t,
@ -222,17 +222,7 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy
if (!el) {
return this.probeCols;
}
// Force layout so `grid-template-columns` resolves to pixel tracks, not `repeat(...)`.
void el.offsetWidth;
const tracks = getComputedStyle(el).gridTemplateColumns;
if (!tracks || tracks === 'none') {
return 1;
}
if (tracks.startsWith('repeat(')) {
const match = tracks.match(/^repeat\(\s*(\d+)\s*,/);
return match ? parseInt(match[1], 10) : 1;
}
return Math.max(1, tracks.trim().split(/\s+/).filter(t => t.length > 0).length);
return measureGridColumns(el);
}
private adjustPageSize(): void {
@ -398,6 +388,12 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy
this.loadItems();
}
onVerifiedCreatorsToggle(): void {
this.verifiedCreatorsOnly = !this.verifiedCreatorsOnly;
this.pageIndex = 0;
this.loadItems();
}
isVendorActive(vendor: string): boolean {
return this.activeVendors.has(vendor);
}
@ -501,12 +497,14 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy
this.activeConnectivity.clear();
this.activeHardwareTypes.clear();
this.activeVendors.clear();
this.verifiedCreatorsOnly = false;
}
get activeFilterCount(): number {
const subtypeCount = this.fixedSubType ? this.getActiveSubtypesArray().length : (this.getActiveSubtypes()?.size || 0);
return subtypeCount + this.activeCategories.size + this.activeUseCases.size +
this.activeConnectivity.size + this.activeHardwareTypes.size + this.activeVendors.size;
this.activeConnectivity.size + this.activeHardwareTypes.size + this.activeVendors.size +
(this.verifiedCreatorsOnly ? 1 : 0);
}
hasActiveDropdownFilters(): boolean {
@ -514,7 +512,7 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy
return this.activeCategories.size > 0 ||
this.activeUseCases.size > 0 || subtypeCount > 0 ||
this.activeConnectivity.size > 0 || this.activeHardwareTypes.size > 0 ||
this.activeVendors.size > 0;
this.activeVendors.size > 0 || this.verifiedCreatorsOnly;
}
hasActiveFilters(): boolean {
@ -524,7 +522,6 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy
getTitle(): string {
switch (this.activeType) {
case ItemType.WIDGET: return 'iot-hub.title-widgets';
case ItemType.DASHBOARD: return 'iot-hub.title-dashboards';
case ItemType.SOLUTION_TEMPLATE: return 'iot-hub.title-solution-templates';
case ItemType.CALCULATED_FIELD: return 'iot-hub.title-calculated-fields';
case ItemType.ALARM_RULE: return 'iot-hub.title-alarm-rules';
@ -703,7 +700,8 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy
ruleChainTypes: this.activeRuleChainTypes.size > 0 ? Array.from(this.activeRuleChainTypes) : undefined,
hardwareTypes: this.activeHardwareTypes.size > 0 ? Array.from(this.activeHardwareTypes) : undefined,
connectivity: this.activeConnectivity.size > 0 ? Array.from(this.activeConnectivity) : undefined,
vendors: this.activeVendors.size > 0 ? Array.from(this.activeVendors) : undefined
vendors: this.activeVendors.size > 0 ? Array.from(this.activeVendors) : undefined,
creatorVerified: this.verifiedCreatorsOnly
});
this.iotHubApiService.getPublishedVersions(
query,

3
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts

@ -15,6 +15,7 @@ import { TbIotHubUnpublishedWarningDialogComponent } from './iot-hub-unpublished
import { TbDeviceInstallDialogComponent } from './device-install-dialog/device-install-dialog.component';
import { InstallFormRendererComponent } from './device-install-dialog/install-form-renderer/install-form-renderer.component';
import { TbIotHubSearchComponent } from './iot-hub-search.component';
import { TbIotHubFacetListComponent } from './iot-hub-facet-list.component';
import { TbIotHubInstalledItemsTableComponent } from './iot-hub-installed-items-table.component';
import { TbIotHubInstalledItemsDialogComponent } from './iot-hub-installed-items-dialog.component';
import { TbIotHubSelectCfEntityDialogComponent } from './iot-hub-select-cf-entity-dialog.component';
@ -36,6 +37,7 @@ import { IotHubItemLinkModule } from './iot-hub-item-link-card/iot-hub-item-link
TbIotHubUnpublishedWarningDialogComponent,
TbDeviceInstallDialogComponent,
TbIotHubSearchComponent,
TbIotHubFacetListComponent,
TbIotHubInstalledItemsTableComponent,
TbIotHubInstalledItemsDialogComponent,
TbIotHubSelectCfEntityDialogComponent,
@ -63,6 +65,7 @@ import { IotHubItemLinkModule } from './iot-hub-item-link-card/iot-hub-item-link
TbIotHubUnpublishedWarningDialogComponent,
TbDeviceInstallDialogComponent,
TbIotHubSearchComponent,
TbIotHubFacetListComponent,
TbIotHubInstalledItemsTableComponent,
TbIotHubInstalledItemsDialogComponent,
TbIotHubSelectCfEntityDialogComponent,

31
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html

@ -0,0 +1,31 @@
<!--
SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
SPDX-License-Identifier: Apache-2.0
-->
<mat-expansion-panel [expanded]="expanded" class="tb-iot-hub-facet-panel">
<mat-expansion-panel-header>
<mat-panel-title>{{ label | translate }}</mat-panel-title>
</mat-expansion-panel-header>
@if (searchable) {
<div class="tb-iot-hub-facet-search">
<mat-icon>search</mat-icon>
<input [placeholder]="'iot-hub.search' | translate" [ngModel]="search" (ngModelChange)="onSearchChange($event)">
@if (search) {
<button mat-icon-button class="tb-iot-hub-facet-search-clear" (click)="onSearchChange('')">
<mat-icon>close</mat-icon>
</button>
}
</div>
}
<div class="tb-iot-hub-facet-items" [class.scrollable]="scrollable">
@for (key of visibleOptions; track key) {
<mat-checkbox [checked]="isSelected(key)" (change)="onToggle(key)">
{{ labelFor(key) }}
</mat-checkbox>
}
</div>
</mat-expansion-panel>

63
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.scss

@ -0,0 +1,63 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
@import "./iot-hub-common";
// Matches the type pages' filter panel, minus its rail indent.
.tb-iot-hub-facet-panel.mat-expansion-panel {
box-shadow: none;
border-radius: 0;
background: transparent;
// Text is indented by --tb-facet-indent (set by the host); the rules between facets are not.
.mat-expansion-panel-header {
padding: 8px 16px 8px var(--tb-facet-indent, 16px);
height: 48px;
min-height: 48px;
}
::ng-deep .mat-expansion-panel-header-title {
font-size: 14px;
font-weight: 500;
color: rgba(0, 0, 0, 0.87);
}
::ng-deep .mat-expansion-panel-body {
padding: 0 8px 8px var(--tb-facet-indent, 16px);
}
mat-checkbox {
display: block;
overflow: hidden;
&:hover {
background: rgba(0, 0, 0, 0.04);
}
}
.tb-iot-hub-facet-items {
// Capped only when long enough to scroll.
&.scrollable {
max-height: 280px;
overflow-y: auto;
}
@include tb-iot-hub-hover-scrollbar;
}
.tb-iot-hub-facet-search {
@include tb-iot-hub-search-container;
margin: 4px 8px 8px 0;
mat-icon {
@include tb-iot-hub-search-icon(rgba(0, 0, 0, 0.54));
}
input {
@include tb-iot-hub-search-input-text(0.2px);
}
.tb-iot-hub-facet-search-clear.mat-mdc-icon-button {
@include tb-iot-hub-search-clear;
}
}
}

60
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.ts

@ -0,0 +1,60 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
import { Component, EventEmitter, Input, OnChanges, Output } from '@angular/core';
import { filterByLabel, IOT_HUB_FILTER_SCROLL_THRESHOLD } from '@home/components/iot-hub/iot-hub-utils';
/**
* One checkbox facet of a filter panel: a title, the option keys, and the set of keys currently
* selected. Presentational only - the host decides what a toggle means.
*/
@Component({
selector: 'tb-iot-hub-facet-list',
standalone: false,
templateUrl: './iot-hub-facet-list.component.html',
styleUrls: ['./iot-hub-facet-list.component.scss']
})
export class TbIotHubFacetListComponent implements OnChanges {
/** Translation key for the facet's heading. */
@Input() label: string;
@Input() options: string[] = [];
/** Keys the host has selected. The host hands over a new Set on every toggle. */
@Input() selected = new Set<string>();
/** Turns an option key into what the user reads. */
@Input() labelFor: (key: string) => string = (key) => key;
@Input() expanded = true;
@Output() toggled = new EventEmitter<string>();
search = '';
searchable = false;
visibleOptions: string[] = [];
scrollable = false;
ngOnChanges(): void {
this.searchable = this.options.length > IOT_HUB_FILTER_SCROLL_THRESHOLD;
this.applySearch();
}
onSearchChange(search: string): void {
this.search = search;
this.applySearch();
}
isSelected(key: string): boolean {
return this.selected.has(key);
}
onToggle(key: string): void {
this.toggled.emit(key);
}
private applySearch(): void {
this.visibleOptions = filterByLabel(this.options, this.search, this.labelFor);
this.scrollable = this.visibleOptions.length > IOT_HUB_FILTER_SCROLL_THRESHOLD;
}
}

1
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss

@ -116,7 +116,6 @@
.tb-type-calc-field { color: #3db5e0; background: rgba(61, 181, 224, 0.06); }
.tb-type-alarm-rule { color: #d7702f; background: rgba(215, 112, 47, 0.06); }
.tb-type-rule-chain { color: #aa5be3; background: rgba(170, 91, 227, 0.06); }
.tb-type-dashboard { color: #607d8b; background: rgba(96, 125, 139, 0.06); }
// "vX.X.X Available" button — Design: border rgba(0,0,0,0.12), rounded-4, px-12 py-6, gap-8
.tb-installed-version-btn {

1
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts

@ -158,7 +158,6 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
getItemTypeChipClass(itemType: string): string {
switch (itemType) {
case 'WIDGET': return 'tb-type-widget';
case 'DASHBOARD': return 'tb-type-dashboard';
case 'CALCULATED_FIELD': return 'tb-type-calc-field';
case 'ALARM_RULE': return 'tb-type-alarm-rule';
case 'RULE_CHAIN': return 'tb-type-rule-chain';

5
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html

@ -71,14 +71,15 @@
}
</div>
} @else {
<!-- Big card (Widget / Dashboard / Solution Template) -->
<!-- Big card (Widget / Solution Template) -->
<div class="tb-iot-hub-item-card" role="button" tabindex="0" (click)="onCardClick()" (keyup.enter)="onCardClick()">
<div class="tb-iot-hub-card-preview">
@if (getPreviewUrl(); as previewUrl) {
<img [src]="previewUrl" alt="" class="tb-iot-hub-preview-image">
} @else {
<div class="tb-iot-hub-preview-placeholder">
<tb-icon>{{ getPlaceholderIcon() }}</tb-icon>
<!-- The item's own colour, standing in for the compact card's coloured square. -->
<tb-icon [style.color]="item.color || null">{{ getPlaceholderIcon() }}</tb-icon>
</div>
}
</div>

14
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts

@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { MpItemVersionView, cfTypeTranslations, cfTypeIcons, ruleChainTypeTranslations, widgetTypeTranslations } from '@shared/models/iot-hub/iot-hub-version.models';
import { getItemTypeIcon, ItemType } from '@shared/models/iot-hub/iot-hub-item.models';
import { getItemTypeIcon, isCompactItemType, ItemType } from '@shared/models/iot-hub/iot-hub-item.models';
import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { TranslateService } from '@ngx-translate/core';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
@ -23,6 +23,11 @@ export class TbIotHubItemCardComponent {
@Input() showTypeChip = true;
@Input() showSubtype = false;
@Input() mode: 'default' | 'add' = 'default';
/**
* `auto`: compact row for the types with nothing to preview (single-type grids widen their
* cells for it). `preview`: the tall card for every type, for grids that mix types.
*/
@Input() layout: 'auto' | 'preview' = 'auto';
@Output() cardClick = new EventEmitter<MpItemVersionView>();
@Output() creatorClick = new EventEmitter<string>();
@Output() installClick = new EventEmitter<MpItemVersionView>();
@ -47,9 +52,10 @@ export class TbIotHubItemCardComponent {
}
isCompactLayout(): boolean {
return this.item.type === ItemType.CALCULATED_FIELD
|| this.item.type === ItemType.ALARM_RULE
|| this.item.type === ItemType.RULE_CHAIN;
if (this.layout === 'preview') {
return false;
}
return isCompactItemType(this.item.type);
}
getPreviewUrl(): string | null {

20
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html

@ -13,7 +13,7 @@
</div>
}
<div class="flex min-w-0 flex-1 flex-col gap-2">
<span class="dlg-title">{{ item.name }}</span>
<span class="dlg-title">{{ itemTitle }}</span>
<div class="dlg-subtitle">
<span class="dlg-subtitle-group">
<tb-icon class="dlg-subtitle-icon">{{ getTypeIcon() }}</tb-icon>
@ -75,7 +75,7 @@
<!-- Main content -->
<div class="dlg-main">
@if (isCompactLayout()) {
<!-- CF/RC/Device: description + author (no image) -->
<!-- Calculated field/alarm rule/rule chain: description + author (no image) -->
<div class="dlg-info dlg-info-compact">
<div class="dlg-info-text">
@if (item.description) {
@ -86,11 +86,15 @@
</div>
</div>
} @else {
<!-- Widget/Dashboard/Solution: image + description side by side -->
<!-- Widget/Solution: image + description side by side -->
<div class="flex gap-6 lt-md:flex-col">
<div class="dlg-preview"
[class.dlg-preview-carousel]="item.type === ItemType.SOLUTION_TEMPLATE && carouselImages.length > 1">
@if (item.type === ItemType.SOLUTION_TEMPLATE && carouselImages.length > 1) {
[class.dlg-preview-carousel]="carouselImages.length > 1"
tbPhotoSwipeGallery galleryChildrenSelector=".dlg-carousel-item, .dlg-preview-img"
(lightboxOpened)="lightboxOpen = true"
(slideChanged)="carouselIndex = $event"
(lightboxClosed)="lightboxOpen = false">
@if (carouselImages.length > 1) {
<div class="dlg-hero-carousel">
<ngx-hm-carousel
[(ngModel)]="carouselIndex"
@ -98,7 +102,7 @@
[infinite]="true"
[autoplay-speed]="3000"
[between-delay]="0"
[autoplay]="true"
[autoplay]="!lightboxOpen"
[mouse-enable]="true"
[show-num]="1"
class="dlg-carousel">
@ -131,7 +135,7 @@
</div>
</div>
} @else {
@if (getPreviewUrl(); as url) {
@if (carouselImages[0]; as url) {
<img [src]="url" alt="" class="dlg-preview-img">
} @else {
<div class="dlg-preview-placeholder">
@ -156,7 +160,7 @@
<!-- Categories & Use Cases / Device metadata -->
<div class="dlg-meta-bar">
<div class="dlg-divider"></div>
<div class="dlg-meta" [class.dlg-meta-4-col]="item.type === ItemType.SOLUTION_TEMPLATE || item.type === ItemType.DASHBOARD">
<div class="dlg-meta" [class.dlg-meta-4-col]="item.type === ItemType.SOLUTION_TEMPLATE">
@if (showCreator) {
<div class="dlg-meta-group dlg-meta-creator-section">
<span class="dlg-meta-label">{{ 'iot-hub.creator' | translate }}</span>

4
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.scss

@ -145,6 +145,10 @@
&.dlg-preview-carousel {
aspect-ratio: 1.5;
}
img {
cursor: zoom-in;
}
}
.dlg-preview-img {

47
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.ts

@ -7,7 +7,7 @@ import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state';
import { DialogComponent } from '@shared/components/dialog.component';
import { MpItemVersionView, cfTypeTranslations, cfTypeIcons, ruleChainTypeTranslations, widgetTypeTranslations, NodeInfo } from '@shared/models/iot-hub/iot-hub-version.models';
import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models';
import { getItemTypeIcon, isCompactItemType, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models';
import { getInstalledItemUrl, IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { TranslateService } from '@ngx-translate/core';
@ -49,6 +49,8 @@ export class TbIotHubItemDetailDialogComponent extends DialogComponent<TbIotHubI
installedItem?: IotHubInstalledItem;
installedItemsCount = 0;
carouselImages: string[] = [];
// Pauses carousel autoplay, so the slide behind the open image stays the one it zooms back to
lightboxOpen = false;
carouselIndex = 0;
// Built-in marker rides on the version line rather than as a standalone badge.
versionLabel: string;
@ -87,9 +89,7 @@ export class TbIotHubItemDetailDialogComponent extends DialogComponent<TbIotHubI
}
isCompactLayout(): boolean {
return this.item.type === ItemType.CALCULATED_FIELD
|| this.item.type === ItemType.ALARM_RULE
|| this.item.type === ItemType.RULE_CHAIN;
return isCompactItemType(this.item.type);
}
getPreviewUrl(): string | null {
@ -172,6 +172,11 @@ export class TbIotHubItemDetailDialogComponent extends DialogComponent<TbIotHubI
&& this.installedItem.itemVersionId !== this.item.id;
}
/** The tracking row keeps the item's current name; a version keeps the one it was published under. */
get itemTitle(): string {
return this.installedItem?.itemVersionId === this.item.id ? this.installedItem.itemName : this.item.name;
}
/** Runs whatever the item's action mode calls for: open the local copy, connect, or install. */
runPrimaryAction(): void {
if (iotHubItemActionMode(this.item) === 'connect') {
@ -278,17 +283,35 @@ export class TbIotHubItemDetailDialogComponent extends DialogComponent<TbIotHubI
this.dialogRef.close();
}
// The item image leads, screenshots follow; a single entry renders as the plain preview image
private buildCarouselImages(): void {
if (this.item.type !== ItemType.SOLUTION_TEMPLATE || !this.item.resources?.length) {
if (this.isCompactLayout()) {
return;
}
const screenshotResources = this.item.resources.filter(r => r.type === 'SCREENSHOT');
const allResources = screenshotResources.length > 0
? screenshotResources
: this.item.resources.filter(r => r.type === 'ICON');
this.carouselImages = allResources.map(r =>
this.iotHubApiService.resolveResourceUrl(`/api/resources/${r.id}`)
);
const urls: string[] = [];
const previewUrl = this.getPreviewUrl();
if (previewUrl) {
urls.push(previewUrl);
}
// Skip the screenshot the preview already shows; by id, since item.image may carry a suffix
const previewResourceId = this.item.image?.match(/\/api\/resources\/([^/?#]+)/)?.[1];
for (const resource of this.item.resources || []) {
if (resource.type === 'SCREENSHOT' && resource.id !== previewResourceId) {
urls.push(this.resourceUrl(resource.id));
}
}
if (!urls.length) {
// Same order as resolveIotHubItemImageUrl: image, screenshot, then a single icon stand-in
const icon = this.item.resources?.find(resource => resource.type === 'ICON');
if (icon) {
urls.push(this.resourceUrl(icon.id));
}
}
this.carouselImages = urls;
}
private resourceUrl(id: string): string {
return this.iotHubApiService.resolveResourceUrl(`/api/resources/${id}`);
}
private loadReadme(): void {

4
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.html

@ -4,7 +4,9 @@
SPDX-License-Identifier: Apache-2.0
-->
<tb-markdown [data]="parsedData"
<tb-markdown tbPhotoSwipeGallery
[galleryChildrenSelector]="readmeGallerySelector"
[data]="parsedData"
[applyDefaultMarkdownStyle]="false"
[additionalStyles]="additionalStyles"
[additionalCompileModules]="itemLinkCompileModules"

4
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.scss

@ -118,6 +118,10 @@ $gallery-border-hover-color: #2a7dec;
max-width: 100%;
}
img.tb-readme-gallery-image {
cursor: zoom-in;
}
a:not(.mdc-button):not(.tb-iot-hub-item-link-card) {
font-weight: 500;
color: $link-color;

12
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.ts

@ -24,6 +24,14 @@ import {
import { DevicePackageInfo } from '@shared/models/iot-hub/device-package.models';
import { isNotEmptyStr } from '@core/utils';
// Every image the readme itself renders opens in the lightbox. Excluded is the chrome that happens
// to be an <img>: the ${images.gallery(...)} block (it runs its own gallery), the code block
// clipboard icon and an item link card's thumbnail. Images inside a link are excluded too: the
// lightbox preventDefaults the click, which would swallow the navigation.
const README_GALLERY_SELECTOR =
'img:not(.tb-gallery-images img):not(.clipboard-btn img):not(tb-iot-hub-item-link-card img):not(a img)';
const README_GALLERY_IMAGE_CLASS = 'tb-readme-gallery-image';
@Component({
selector: 'tb-iot-hub-markdown',
standalone: false,
@ -61,6 +69,8 @@ export class TbIotHubMarkdownComponent implements OnInit, OnChanges {
readonly itemLinkCompileModules: Type<any>[] = [IotHubItemLinkModule];
readonly readmeGallerySelector = README_GALLERY_SELECTOR;
constructor(
private iotHubApiService: IotHubApiService,
private elementRef: ElementRef<HTMLElement>
@ -86,6 +96,8 @@ export class TbIotHubMarkdownComponent implements OnInit, OnChanges {
onReady() {
const container = this.elementRef.nativeElement;
container.querySelectorAll(README_GALLERY_SELECTOR)
.forEach(image => image.classList.add(README_GALLERY_IMAGE_CLASS));
this.ready.emit(container);
}

160
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.html

@ -4,14 +4,26 @@
SPDX-License-Identifier: Apache-2.0
-->
<div class="mb-10 flex items-baseline gap-4 lt-md:mb-4">
<div class="tb-search-pad mb-10 flex items-baseline gap-4 lt-md:mb-4">
<ng-content></ng-content>
<span class="tb-search-results-count tb-search-results-count-mobile">
{{ 'iot-hub.results-count' | translate:{ count: totalElements } }}
</span>
</div>
<!-- Search + Sort row -->
<div class="flex items-center gap-4">
<!-- Hidden probe — we read its computed grid-template-columns to detect the current column count. -->
<div #cardGridProbe class="tb-search-card-grid tb-search-card-grid-probe" aria-hidden="true"></div>
<!-- Filter + Search + Sort row -->
<div class="tb-search-pad flex items-center gap-4">
@if (showFilters) {
<button mat-stroked-button class="tb-search-filter-btn" (click)="filtersOpen = !filtersOpen">
<mat-icon>filter_alt</mat-icon>
{{ 'iot-hub.filter' | translate }}
@if (activeFilterCount > 0) {
<span class="tb-search-filter-count">{{ activeFilterCount }}</span>
}
</button>
}
<div class="tb-search-input-field flex flex-1 items-center">
<input class="tb-search-input"
[placeholder]="searchPlaceholderKey | translate"
@ -43,7 +55,7 @@
</div>
<!-- Results count + Pagination (shown when results exist) -->
<div class="tb-search-pagination-row" [class.lt-md:!hidden]="totalElements === 0">
<div class="tb-search-pagination-row tb-search-pad" [class.lt-md:!hidden]="totalElements === 0">
<span class="tb-search-results-count">
{{ 'iot-hub.results-count' | translate:{ count: totalElements } }}
</span>
@ -76,62 +88,98 @@
<div class="tb-search-divider"></div>
<div class="relative min-h-0">
<div class="tb-results-container">
<!-- Error -->
@if (hasError) {
<div class="tb-search-empty flex flex-col items-center py-10">
<div class="tb-no-service-bg"></div>
<h3>{{ 'iot-hub.network-server-unavailable' | translate }}</h3>
<p>{{ 'iot-hub.network-server-unavailable-text' | translate }}</p>
<button mat-flat-button color="primary" (click)="retryLoadResults()">
{{ 'iot-hub.try-again' | translate }}
</button>
</div>
<!-- Facets, rendered once and projected into the sidebar or the drawer -->
<ng-template #facetPanel>
<div class="tb-search-facets">
@if (activeFilterCount > 0) {
<button mat-button color="primary" class="tb-search-facets-clear" (click)="clearFilters()">
{{ 'iot-hub.clear-filters' | translate }}
</button>
}
<!-- No results -->
@if (!hasError && totalElements === 0 && searchText?.trim()) {
<div class="tb-search-empty flex flex-col items-center py-10">
<div class="tb-no-data-bg"></div>
<h3>{{ 'iot-hub.no-items-found' | translate }}</h3>
<p>{{ 'iot-hub.try-adjusting-search' | translate }}</p>
</div>
<tb-iot-hub-facet-list label="iot-hub.item-type"
[options]="typeOptions"
[selected]="activeTypes"
[labelFor]="getTypeLabel"
(toggled)="onTypeToggle($event)">
</tb-iot-hub-facet-list>
@if (categoryOptions.length > 0) {
<!-- Closed by default: these run to dozens of options. -->
<tb-iot-hub-facet-list label="iot-hub.category"
[expanded]="false"
[options]="categoryOptions"
[selected]="activeCategories"
(toggled)="onCategoryToggle($event)">
</tb-iot-hub-facet-list>
}
@if (useCaseOptions.length > 0) {
<tb-iot-hub-facet-list label="iot-hub.use-case"
[expanded]="false"
[options]="useCaseOptions"
[selected]="activeUseCases"
(toggled)="onUseCaseToggle($event)">
</tb-iot-hub-facet-list>
}
</div>
</ng-template>
<!-- Results grouped by type -->
@if (resultGroups.length > 0) {
<div class="tb-search-categories">
@for (group of resultGroups; track group.type) {
<div class="tb-search-section">
<!-- Section header -->
<button mat-button class="tb-search-section-header" (click)="navigateToType(group.type)">
{{ getTypeLabel(group.type) }}
<mat-icon>chevron_right</mat-icon>
</button>
<!-- Card grid -->
<div class="tb-search-card-grid" [class.tb-search-card-grid-compact]="isCompactType(group.type)">
@for (item of group.items; track item.id) {
<tb-iot-hub-item-card
[item]="item"
[installedItem]="getInstalledItem(item)"
[installedItemsCount]="getInstalledItemsCount(item)"
[showTypeChip]="false"
[showSubtype]="false"
[showCreator]="showCreator"
(cardClick)="openItemDetail($event)"
(creatorClick)="navigateToCreator($event)"
(installClick)="installItem($event)"
(updateClick)="updateItem($event)"
(deleteClick)="deleteInstalledItem($event)">
</tb-iot-hub-item-card>
}
</div>
</div>
}
</div>
<div class="relative min-h-0 flex-1">
<!-- A flex row, not mat-drawer-container, which let a tall facet list overflow the card. -->
<div class="tb-search-layout">
@if (showFilters) {
<aside class="tb-search-facets-desktop" [class.opened]="filtersOpen">
<div class="tb-search-facets-header flex items-center justify-between">
<span>{{ 'iot-hub.filter' | translate }}</span>
<button mat-icon-button (click)="filtersOpen = false">
<mat-icon>close</mat-icon>
</button>
</div>
<ng-container *ngTemplateOutlet="facetPanel"></ng-container>
</aside>
}
<div class="tb-results-container">
<!-- Error -->
@if (hasError) {
<div class="tb-search-empty flex flex-col items-center py-10">
<div class="tb-no-service-bg"></div>
<h3>{{ 'iot-hub.network-server-unavailable' | translate }}</h3>
<p>{{ 'iot-hub.network-server-unavailable-text' | translate }}</p>
<button mat-flat-button color="primary" (click)="retryLoadResults()">
{{ 'iot-hub.try-again' | translate }}
</button>
</div>
}
<!-- No results -->
@if (!hasError && totalElements === 0 && searchText?.trim()) {
<div class="tb-search-empty flex flex-col items-center py-10">
<div class="tb-no-data-bg"></div>
<h3>{{ 'iot-hub.no-items-found' | translate }}</h3>
<p>{{ 'iot-hub.try-adjusting-search' | translate }}</p>
</div>
}
<!-- Results -->
@if (results.length > 0) {
<div class="tb-search-card-grid">
@for (item of results; track item.id) {
<tb-iot-hub-item-card
layout="preview"
[item]="item"
[installedItem]="getInstalledItem(item)"
[installedItemsCount]="getInstalledItemsCount(item)"
[showCreator]="showCreator"
(cardClick)="openItemDetail($event)"
(creatorClick)="navigateToCreator($event)"
(installClick)="installItem($event)"
(updateClick)="updateItem($event)"
(deleteClick)="deleteInstalledItem($event)">
</tb-iot-hub-item-card>
}
</div>
}
</div>
</div>
<!-- Loading -->

160
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss

@ -9,6 +9,13 @@
flex-direction: column;
}
// Full bleed: content rows pad themselves in by --tb-search-side-pad; the divider and the filter
// rail reach the edge.
.tb-search-pad {
padding-left: var(--tb-search-side-pad, 0px);
padding-right: var(--tb-search-side-pad, 0px);
}
.tb-search-results-count-mobile {
display: none;
margin-left: auto;
@ -144,69 +151,113 @@
overflow: auto;
}
// Categories / sections
.tb-search-categories {
display: flex;
flex-direction: column;
gap: 48px;
// Card grid
.tb-search-card-grid {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 20px;
// Zero-height probe for the column count; needs display: grid and a width to resolve tracks.
&.tb-search-card-grid-probe {
width: 100%;
height: 0;
gap: 0;
overflow: hidden;
visibility: hidden;
pointer-events: none;
}
}
// Section header
.tb-search-section-header {
font-size: 18px;
font-weight: 500;
line-height: 24px;
color: rgba(0, 0, 0, 0.87);
padding: 0;
margin-bottom: 12px;
// Filter button, with the active count
.tb-search-filter-btn {
flex-shrink: 0;
}
.tb-search-filter-count {
margin-left: 6px;
min-width: 18px;
height: 18px;
padding: 0 5px;
border-radius: 9px;
background: rgba(0, 0, 0, 0.08);
font-size: 12px;
line-height: 18px;
font-variant-numeric: tabular-nums;
}
mat-icon {
font-size: 24px;
width: 24px;
height: 24px;
// Facet sidebar beside the grid. Both columns scroll inside the given height, so neither grows
// past the card.
.tb-search-layout {
display: flex;
gap: 24px;
height: 100%;
min-height: 0;
.tb-results-container {
flex: 1;
min-width: 0;
// Only on the right: the gap to the rail already separates it on the left.
padding-right: var(--tb-search-side-pad, 0px);
}
}
// Card grid
.tb-search-card-grid {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 20px;
.tb-search-facets-desktop {
width: 232px;
flex-shrink: 0;
border-right: 1px solid rgba(0, 0, 0, 0.12);
&.tb-search-card-grid-compact {
grid-template-columns: repeat(3, 1fr);
// Starts at the card's edge so the rules across it reach it; each facet indents its own text.
--tb-facet-indent: var(--tb-search-side-pad, 16px);
align-self: stretch;
height: 100%;
overflow-y: auto;
padding-top: 20px;
@include tb-iot-hub-hover-scrollbar;
}
// The close button and heading belong to the narrow layout only.
.tb-search-facets-header {
display: none;
height: 48px;
font-size: 16px;
font-weight: 500;
}
.tb-search-facets {
display: flex;
flex-direction: column;
padding-bottom: 24px;
// A flush rule between filter sections, as on the type pages.
tb-iot-hub-facet-list + tb-iot-hub-facet-list {
border-top: 1px solid rgba(0, 0, 0, 0.12);
}
}
.tb-search-facets-clear {
align-self: flex-start;
margin-left: calc(var(--tb-facet-indent, 16px) - 16px);
}
// Responsive
@media #{$mat-gt-xxl} {
.tb-search-card-grid {
grid-template-columns: repeat(6, 1fr);
&.tb-search-card-grid-compact {
grid-template-columns: repeat(4, 1fr);
}
}
}
@media #{$mat-lt-xl} {
.tb-search-card-grid {
grid-template-columns: repeat(4, 1fr);
&.tb-search-card-grid-compact {
grid-template-columns: repeat(3, 1fr);
}
}
}
@media #{$mat-lt-xmd} {
.tb-search-card-grid {
grid-template-columns: repeat(3, 1fr);
&.tb-search-card-grid-compact {
grid-template-columns: repeat(2, 1fr);
}
}
}
@ -229,10 +280,6 @@
.tb-search-card-grid {
grid-template-columns: repeat(2, 1fr);
&.tb-search-card-grid-compact {
grid-template-columns: repeat(1, 1fr);
}
}
}
@ -269,3 +316,36 @@
margin-left: 0;
}
}
// Below this width the sidebar collapses and the Filter button opens it above the results.
@media #{$mat-lt-lg} {
.tb-search-layout {
flex-direction: column;
}
.tb-search-facets-desktop {
display: none;
// Above the results it is content, not a rail, so it is padded in like the rows above.
width: 100%;
height: auto;
max-height: 60vh;
border-right: none;
border-bottom: 1px solid rgba(0, 0, 0, 0.12);
padding-right: 0;
&.opened {
display: block;
}
}
.tb-search-facets-header {
display: flex;
}
}
// The sidebar is shown, so there is nothing for the button to open.
@media #{$mat-gt-md} {
.tb-search-filter-btn {
display: none;
}
}

297
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts

@ -1,33 +1,29 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core';
import { Component, OnInit, OnDestroy, Input, Output, EventEmitter, ViewChild, ElementRef, NgZone } from '@angular/core';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { forkJoin, Subject, Subscription } from 'rxjs';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
import { forkJoin, of, Subject, Subscription } from 'rxjs';
import { catchError, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';
import { PageLink } from '@shared/models/page/page-link';
import { Direction, SortOrder } from '@shared/models/page/sort-order';
import { SortOrder } from '@shared/models/page/sort-order';
import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models';
import { ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models';
import { PageData } from '@shared/models/page/page-data';
import {
CROSS_TYPE_ITEM_TYPES,
FilterParamInfo,
IOT_HUB_SORT_OPTIONS,
ItemType,
itemTypeTranslations
} from '@shared/models/iot-hub/iot-hub-item.models';
import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { IotHubActionsService } from './iot-hub-actions.service';
import { measureGridColumns } from './iot-hub-utils';
interface SearchResultGroup {
type: ItemType;
items: MpItemVersionView[];
}
interface SortOption {
value: string;
label: string;
direction: Direction;
}
const TYPE_ORDER: ItemType[] = [
ItemType.DEVICE, ItemType.SOLUTION_TEMPLATE, ItemType.WIDGET,
ItemType.CALCULATED_FIELD, ItemType.ALARM_RULE, ItemType.RULE_CHAIN
];
/** A page is whole rows of the grid, and never fewer than MIN_PAGE_SIZE cards. */
const ROWS_PER_PAGE = 3;
const MIN_PAGE_SIZE = 12;
@Component({
selector: 'tb-iot-hub-search',
@ -37,32 +33,50 @@ const TYPE_ORDER: ItemType[] = [
})
export class TbIotHubSearchComponent implements OnInit, OnDestroy {
readonly ItemType = ItemType;
@Input() searchText = '';
@Input() creatorId: string;
@Input() showCreator = true;
/** Off on the creator profile, which is already scoped to one creator. */
@Input() showFilters = true;
@Output() searchTextChange = new EventEmitter<string>();
get searchPlaceholderKey(): string {
return this.creatorId ? 'iot-hub.search-published-items' : 'iot-hub.search';
}
resultGroups: SearchResultGroup[] = [];
results: MpItemVersionView[] = [];
totalElements = 0;
isLoading = false;
hasError = false;
private retryTimer: any = null;
pageSize = 15;
pageIndex = 0;
pageSizeOptions = [15, 30, 60];
sortOptions: SortOption[] = [
{ value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC },
{ value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC },
{ value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC }
];
/** A hidden element carrying the real grid's classes, so the column count comes from the CSS. */
@ViewChild('cardGridProbe', { static: true }) cardGridProbe!: ElementRef<HTMLElement>;
cols = 5;
pageSize = MIN_PAGE_SIZE;
private resizeObserver?: ResizeObserver;
private resizeSubject = new Subject<void>();
private resizeSubscription?: Subscription;
get pageSizeOptions(): number[] {
const base = Math.max(MIN_PAGE_SIZE, this.cols * ROWS_PER_PAGE);
return [base, base * 2, base * 4];
}
// Filter panel state. An empty set means "no filter".
/** Narrow widths only: the facet panel is a block above the results, not a sidebar. */
filtersOpen = false;
readonly typeOptions: string[] = CROSS_TYPE_ITEM_TYPES;
categoryOptions: string[] = [];
useCaseOptions: string[] = [];
activeTypes = new Set<string>();
activeCategories = new Set<string>();
activeUseCases = new Set<string>();
readonly sortOptions = IOT_HUB_SORT_OPTIONS;
selectedSortIndex = 0;
installedWidgets: IotHubInstalledItem[] = [];
@ -74,16 +88,30 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy {
private searchSubject = new Subject<string>();
private searchSubscription: Subscription;
/** Every reload goes through here, so a newer request cancels an older one still in flight. */
private loadSubject = new Subject<void>();
private loadSubscription: Subscription;
constructor(
private router: Router,
private translate: TranslateService,
private iotHubApiService: IotHubApiService,
private iotHubActions: IotHubActionsService
private iotHubActions: IotHubActionsService,
private zone: NgZone
) {}
ngOnInit(): void {
this.measureCols();
this.observeGridWidth();
if (this.showFilters) {
this.loadFilterInfo();
}
this.loadInstalledItems();
this.loadSubscription = this.loadSubject.pipe(
switchMap(() => this.fetchResults(this.searchText || '').pipe(
catchError(() => of(null))
))
).subscribe(result => this.applyResult(result));
this.searchSubscription = this.searchSubject.pipe(
debounceTime(300),
distinctUntilChanged()
@ -96,6 +124,125 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy {
ngOnDestroy(): void {
this.searchSubscription?.unsubscribe();
this.loadSubscription?.unsubscribe();
this.resizeSubscription?.unsubscribe();
this.resizeObserver?.disconnect();
}
// Filters
getTypeLabel = (key: string): string => {
const translationKey = itemTypeTranslations.get(key as ItemType);
return translationKey ? this.translate.instant(translationKey + '-plural') : key;
};
onTypeToggle(key: string): void {
this.activeTypes = this.toggled(this.activeTypes, key);
this.reloadFromFirstPage();
}
onCategoryToggle(key: string): void {
this.activeCategories = this.toggled(this.activeCategories, key);
this.reloadFromFirstPage();
}
onUseCaseToggle(key: string): void {
this.activeUseCases = this.toggled(this.activeUseCases, key);
this.reloadFromFirstPage();
}
get activeFilterCount(): number {
return this.activeTypes.size + this.activeCategories.size + this.activeUseCases.size;
}
clearFilters(): void {
if (this.activeFilterCount === 0) {
return;
}
this.activeTypes = new Set<string>();
this.activeCategories = new Set<string>();
this.activeUseCases = new Set<string>();
this.reloadFromFirstPage();
}
/** A new Set rather than a mutation, so the facet list's @Input sees the change. */
private toggled(set: Set<string>, key: string): Set<string> {
const next = new Set(set);
if (!next.delete(key)) {
next.add(key);
}
return next;
}
private reloadFromFirstPage(): void {
this.pageIndex = 0;
this.loadResults();
}
/**
* filterInfo answers per item type, so the six answers are merged. Each request has its own
* catchError: one type failing costs that type's options, not the panel.
*/
private loadFilterInfo(): void {
const config = { ignoreLoading: true, ignoreErrors: true };
forkJoin(
CROSS_TYPE_ITEM_TYPES.map(type =>
this.iotHubApiService.getFilterInfo(type, config).pipe(catchError(() => of(null)))
)
).subscribe({
next: infos => {
this.categoryOptions = this.mergeFacet(infos.map(i => i?.categories));
this.useCaseOptions = this.mergeFacet(infos.map(i => i?.useCases));
}
});
}
/** Keys that have items in any of the per-type answers, sorted. */
private mergeFacet(lists: (FilterParamInfo[] | undefined)[]): string[] {
const keys = new Set<string>();
for (const list of lists) {
for (const option of list || []) {
if (option.totalItems > 0) {
keys.add(option.key);
}
}
}
return [...keys].sort((a, b) => a.localeCompare(b));
}
// Column count -> page size
private observeGridWidth(): void {
const el = this.cardGridProbe?.nativeElement;
if (!el || typeof ResizeObserver === 'undefined') {
return;
}
this.resizeSubscription = this.resizeSubject.pipe(debounceTime(150)).subscribe(() => {
const before = this.pageSizeOptions[0];
// Keep the same first item in view, not the same page number.
const firstItem = this.pageIndex * this.pageSize;
this.measureCols();
if (this.pageSizeOptions[0] === before) {
return;
}
this.pageSize = this.pageSizeOptions[0];
this.pageIndex = Math.floor(firstItem / this.pageSize);
this.loadResults();
});
// zone.js does not patch ResizeObserver; without zone.run the reload would not render.
this.resizeObserver = new ResizeObserver(() => this.zone.run(() => this.resizeSubject.next()));
this.resizeObserver.observe(el);
}
private measureCols(): void {
const el = this.cardGridProbe?.nativeElement;
if (!el) {
return;
}
this.cols = measureGridColumns(el);
if (!this.pageSizeOptions.includes(this.pageSize)) {
this.pageSize = this.pageSizeOptions[0];
}
}
onSearchInput(): void {
@ -158,35 +305,6 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy {
this.loadResults();
}
// Type helpers
isCompactType(type: ItemType): boolean {
return type === ItemType.CALCULATED_FIELD
|| type === ItemType.ALARM_RULE
|| type === ItemType.RULE_CHAIN;
}
getTypeLabel(type: ItemType): string {
const key = itemTypeTranslations.get(type);
return key ? this.translate.instant(key + '-plural') : type;
}
getTypeRoute(type: ItemType): string {
switch (type) {
case ItemType.WIDGET: return 'widgets';
case ItemType.SOLUTION_TEMPLATE: return 'solution-templates';
case ItemType.CALCULATED_FIELD: return 'calculated-fields';
case ItemType.ALARM_RULE: return 'alarm-rules';
case ItemType.RULE_CHAIN: return 'rule-chains';
case ItemType.DEVICE: return 'devices';
default: return 'widgets';
}
}
navigateToType(type: ItemType): void {
const search = this.searchText?.trim() || undefined;
void this.router.navigate(['/iot-hub', this.getTypeRoute(type)], { queryParams: { search } });
}
// Installed items
getInstalledItem(item: MpItemVersionView): IotHubInstalledItem | undefined {
switch (item.type) {
@ -270,52 +388,39 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy {
clearTimeout(this.retryTimer);
this.retryTimer = null;
}
// hasError stays as-is until a request succeeds.
this.isLoading = true;
// hasError stays as-is until the request actually succeeds
// (cleared in the `next` callback below).
this.fetchResults(this.searchText || '').subscribe({
next: result => {
this.applyResults(result.data, result.totalElements);
this.hasError = false;
},
error: () => {
this.isLoading = false;
this.hasError = true;
this.resultGroups = [];
this.totalElements = 0;
}
});
this.loadSubject.next();
}
/** A null result is a failed request. */
private applyResult(result: PageData<MpItemVersionView> | null): void {
this.isLoading = false;
if (result) {
this.totalElements = result.totalElements;
this.results = result.data;
this.hasError = false;
} else {
this.hasError = true;
this.results = [];
this.totalElements = 0;
}
}
private fetchResults(text: string) {
const sort = this.sortOptions[this.selectedSortIndex];
const sortOrder: SortOrder = { property: sort.value, direction: sort.direction };
const pageLink = new PageLink(this.pageSize, this.pageIndex, text.trim() || null, sortOrder);
const query = new MpItemVersionQuery(pageLink, { creatorId: this.creatorId || undefined });
const query = new MpItemVersionQuery(pageLink, {
creatorId: this.creatorId || undefined,
// No type selected means every type the platform surfaces (the Hub also holds dashboards).
types: this.activeTypes.size ? [...this.activeTypes] : CROSS_TYPE_ITEM_TYPES,
categories: this.activeCategories.size ? [...this.activeCategories] : undefined,
useCases: this.activeUseCases.size ? [...this.activeUseCases] : undefined
});
return this.iotHubApiService.getPublishedVersions(query, { ignoreLoading: true, ignoreErrors: true });
}
private applyResults(data: MpItemVersionView[], totalElements: number): void {
this.totalElements = totalElements;
this.resultGroups = this.groupResults(data);
this.isLoading = false;
}
private groupResults(items: MpItemVersionView[]): SearchResultGroup[] {
const groupMap = new Map<ItemType, MpItemVersionView[]>();
for (const item of items) {
let list = groupMap.get(item.type);
if (!list) {
list = [];
groupMap.set(item.type, list);
}
list.push(item);
}
return TYPE_ORDER
.filter(type => groupMap.has(type))
.map(type => ({ type, items: groupMap.get(type) }));
}
private loadInstalledItems(): void {
const config = { ignoreLoading: true };
const pageLink = new PageLink(10000, 0);

4
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html

@ -8,11 +8,11 @@
@switch (state) {
@case ('confirm') {
<h2 class="tb-iot-hub-install-title">{{ 'iot-hub.update-confirm-title' | translate:{ name: data.itemName } }}</h2>
<p class="tb-iot-hub-install-desc">{{ 'iot-hub.update-desc' | translate }}</p>
<p class="tb-iot-hub-install-desc">{{ updateDescKey | translate }}</p>
}
@case ('updating') {
<h2 class="tb-iot-hub-install-title">{{ 'iot-hub.update-confirm-title' | translate:{ name: data.itemName } }}</h2>
<p class="tb-iot-hub-install-desc">{{ 'iot-hub.update-desc' | translate }}</p>
<p class="tb-iot-hub-install-desc">{{ updateDescKey | translate }}</p>
}
@case ('success') {
<h2 class="tb-iot-hub-install-title">{{ 'iot-hub.update-success-title' | translate }}</h2>

11
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.ts

@ -59,6 +59,17 @@ export class TbIotHubUpdateDialogComponent extends DialogComponent<TbIotHubUpdat
return key ? this.translate.instant(key) : '';
}
/**
* Updating a solution template is a delete + reinstall of every entity it created, and unlike the other item
* types it is not stopped by the modified-entity check, so the tenant's own edits to those dashboards, devices
* and rule chains are lost. Say that instead of the generic "replace the current version" wording.
*/
get updateDescKey(): string {
return this.data?.itemType === ItemType.SOLUTION_TEMPLATE
? 'iot-hub.update-desc-solution-template'
: 'iot-hub.update-desc';
}
update(force = false): void {
this.state = 'updating';
this.iotHubApiService.updateItemVersion(this.data.installedItemId, this.data.versionId, { ignoreLoading: true }, force).subscribe({

26
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-utils.ts

@ -6,6 +6,8 @@ import { IotHubApiService } from '@core/http/iot-hub-api.service';
export const IOT_HUB_FILTER_GROUPING_THRESHOLD = 11;
export const IOT_HUB_FILTER_POPULAR_LIMIT = 10;
/** Above this many options a filter list scrolls, and the search page's facet gets a search box. */
export const IOT_HUB_FILTER_SCROLL_THRESHOLD = 8;
/**
* Primary action offered for an IoT Hub item:
@ -62,12 +64,30 @@ export interface IotHubFilterGroup {
items: FilterParamInfo[];
}
export function filterIotHubItemsBySearch(items: FilterParamInfo[], search: string): FilterParamInfo[] {
const normalized = (search || '').toLowerCase();
export function filterByLabel<T>(items: T[], search: string, labelOf: (item: T) => string): T[] {
const normalized = (search || '').trim().toLowerCase();
if (!normalized) {
return items;
}
return items.filter(item => item.key.toLowerCase().includes(normalized));
return items.filter(item => labelOf(item).toLowerCase().includes(normalized));
}
export function filterIotHubItemsBySearch(items: FilterParamInfo[], search: string): FilterParamInfo[] {
return filterByLabel(items, search, item => item.key);
}
/** Column count of a CSS grid, from its computed tracks (`repeat(...)` before first layout). */
export function measureGridColumns(el: HTMLElement): number {
void el.offsetWidth;
const tracks = getComputedStyle(el).gridTemplateColumns;
if (!tracks || tracks === 'none') {
return 1;
}
if (tracks.startsWith('repeat(')) {
const match = tracks.match(/^repeat\(\s*(\d+)\s*,/);
return match ? parseInt(match[1], 10) : 1;
}
return Math.max(1, tracks.trim().split(/\s+/).filter(t => t.length > 0).length);
}
export function groupIotHubFilterItems(items: FilterParamInfo[], search: string): IotHubFilterGroup[] {

4
ui-ngx/src/app/modules/home/components/widget/lib/settings/common/action/custom-sample-html.raw

@ -6,7 +6,7 @@
<!-- -->
<!--<form #editEntityForm="ngForm" [formGroup]="editEntityFormGroup"-->
<!-- (ngSubmit)="save()" class="edit-entity-form">-->
<!-- <mat-toolbar class="flex flex-row" color="primary">-->
<!-- <mat-toolbar color="tb-primary" class="tb-bottom-border flex flex-row">-->
<!-- <h2>Edit {{entityType.toLowerCase()}} {{entityName}}</h2>-->
<!-- <span class="flex-1"></span>-->
<!-- <button mat-icon-button (click)="cancel()" type="button">-->
@ -198,7 +198,7 @@
<!---->
<!--<form #addEntityForm="ngForm" [formGroup]="addEntityFormGroup"-->
<!-- (ngSubmit)="save()" class="add-entity-form">-->
<!-- <mat-toolbar class="flex flex-row" color="primary">-->
<!-- <mat-toolbar color="tb-primary" class="tb-bottom-border flex flex-row">-->
<!-- <h2>Add entity</h2>-->
<!-- <span class="flex-1"></span>-->
<!-- <button mat-icon-button (click)="cancel()" type="button">-->

4
ui-ngx/src/app/modules/home/components/widget/lib/settings/common/action/mobile-action-editor.models.ts

@ -37,7 +37,7 @@ const processImageFunctionTemplate: TbFunction =
' imageDialogTemplate =\n' +
' \'<div aria-label="Image">\' +\n' +
' \'<form #theForm="ngForm">\' +\n' +
' \'<mat-toolbar class="flex flex-row" color="primary">\' +\n' +
' \'<mat-toolbar color="tb-primary" class="tb-bottom-border flex flex-row">\' +\n' +
' \'<h2>{{title}}</h2>\' +\n' +
' \'<span class="flex-1"></span>\' +\n' +
' \'<button mat-icon-button (click)="close()">\' +\n' +
@ -55,7 +55,7 @@ const processImageFunctionTemplate: TbFunction =
' \'</div>\' +\n' +
' \'<div mat-dialog-actions class="flex flex-row">\' +\n' +
' \'<span class="flex-1"></span>\' +\n' +
' \'<button mat-button (click)="close()" style="margin-right:20px;">Close</button>\' +\n' +
' \'<button mat-button color="primary" (click)="close()">Close</button>\' +\n' +
' \'</div>\' +\n' +
' \'</form>\' +\n' +
' \'</div>\';\n' +

2
ui-ngx/src/app/modules/home/components/widget/lib/settings/common/action/place-map-item-sample-html.raw

@ -4,7 +4,7 @@
<form #addEntityForm="ngForm" [formGroup]="addEntityFormGroup"
(ngSubmit)="save()" style="width: 552px">
<mat-toolbar class="flex flex-row" color="primary">
<mat-toolbar color="tb-primary" class="tb-bottom-border flex flex-row">
<h2>Add entity</h2>
<span class="flex-1"></span>
<button mat-icon-button (click)="cancel()" type="button">

2
ui-ngx/src/app/modules/home/pages/admin/white-labeling.component.html

@ -266,7 +266,7 @@
<mat-checkbox
[disabled]="wlSettings.get('hideConnectivityDialog')?.disabled"
[checked]="!wlSettings.get('hideConnectivityDialog')?.value"
(change)="wlSettings.get('hideConnectivityDialog')?.setValue(!$event.checked)">
(change)="onShowConnectivityDialogChange($event.checked)">
<div class="flex flex-col gap-1">
<div class="tb-wl-subtitle">{{ 'white-labeling.show-connectivity-dialog' | translate }}</div>
<div class="tb-wl-desc">{{ 'white-labeling.show-connectivity-dialog-desc' | translate }}</div>

15
ui-ngx/src/app/modules/home/pages/admin/white-labeling.component.ts

@ -301,14 +301,7 @@ export class WhiteLabelingComponent extends PageComponent implements OnInit, Has
whiteLabelingParams.primaryColorPanels = null;
}
(this.isLoginWl ? this.whiteLabelingService.saveLoginWhiteLabelParams(whiteLabelingParams) :
this.whiteLabelingService.saveWhiteLabelParams(whiteLabelingParams)).subscribe(() => {
this.whiteLabelingParams = whiteLabelingParams;
if (this.isLoginWl) {
this.loadWhiteLabelingParams();
} else {
this.wlSettings.markAsPristine();
}
});
this.whiteLabelingService.saveWhiteLabelParams(whiteLabelingParams)).subscribe(() => this.loadWhiteLabelingParams());
}
confirmForm(): UntypedFormGroup {
@ -386,6 +379,12 @@ export class WhiteLabelingComponent extends PageComponent implements OnInit, Has
});
}
onShowConnectivityDialogChange(checked: boolean): void {
const control = this.wlSettings.get('hideConnectivityDialog');
control.setValue(!checked);
control.markAsDirty();
}
private updatePaletteColors(): void {
this.selectedPrimaryColor = this.colorFromPalette(this.wlSettings.get('paletteSettings').get('primaryPalette').value);
this.selectedAccentColor = this.colorFromPalette(this.wlSettings.get('paletteSettings').get('accentPalette').value, false);

8
ui-ngx/src/app/modules/home/pages/customer/customer.component.html

@ -60,6 +60,14 @@
{{'customer.manage-edges' | translate }}
</button>
}
@if (resource.AGENT | hasGenericPermission: operation.READ) {
<button mat-stroked-button color="primary"
[disabled]="(isLoading$ | async)"
(click)="onEntityAction($event, 'manageAgents')"
[class.!hidden]="hideManageAgents() || isEdit">
{{'customer.manage-agents' | translate }}
</button>
}
@if (resource.DASHBOARD | hasGenericPermission: operation.READ) {
<button mat-stroked-button color="primary"
[disabled]="(isLoading$ | async)"

4
ui-ngx/src/app/modules/home/pages/customer/customer.component.ts

@ -103,6 +103,10 @@ export class CustomerComponent extends GroupContactBasedComponent<CustomerInfo>
}
}
hideManageAgents() {
return this.isGroupMode();
}
hideManageDashboards() {
if (this.isGroupMode()) {
return !this.groupEntitiesTableConfig.manageDashboardsEnabled(this.entity);

10
ui-ngx/src/app/modules/home/pages/customer/customers-table-config.resolver.ts

@ -208,16 +208,6 @@ export class CustomersTableConfigResolver {
}
);
}
if (this.userPermissionsService.hasGenericPermission(Resource.AGENT, Operation.READ)) {
actions.push(
{
name: this.translate.instant('customer.manage-customer-agents'),
icon: 'memory',
isEnabled: (customer) => true,
onAction: ($event, entity) => this.manageCustomerAgents($event, entity, config)
}
);
}
if (this.userPermissionsService.hasGenericPermission(Resource.DASHBOARD, Operation.READ)) {
actions.push(
{

3
ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html

@ -96,7 +96,8 @@
<div class="tb-creator-divider"></div>
<!-- Right: published items -->
<tb-iot-hub-search class="tb-creator-items" [creatorId]="creatorId" [showCreator]="false">
<tb-iot-hub-search class="tb-creator-items" [creatorId]="creatorId" [showCreator]="false"
[showFilters]="false">
<h3 class="tb-creator-items-heading">
{{ 'iot-hub.published-items' | translate }} ({{ creator.publishedCount }})
</h3>

1
ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-deep-link.utils.ts

@ -12,7 +12,6 @@ export function isUUID(s: string | null | undefined): s is string {
export function typeSegment(t: ItemType): string | undefined {
switch (t) {
case ItemType.WIDGET: return 'widgets';
case ItemType.DASHBOARD: return 'dashboards';
case ItemType.SOLUTION_TEMPLATE: return 'solution-templates';
case ItemType.CALCULATED_FIELD: return 'calculated-fields';
case ItemType.ALARM_RULE: return 'alarm-rules';

83
ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html

@ -54,13 +54,13 @@
[matAutocomplete]="searchAuto"
(input)="onSearchInput()"
(focus)="onSearchFocus()"
(keyup.enter)="onSearch()">
(keydown.enter)="onSearchEnter($event)">
@if (searchText) {
<button matSuffix mat-icon-button (click)="clearSearch()">
<mat-icon>close</mat-icon>
</button>
}
<button matSuffix mat-icon-button (click)="$event.stopPropagation(); onSearch()">
<button matSuffix mat-icon-button (click)="$event.stopPropagation(); seeAllResults()">
<mat-icon>search</mat-icon>
</button>
</mat-form-field>
@ -72,6 +72,13 @@
<mat-option [disabled]="true" class="tb-search-popup-loading">
<mat-spinner diameter="24"></mat-spinner>
</mat-option>
} @else if (searchFailed) {
<mat-option [disabled]="true" class="tb-search-popup-no-results">
<div class="tb-search-popup-no-results-content">
<mat-icon>cloud_off</mat-icon>
<span>{{ 'iot-hub.network-server-unavailable' | translate }}</span>
</div>
</mat-option>
} @else if (searchResults.length === 0 && searchLoaded) {
<mat-option [disabled]="true" class="tb-search-popup-no-results">
<div class="tb-search-popup-no-results-content">
@ -84,39 +91,55 @@
</div>
</mat-option>
} @else {
@for (group of searchResultGroups; track group.type) {
<mat-optgroup [label]="getSearchGroupLabel(group.type)">
@for (item of group.items; track item.id) {
<mat-option [value]="searchText" (click)="openItemDetail(item)">
@if (isCompactType(item.type)) {
<div class="tb-search-popup-icon-square" [style.background]="item.color || '#048ad3'">
<tb-icon class="tb-search-popup-icon-inner">{{ getCompactIcon(item) }}</tb-icon>
</div>
} @else {
<div class="tb-search-popup-thumbnail">
@if (getItemImage(item); as imgUrl) {
<img [src]="imgUrl" alt="">
@for (item of searchResults; track item.id) {
<mat-option class="tb-search-popup-item" [value]="searchText"
(onSelectionChange)="onRowSelected($event, item)">
<!-- One 99x56 frame for every row, so names line up. -->
<div class="tb-search-popup-thumbnail">
@if (isCompactType(item.type)) {
<div class="tb-search-popup-icon-square" [style.background]="item.color || '#048ad3'">
<tb-icon class="tb-search-popup-icon-inner">{{ getCompactIcon(item) }}</tb-icon>
</div>
} @else if (getItemImage(item); as imgUrl) {
<img [src]="imgUrl" alt="">
} @else {
<tb-icon class="tb-search-popup-thumb-placeholder">{{ getItemTypeIcon(item.type) }}</tb-icon>
}
</div>
<div class="tb-search-popup-text">
<span class="tb-search-popup-name">{{ item.name }}</span>
<span class="tb-search-popup-meta">
<span class="tb-search-popup-type" [style.--tb-search-popup-type-color]="getItemTypeColor(item.type)">
<tb-icon>{{ getItemTypeIcon(item.type) }}</tb-icon>
{{ getItemTypeLabel(item.type) }}
</span>
@if (item.creatorDisplayName) {
<span class="tb-search-popup-author">
@if (item.creatorVerified) {
<mat-icon class="tb-search-popup-verified">verified</mat-icon>
} @else {
<tb-icon class="tb-search-popup-thumb-placeholder">{{ getItemTypeIcon(item.type) }}</tb-icon>
<mat-icon>person</mat-icon>
}
</div>
}
<div class="tb-search-popup-text">
<span class="tb-search-popup-name">{{ item.name }}</span>
<span class="tb-search-popup-author">
<mat-icon>person</mat-icon>
{{ item.creatorDisplayName }}
<span class="tb-search-popup-author-name">{{ item.creatorDisplayName }}</span>
</span>
</div>
</mat-option>
}
</mat-optgroup>
}
</span>
</div>
</mat-option>
}
}
<div class="tb-search-popup-footer" role="button" tabindex="0"
(click)="seeAllResults()" (keyup.enter)="seeAllResults()">
{{ 'iot-hub.see-all-results' | translate }}
</div>
<mat-option class="tb-search-popup-footer" [value]="searchText"
(onSelectionChange)="onFooterSelected($event)">
@if (searchText?.trim(); as query) {
@if (searchTotal > searchResults.length) {
{{ 'iot-hub.see-all-results-for' | translate:{ count: searchTotal, search: query } }}
} @else {
{{ 'iot-hub.see-results-for' | translate:{ search: query } }}
}
} @else {
{{ 'iot-hub.see-all-results' | translate }}
}
</mat-option>
</mat-autocomplete>
</div>
</div>

128
ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss

@ -221,36 +221,14 @@
0 114px 46px 0 rgba(0, 0, 0, 0.01),
0 178px 50px 0 rgba(0, 0, 0, 0);
// Section group — 12px gap between groups
.mat-mdc-optgroup + .mat-mdc-optgroup .mat-mdc-optgroup-label {
margin-top: 12px;
}
// Section title — Design: 14px Medium, 0.25 tracking, black-tertiary, 4px V / 16px H
.mat-mdc-optgroup .mat-mdc-optgroup-label {
padding: 4px 16px;
min-height: 28px;
font-size: 14px;
font-weight: 500;
line-height: 20px;
letter-spacing: 0.25px;
color: rgba(0, 0, 0, 0.54);
white-space: nowrap;
// Shared by every row; each row kind below is selected by its own class.
.mat-mdc-option {
.mdc-list-item__primary-text {
font-size: 14px;
font-weight: 500;
line-height: 20px;
letter-spacing: 0.25px;
color: rgba(0, 0, 0, 0.54);
display: flex;
align-items: center;
gap: 16px;
width: 100%;
}
}
// Item row — Design: 8px V / 16px H, 16px gap, centered
.mat-mdc-optgroup .mat-mdc-option:not(.mat-mdc-option-multiple) {
padding: 8px 16px;
min-height: auto;
height: auto;
&:hover:not(.mdc-list-item--disabled),
&.mat-mdc-option-active:not(.mdc-list-item--disabled) {
@ -260,13 +238,13 @@
.mat-icon, tb-icon {
margin-right: 0;
}
}
.mdc-list-item__primary-text {
display: flex;
align-items: center;
gap: 16px;
width: 100%;
}
// Item row — Design: 8px V / 16px H, 16px gap, centered
.mat-mdc-option.tb-search-popup-item {
padding: 8px 16px;
min-height: auto;
height: auto;
}
// Thumbnail — Design: 99px x 56px, 4px radius, 1px border, 4% bg
@ -296,11 +274,11 @@
color: rgba(0, 0, 0, 0.38);
}
// Icon square — Design: 56x56, 4.667px radius, colored bg
// Icon tile for an item with no screenshot, centred in the thumbnail frame: 36x36, colored bg
.tb-search-popup-icon-square {
width: 56px;
height: 56px;
border-radius: 4.667px;
width: 36px;
height: 36px;
border-radius: 6px;
flex-shrink: 0;
display: flex;
align-items: center;
@ -308,9 +286,9 @@
}
.tb-search-popup-icon-inner {
font-size: 28px;
width: 28px;
height: 28px;
font-size: 22px;
width: 22px;
height: 22px;
color: white !important;
--tb-icon-color: white;
}
@ -347,13 +325,63 @@
letter-spacing: 0.25px;
color: rgba(0, 0, 0, 0.54);
white-space: nowrap;
min-width: 0;
mat-icon {
flex-shrink: 0;
font-size: 16px;
width: 16px;
height: 16px;
margin-right: 0;
color: rgba(0, 0, 0, 0.54);
// Same teal the IoT Hub item cards give a verified creator.
&.tb-search-popup-verified {
color: #00695c;
}
}
}
// Shares the meta row with the item type, so a long name is cut rather than overflowing.
.tb-search-popup-author-name {
overflow: hidden;
text-overflow: ellipsis;
}
// Meta row: the item type, a middle dot, then the author - "Widget · pinkevych.d".
.tb-search-popup-meta {
display: flex;
align-items: center;
gap: 4px;
min-width: 0;
}
// Item type in its colour, darkened so the paler ones stay legible.
.tb-search-popup-type {
display: flex;
align-items: center;
gap: 4px;
flex-shrink: 0;
font-size: 12px;
font-weight: 500;
line-height: 16px;
letter-spacing: 0.25px;
color: color-mix(in srgb, var(--tb-search-popup-type-color) 75%, #000);
white-space: nowrap;
tb-icon {
font-size: 14px;
width: 14px;
height: 14px;
line-height: 14px;
color: inherit;
}
// No author, nothing to separate from.
&:not(:last-child)::after {
content: '·';
font-weight: 700;
color: rgba(0, 0, 0, 0.54);
}
}
@ -371,6 +399,7 @@
.tb-search-popup-no-results {
pointer-events: none;
opacity: 1 !important;
padding: 8px 16px;
}
.tb-search-popup-no-results-content {
@ -392,26 +421,31 @@
}
// Footer — Design: 40px h, 8px V / 16px H, 1px top border, tb-primary text
.tb-search-popup-footer {
.mat-mdc-option.tb-search-popup-footer {
position: sticky;
bottom: 0;
z-index: 1;
border-top: 1px solid rgba(0, 0, 0, 0.12);
height: 40px;
min-height: 40px;
padding: 8px 16px;
display: flex;
align-items: center;
justify-content: flex-start;
font-size: 14px;
font-weight: 500;
line-height: 20px;
letter-spacing: 0.25px;
color: var(--tb-primary-500);
cursor: pointer;
background: white;
white-space: nowrap;
&:hover {
.mdc-list-item__primary-text {
justify-content: flex-start;
font: inherit;
letter-spacing: inherit;
color: inherit;
}
&:hover:not(.mdc-list-item--disabled),
&.mat-mdc-option-active:not(.mdc-list-item--disabled) {
background: #f5f5f5;
}
}

120
ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts

@ -3,14 +3,25 @@
import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/core';
import { Router } from '@angular/router';
import { MatAutocompleteTrigger } from '@angular/material/autocomplete';
import { MatOptionSelectionChange } from '@angular/material/core';
import { BreakpointObserver } from '@angular/cdk/layout';
import { forkJoin, Subject, Subscription } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';
import { forkJoin, of, Subject, Subscription } from 'rxjs';
import { catchError, debounceTime, switchMap } from 'rxjs/operators';
import { MediaBreakpoints } from '@shared/models/constants';
import { PageLink } from '@shared/models/page/page-link';
import { Direction, SortOrder } from '@shared/models/page/sort-order';
import { PageData } from '@shared/models/page/page-data';
import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models';
import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models';
import {
CROSS_TYPE_ITEM_TYPES,
getItemTypeColor,
isCompactItemType,
getItemTypeIcon,
ItemType,
itemTypeColors,
itemTypeTranslations,
RELEVANCE_SORT_PROPERTY
} from '@shared/models/iot-hub/iot-hub-item.models';
import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { TranslateService } from '@ngx-translate/core';
@ -32,15 +43,8 @@ interface HeroTypeConfig {
icon: string;
}
interface SearchResultGroup {
type: ItemType;
items: MpItemVersionView[];
}
const SEARCH_GROUP_ORDER: ItemType[] = [
ItemType.DEVICE, ItemType.SOLUTION_TEMPLATE, ItemType.WIDGET,
ItemType.CALCULATED_FIELD, ItemType.ALARM_RULE, ItemType.RULE_CHAIN
];
/** Rows the search popup shows: page 0 of the search page's own request. */
const SEARCH_POPUP_PAGE_SIZE = 10;
@Component({
selector: 'tb-iot-hub-home',
@ -51,12 +55,15 @@ const SEARCH_GROUP_ORDER: ItemType[] = [
export class TbIotHubHomeComponent implements OnInit, OnDestroy {
readonly ItemType = ItemType;
readonly isCompactType = isCompactItemType;
searchText = '';
searchResults: MpItemVersionView[] = [];
searchResultGroups: SearchResultGroup[] = [];
/** Everything the search matched, for the footer's "See all N results". */
searchTotal = 0;
searchLoaded = false;
searchLoading = false;
searchFailed = false;
@ViewChild(MatAutocompleteTrigger) searchAutoTrigger: MatAutocompleteTrigger;
@ViewChild('searchInput', {read: ElementRef}) searchInputRef: ElementRef;
private searchSubject = new Subject<string>();
@ -65,27 +72,27 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy {
heroTypes: HeroTypeConfig[] = [
{
type: ItemType.DEVICE, labelKey: 'item.type-device-plural', color: '#4b63cc',
type: ItemType.DEVICE, labelKey: 'item.type-device-plural', color: itemTypeColors[ItemType.DEVICE],
icon: 'assets/iot-hub/hero-device-cluster.svg'
},
{
type: ItemType.SOLUTION_TEMPLATE, labelKey: 'item.type-solution-template-plural', color: '#2b6bb4',
type: ItemType.SOLUTION_TEMPLATE, labelKey: 'item.type-solution-template-plural', color: itemTypeColors[ItemType.SOLUTION_TEMPLATE],
icon: 'assets/iot-hub/hero-solution-template-cluster.svg'
},
{
type: ItemType.WIDGET, labelKey: 'item.type-widget-plural', color: '#2c9755',
type: ItemType.WIDGET, labelKey: 'item.type-widget-plural', color: itemTypeColors[ItemType.WIDGET],
icon: 'assets/iot-hub/hero-widget-cluster.svg'
},
{
type: ItemType.CALCULATED_FIELD, labelKey: 'item.type-calculated-field-plural', color: '#3cb4e0',
type: ItemType.CALCULATED_FIELD, labelKey: 'item.type-calculated-field-plural', color: itemTypeColors[ItemType.CALCULATED_FIELD],
icon: 'assets/iot-hub/hero-calculated-field-cluster.svg'
},
{
type: ItemType.ALARM_RULE, labelKey: 'item.type-alarm-rule-plural', color: '#d66f2e',
type: ItemType.ALARM_RULE, labelKey: 'item.type-alarm-rule-plural', color: itemTypeColors[ItemType.ALARM_RULE],
icon: 'assets/iot-hub/hero-alarm-rule-cluster.svg'
},
{
type: ItemType.RULE_CHAIN, labelKey: 'item.type-rule-chain-plural', color: '#a95ae2',
type: ItemType.RULE_CHAIN, labelKey: 'item.type-rule-chain-plural', color: itemTypeColors[ItemType.RULE_CHAIN],
icon: 'assets/iot-hub/hero-rule-chain-cluster.svg'
}
];
@ -153,17 +160,23 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy {
});
this.searchSubscription = this.searchSubject.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap(text => {
this.searchLoading = true;
const sortOrder: SortOrder = { property: 'totalInstallCount', direction: Direction.DESC };
const pageLink = new PageLink(10, 0, text.trim() || null, sortOrder);
const query = new MpItemVersionQuery(pageLink);
return this.iotHubApiService.getPublishedVersions(query, { ignoreLoading: true });
const trimmed = text.trim();
// One list ranked across every type the platform surfaces. With an empty field relevance
// is served as the install count.
const sortOrder: SortOrder = { property: RELEVANCE_SORT_PROPERTY, direction: Direction.DESC };
const pageLink = new PageLink(SEARCH_POPUP_PAGE_SIZE, 0, trimmed || null, sortOrder);
const query = new MpItemVersionQuery(pageLink, { types: CROSS_TYPE_ITEM_TYPES });
// A failure must not end the subscription.
return this.iotHubApiService.getPublishedVersions(query, { ignoreLoading: true }).pipe(
catchError(() => of(null as PageData<MpItemVersionView>))
);
})
).subscribe(result => {
this.searchResults = result.data;
this.searchResultGroups = this.groupSearchResults(result.data);
).subscribe(page => {
this.searchFailed = !page;
this.searchResults = page?.data ?? [];
this.searchTotal = page?.totalElements ?? 0;
this.searchLoaded = true;
this.searchLoading = false;
});
@ -227,7 +240,26 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy {
setTimeout(() => this.searchAutoTrigger?.openPanel());
}
onSearch(): void {
onRowSelected(event: MatOptionSelectionChange, item: MpItemVersionView): void {
if (event.isUserInput) {
this.openItemDetail(item);
}
}
onFooterSelected(event: MatOptionSelectionChange): void {
if (event.isUserInput) {
this.seeAllResults();
}
}
/**
* Enter in the field opens the search page - unless the autocomplete has just used this press
* to select a highlighted row, which it marks with preventDefault before this handler runs.
*/
onSearchEnter(event: KeyboardEvent): void {
if (event.defaultPrevented || event.isComposing) {
return;
}
this.seeAllResults();
}
@ -237,12 +269,6 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy {
void this.router.navigate(['/iot-hub/search'], { queryParams: { search } });
}
isCompactType(type: ItemType): boolean {
return type === ItemType.CALCULATED_FIELD
|| type === ItemType.ALARM_RULE
|| type === ItemType.RULE_CHAIN;
}
getCompactIcon(item: MpItemVersionView): string {
return item.icon || getItemTypeIcon(item.type);
}
@ -255,9 +281,13 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy {
return getItemTypeIcon(type);
}
getSearchGroupLabel(type: ItemType): string {
getItemTypeColor(type: ItemType): string {
return getItemTypeColor(type);
}
getItemTypeLabel(type: ItemType): string {
const key = itemTypeTranslations.get(type);
return key ? this.translate.instant(key + '-plural') : type;
return key ? this.translate.instant(key) : type;
}
navigateToBrowse(type: ItemType): void {
@ -276,7 +306,6 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy {
private getTypeRoute(type: ItemType): string {
switch (type) {
case ItemType.WIDGET: return 'widgets';
case ItemType.DASHBOARD: return 'dashboards';
case ItemType.SOLUTION_TEMPLATE: return 'solution-templates';
case ItemType.CALCULATED_FIELD: return 'calculated-fields';
case ItemType.ALARM_RULE: return 'alarm-rules';
@ -523,21 +552,4 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy {
});
}
private groupSearchResults(items: MpItemVersionView[]): SearchResultGroup[] {
const groupMap = new Map<ItemType, MpItemVersionView[]>();
for (const item of items) {
if (!SEARCH_GROUP_ORDER.includes(item.type)) {
continue;
}
let list = groupMap.get(item.type);
if (!list) {
list = [];
groupMap.set(item.type, list);
}
list.push(item);
}
return SEARCH_GROUP_ORDER
.filter(type => groupMap.has(type))
.map(type => ({ type, items: groupMap.get(type) }));
}
}

7
ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.ts

@ -29,13 +29,6 @@ const PAGE_CONFIGS: Record<string, ItemTypePageConfig> = {
image: 'assets/iot-hub/items-page-widgets-hero.svg',
routeSegment: 'widgets'
},
DASHBOARD: {
type: ItemType.DASHBOARD,
titleKey: 'item.type-dashboard-plural',
descriptionKey: 'iot-hub.items-page-desc-dashboards',
image: 'assets/iot-hub/items-page-dashboards-hero.svg',
routeSegment: 'dashboards'
},
SOLUTION_TEMPLATE: {
type: ItemType.SOLUTION_TEMPLATE,
titleKey: 'item.type-solution-template-plural',

13
ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-routing.module.ts

@ -49,19 +49,6 @@ const routes: Routes = [
breadcrumb: { label: 'item.type-widget-plural', icon: 'widgets' }
}
},
{
path: 'dashboards',
component: TbIotHubItemsPageComponent,
data: {
auth: [Authority.TENANT_ADMIN],
canActivate: (userPermissionsService: UserPermissionsService): boolean => {
return userPermissionsService.hasGenericPermission(Resource.ALL, Operation.ALL);
},
title: 'item.type-dashboard-plural',
itemType: 'DASHBOARD',
breadcrumb: { label: 'item.type-dashboard-plural', icon: 'dashboard' }
}
},
{
path: 'solution-templates',
component: TbIotHubItemsPageComponent,

99
ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-search-page.component.scss

@ -8,12 +8,17 @@
height: 100%;
}
// Same frame as the type pages: one even padding on the card, and the search component pulled
// out to the card's edges by the same amount, so the rail, heading and grid line up.
.tb-search-page {
--tb-search-page-pad: 40px;
padding: var(--tb-search-page-pad) var(--tb-search-page-pad) calc(var(--tb-search-page-pad) + 8px);
}
// Back button
.tb-search-back-btn {
align-self: flex-start;
margin-top: 40px;
margin-left: 123px;
margin-left: -8px;
}
// Title
@ -30,100 +35,24 @@
color: rgba(0, 0, 0, 0.54);
}
// Full bleed; it pads its own rows back in through --tb-search-side-pad.
tb-iot-hub-search {
flex: 1;
min-height: 0;
padding-left: 123px;
padding-right: 123px;
::ng-deep {
.tb-search-divider {
margin-left: -123px;
margin-right: -123px;
}
.tb-results-container {
padding-right: 123px;
padding-bottom: 40px;
margin-right: -123px;
}
}
}
// Responsive
@media #{$mat-lt-xxl} {
.tb-search-back-btn {
margin-left: 40px;
}
tb-iot-hub-search {
padding-left: 40px;
padding-right: 40px;
::ng-deep {
.tb-search-divider {
margin-left: -40px;
margin-right: -40px;
}
.tb-results-container {
padding-right: 40px;
margin-right: -40px;
}
}
}
--tb-search-side-pad: var(--tb-search-page-pad);
margin-left: calc(-1 * var(--tb-search-page-pad));
margin-right: calc(-1 * var(--tb-search-page-pad));
}
@media #{$mat-lt-lg} {
.tb-search-back-btn {
margin-top: 24px;
margin-left: 24px;
}
tb-iot-hub-search {
padding-left: 24px;
padding-right: 24px;
::ng-deep {
.tb-search-divider {
margin-left: -24px;
margin-right: -24px;
}
.tb-results-container {
padding-right: 24px;
padding-bottom: 24px;
margin-right: -24px;
}
}
.tb-search-page {
--tb-search-page-pad: 24px;
}
}
@media #{$mat-lt-sm} {
.tb-search-page {
--tb-search-page-pad: 16px;
gap: 16px;
}
.tb-search-back-btn {
margin-top: 16px;
margin-left: 16px;
}
tb-iot-hub-search {
padding-left: 16px;
padding-right: 16px;
::ng-deep {
.tb-search-divider {
margin-left: -16px;
margin-right: -16px;
}
.tb-results-container {
padding-right: 16px;
padding-bottom: 16px;
margin-right: -16px;
}
}
}
}

2
ui-ngx/src/app/modules/home/pages/reporting/report/manage-report-public-access-modal.component.html

@ -4,7 +4,7 @@
SPDX-License-Identifier: BUSL-1.1
-->
<mat-toolbar class="flex flex-row" color="primary">
<mat-toolbar color="tb-primary" class="tb-bottom-border flex flex-row">
<h2>{{ 'report.manage-public-access' | translate }}</h2>
<span class="flex-1"></span>
<button mat-icon-button

188
ui-ngx/src/app/shared/directives/photoswipe-gallery.directive.ts

@ -1,17 +1,35 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
import { Directive, ElementRef, Input, OnDestroy, OnInit } from '@angular/core';
import { Directive, ElementRef, EventEmitter, Input, NgZone, OnDestroy, OnInit, Output } from '@angular/core';
import PhotoSwipeLightbox from 'photoswipe/lightbox';
import PhotoSwipe from 'photoswipe';
import cssjs from '@core/css/css';
const PHOTO_GALLERY_STYLE_ID = 'photoswipe-gallery-style';
// Share of the available area an opened image takes, leaving backdrop to click and room for close
const SHRINK_FILL = 0.86;
const GROW_FILL = 0.95;
/** Upper bound for enlarging a small image, relative to its own size. */
const MAX_UPSCALE = 2;
/** How far a click-to-zoom steps past the level the image opened at. */
const ZOOM_STEP = 2;
// Symmetric, so the image stays centred; the caption floats over the bottom padding
const VIEWPORT_PADDING = { top: 64, bottom: 64, left: 24, right: 24 };
const PHOTO_GALLERY_CLASS = 'tb-photoswipe-gallery';
const PHOTO_GALLERY_STYLE =
'{\n'+
' background: rgba(10, 10, 20, 0.55);\n' +
// PhotoSwipe's own transform/will-change create a layer backdrop-filter cannot see through
'{\n' +
' transform: none;\n' +
' will-change: auto;\n' +
'}\n' +
'\n' +
// On .pswp__bg, the layer PhotoSwipe fades in with the zoom
'.pswp__bg {\n' +
' background: rgba(10, 10, 20, 0.55);\n' +
' backdrop-filter: blur(18px);\n' +
' opacity: 1;\n' +
' -webkit-backdrop-filter: blur(18px);\n' +
' transform: none;\n' +
' will-change: backdrop-filter;\n' +
'}\n' +
'\n' +
'.pswp__tb-photoswipe-caption {\n' +
@ -49,12 +67,18 @@ const PHOTO_GALLERY_STYLE =
'.pswp__item img.pswp__img {\n' +
' display: block;\n' +
' object-fit: contain;\n' +
' border-radius: 4px; \n' +
' box-shadow: 0 20px 60px #00000080;\n' +
' border-radius: 4px;\n' +
'}\n' +
'\n' +
// drop-shadow follows transparency; on the wrap so it survives the placeholder swap
'.pswp__zoom-wrap {\n' +
' filter: drop-shadow(0 20px 30px rgba(0, 0, 0, 0.5));\n' +
'}\n' +
'\n' +
// PhotoSwipe's #222 placeholder background flashes against the translucent backdrop
'.pswp__item .pswp__img--placeholder {\n' +
' border-radius: 4px; \n' +
' background: transparent;\n' +
' border-radius: 4px;\n' +
'}\n' +
'\n' +
'.pswp__button {\n' +
@ -117,6 +141,49 @@ const PHOTO_GALLERY_STYLE =
' right: 12px;\n' +
'}';
/** The parts of PhotoSwipe's ZoomLevel this directive needs; `panAreaSize` already excludes padding. */
interface ZoomLevelSizes {
fit: number;
panAreaSize: { x: number; y: number } | null;
elementSize: { x: number; y: number } | null;
}
/** PhotoSwipe's `fit` is capped at 1; use the raw ratio so a small image grows, up to MAX_UPSCALE. */
function initialZoom(zoomLevel: ZoomLevelSizes): number {
const { panAreaSize, elementSize } = zoomLevel;
if (!panAreaSize || !elementSize?.x || !elementSize?.y) {
return zoomLevel.fit;
}
const fitRatio = Math.min(panAreaSize.x / elementSize.x, panAreaSize.y / elementSize.y);
if (fitRatio <= 1) {
return fitRatio * SHRINK_FILL;
}
return Math.min(fitRatio * GROW_FILL, MAX_UPSCALE);
}
/** Click-to-zoom level; always above the opening level, so the click visibly zooms. */
function secondaryZoom(zoomLevel: ZoomLevelSizes): number {
return Math.max(initialZoom(zoomLevel) * ZOOM_STEP, Math.min(1, zoomLevel.fit * 3));
}
// A gallery child may be a container with no image in it
function thumbnailImage(element: Element): HTMLImageElement | null {
return element instanceof HTMLImageElement ? element : element.querySelector('img');
}
/** Bounds of the pixels an `object-fit: contain` image paints, centred inside its box. */
function containedImageBounds(image: HTMLImageElement): { x: number; y: number; w: number } {
const rect = image.getBoundingClientRect();
const scale = Math.min(rect.width / image.naturalWidth, rect.height / image.naturalHeight);
const width = image.naturalWidth * scale;
const height = image.naturalHeight * scale;
return {
x: rect.left + (rect.width - width) / 2,
y: rect.top + (rect.height - height) / 2,
w: width
};
}
@Directive({
selector: '[tbPhotoSwipeGallery]',
standalone: false
@ -126,10 +193,17 @@ export class PhotoSwipeGalleryDirective implements OnInit, OnDestroy {
@Input() galleryChildrenSelector = '.tb-image';
@Input() imageCaptionSelector = '.tb-image-tooltip';
@Output() readonly lightboxOpened = new EventEmitter<void>();
@Output() readonly lightboxClosed = new EventEmitter<void>();
/** The slide the lightbox moved to, emitted while it is still open. */
@Output() readonly slideChanged = new EventEmitter<number>();
private lightbox: PhotoSwipeLightbox;
private closeOnOpened = false;
constructor(
private elementRef: ElementRef<HTMLElement>
private elementRef: ElementRef<HTMLElement>,
private ngZone: NgZone
) {}
ngOnInit(): void {
@ -139,22 +213,38 @@ export class PhotoSwipeGalleryDirective implements OnInit, OnDestroy {
children: this.galleryChildrenSelector,
pswpModule: PhotoSwipe,
counter: false,
bgOpacity: 0,
mainClass: PHOTO_GALLERY_CLASS
// No toolbar magnifier: zoom stays on scroll and click
zoom: false,
// The backdrop look lives in PHOTO_GALLERY_STYLE; PhotoSwipe fades it in up to this opacity
bgOpacity: 1,
mainClass: PHOTO_GALLERY_CLASS,
padding: VIEWPORT_PADDING,
// The scroll lock only preventDefaults wheel, so PhotoSwipe still receives it
wheelToZoom: true,
initialZoomLevel: zoomLevel => initialZoom(zoomLevel),
secondaryZoomLevel: zoomLevel => secondaryZoom(zoomLevel)
});
this.lightbox.addFilter('domItemData', (itemData, element) => {
let image: HTMLImageElement;
if (element instanceof HTMLImageElement) {
image = element;
} else {
image = element.querySelector('img');
const image = thumbnailImage(element);
if (!image) {
return itemData;
}
itemData.src = image.src;
itemData.width = image.naturalWidth;
itemData.height = image.naturalHeight;
itemData.thumbCropped = true;
// Only a cover-fitted thumbnail is cropped; otherwise the zoom starts from a clipped frame
itemData.thumbCropped = getComputedStyle(image).objectFit === 'cover';
return itemData;
});
// PhotoSwipe measures the thumbnail's box, but `contain` paints a smaller image inside it,
// so the zoom would start off the visible pixels
this.lightbox.addFilter('thumbBounds', (thumbBounds, itemData) => {
const image = itemData.element ? thumbnailImage(itemData.element) : null;
if (!image?.naturalWidth || getComputedStyle(image).objectFit !== 'contain') {
return thumbBounds;
}
return containedImageBounds(image);
});
this.lightbox.on('uiRegister', () => {
this.lightbox.pswp.ui.registerElement({
name: 'tb-photoswipe-caption',
@ -182,15 +272,81 @@ export class PhotoSwipeGalleryDirective implements OnInit, OnDestroy {
}
});
});
// Emitted while still open: PhotoSwipe reads the thumbnail position when closing starts, so a
// host carousel must already show the matching slide by then
this.lightbox.on('change', () => {
this.ngZone.run(() => this.slideChanged.emit(this.lightbox.pswp.currIndex));
});
this.lightbox.on('beforeOpen', () => {
this.attachDocumentListeners();
this.ngZone.run(() => this.lightboxOpened.emit());
});
this.lightbox.on('destroy', () => {
this.detachDocumentListeners();
this.ngZone.run(() => this.lightboxClosed.emit());
});
this.lightbox.init();
}
ngOnDestroy(): void {
this.detachDocumentListeners();
if (this.lightbox) {
this.lightbox.destroy();
}
}
/**
* Escape closes the image only, not a mat-dialog behind it. Runs in the capture phase, ahead of
* the CDK overlay, and closes PhotoSwipe itself: stopping propagation also keeps the key from
* PhotoSwipe's own bubble-phase handler on document.
*/
private readonly onKeydownCapture = (e: KeyboardEvent): void => {
const pswp = this.lightbox?.pswp;
if (e.key !== 'Escape' || !pswp) {
return;
}
e.stopPropagation();
e.preventDefault();
if (pswp.opener?.isOpen) {
pswp.close();
return;
}
// During the opening zoom close() is a no-op, so close once it ends (only once)
if (this.closeOnOpened) {
return;
}
this.closeOnOpened = true;
pswp.on('openingAnimationEnd', () => pswp.close());
};
private readonly onScrollEvent = (e: Event): void => {
// Touch gestures inside the lightbox belong to PhotoSwipe (pan, pinch, swipe)
if (e.type === 'touchmove' && this.lightbox?.pswp?.element?.contains(e.target as Node)) {
return;
}
e.preventDefault();
};
/**
* Escape interception plus the page scroll lock. PhotoSwipe does not lock page scroll, and the
* scroller may be the page or a dialog pane, so the wheel and touch events are blocked instead.
* Outside the zone, since touchmove fires at ~60 Hz during a pinch or pan.
*/
private attachDocumentListeners(): void {
this.ngZone.runOutsideAngular(() => {
document.addEventListener('keydown', this.onKeydownCapture, true);
document.addEventListener('wheel', this.onScrollEvent, { passive: false, capture: true });
document.addEventListener('touchmove', this.onScrollEvent, { passive: false, capture: true });
});
}
private detachDocumentListeners(): void {
this.closeOnOpened = false;
document.removeEventListener('keydown', this.onKeydownCapture, true);
document.removeEventListener('wheel', this.onScrollEvent, true);
document.removeEventListener('touchmove', this.onScrollEvent, true);
}
private initPhotoSwipeGalleryStyle(): void {
const existingElement = document.getElementById(PHOTO_GALLERY_STYLE_ID);
if (!existingElement) {

10
ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts

@ -10,11 +10,6 @@ export interface WidgetInstalledItemDescriptor {
widgetTypeId: { id: string };
}
export interface DashboardInstalledItemDescriptor {
type: 'DASHBOARD';
dashboardId: { id: string };
}
export interface CalculatedFieldInstalledItemDescriptor {
type: 'CALCULATED_FIELD';
calculatedFieldId: { id: string };
@ -52,7 +47,6 @@ export interface SolutionTemplateInstalledItemDescriptor {
export type IotHubInstalledItemDescriptor =
| WidgetInstalledItemDescriptor
| DashboardInstalledItemDescriptor
| CalculatedFieldInstalledItemDescriptor
| AlarmRuleInstalledItemDescriptor
| RuleChainInstalledItemDescriptor
@ -142,10 +136,6 @@ export const getInstalledItemUrl = (descriptor?: IotHubInstalledItemDescriptor):
entityId = descriptor.widgetTypeId?.id;
entityType = EntityType.WIDGET_TYPE;
break;
case 'DASHBOARD':
entityId = descriptor.dashboardId?.id;
entityType = EntityType.DASHBOARD;
break;
case 'CALCULATED_FIELD':
case 'ALARM_RULE':
entityId = descriptor.calculatedFieldId?.id;

58
ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts

@ -1,8 +1,9 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
import { Direction } from '@shared/models/page/sort-order';
export enum ItemType {
WIDGET = 'WIDGET',
DASHBOARD = 'DASHBOARD',
SOLUTION_TEMPLATE = 'SOLUTION_TEMPLATE',
CALCULATED_FIELD = 'CALCULATED_FIELD',
ALARM_RULE = 'ALARM_RULE',
@ -13,7 +14,6 @@ export enum ItemType {
export const itemTypeTranslations = new Map<ItemType, string>(
[
[ItemType.WIDGET, 'item.type-widget'],
[ItemType.DASHBOARD, 'item.type-dashboard'],
[ItemType.SOLUTION_TEMPLATE, 'item.type-solution-template'],
[ItemType.CALCULATED_FIELD, 'item.type-calculated-field'],
[ItemType.ALARM_RULE, 'item.type-alarm-rule'],
@ -28,7 +28,6 @@ export const itemTypeTranslations = new Map<ItemType, string>(
// mapping stays consistent across the app.
export const itemTypeIcons: Record<string, string> = {
[ItemType.WIDGET]: 'widgets',
[ItemType.DASHBOARD]: 'dashboard',
[ItemType.SOLUTION_TEMPLATE]: 'apps',
[ItemType.CALCULATED_FIELD]: 'mdi:function-variant',
[ItemType.RULE_CHAIN]: 'settings_ethernet',
@ -39,11 +38,24 @@ export const itemTypeIcons: Record<string, string> = {
export const getItemTypeIcon = (type?: string | null): string =>
type && itemTypeIcons[type] ? itemTypeIcons[type] : 'category';
/** Colour for a type with no colour of its own. */
export const DEFAULT_ITEM_TYPE_COLOR = '#5f6368';
/** Colour per item type, wherever an item's type is marked with one. */
export const itemTypeColors: Record<string, string> = {
[ItemType.WIDGET]: '#2c9755',
[ItemType.SOLUTION_TEMPLATE]: '#2b6bb4',
[ItemType.CALCULATED_FIELD]: '#3cb4e0',
[ItemType.RULE_CHAIN]: '#a95ae2',
[ItemType.ALARM_RULE]: '#d66f2e',
[ItemType.DEVICE]: '#4b63cc'
};
export const getItemTypeColor = (type?: string | null): string =>
type && itemTypeColors[type] ? itemTypeColors[type] : DEFAULT_ITEM_TYPE_COLOR;
/**
* Item types discoverable to creators in the marketplace UI.
* DASHBOARD is intentionally absent (IoT Hub no longer accepts Dashboard contributions).
* Defensive code paths (item card, detail dialog descriptor switch, installed-items table,
* install handler, /iot-hub/dashboards route) remain functional for already-installed items.
*/
export const CREATOR_VISIBLE_ITEM_TYPES: ItemType[] = [
ItemType.WIDGET,
@ -54,6 +66,40 @@ export const CREATOR_VISIBLE_ITEM_TYPES: ItemType[] = [
ItemType.RULE_CHAIN,
];
/** Item types a cross-type surface (search page, popup) shows, in display order. */
export const CROSS_TYPE_ITEM_TYPES: ItemType[] = [
ItemType.DEVICE,
ItemType.SOLUTION_TEMPLATE,
ItemType.WIDGET,
ItemType.CALCULATED_FIELD,
ItemType.ALARM_RULE,
ItemType.RULE_CHAIN,
];
/** Types drawn as a coloured icon tile rather than a screenshot. */
export const isCompactItemType = (type?: string | null): boolean =>
type === ItemType.CALCULATED_FIELD || type === ItemType.ALARM_RULE || type === ItemType.RULE_CHAIN;
/** Sort property served by relevance ranking. */
export const RELEVANCE_SORT_PROPERTY = 'relevance';
export interface SortOption {
value: string;
label: string;
direction: Direction;
}
/**
* The sort menu of every IoT Hub surface with a search field; the first entry is the default.
* Relevance stays the default with an empty field, where it orders by install count.
*/
export const IOT_HUB_SORT_OPTIONS: SortOption[] = [
{ value: RELEVANCE_SORT_PROPERTY, label: 'iot-hub.sort-most-relevant', direction: Direction.DESC },
{ value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC },
{ value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC },
{ value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC }
];
export interface FilterParamInfo {
key: string;
totalItems: number;

100
ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts

@ -119,7 +119,10 @@ export interface ListingItemVersionNotFound {
}
export interface MpItemVersionQueryOptions {
/** Single item type, for a surface pinned to one (the type pages, the add-item dialog). */
type?: string;
/** Several item types at once, sent as a repeated `type` parameter. */
types?: string[];
ceOnly?: boolean;
creatorId?: string;
categories?: string[];
@ -132,53 +135,66 @@ export interface MpItemVersionQueryOptions {
connectivity?: string[];
vendors?: string[];
scadaFirst?: boolean;
// Serialized only when true: the API matches the value, so `false` would mean "unverified only"
creatorVerified?: boolean;
}
/** Every filter, as `&name=value` pairs. */
function filtersToQuery(o: MpItemVersionQueryOptions): string {
let query = '';
if (o.type) {
query += `&type=${encodeURIComponent(o.type)}`;
}
if (o.types?.length) {
query += o.types.map(t => `&type=${encodeURIComponent(t)}`).join('');
}
if (o.ceOnly != null) {
query += `&ceOnly=${o.ceOnly}`;
}
if (o.creatorId) {
query += `&creatorId=${encodeURIComponent(o.creatorId)}`;
}
if (o.categories?.length) {
query += o.categories.map(c => `&categories=${encodeURIComponent(c)}`).join('');
}
if (o.useCases?.length) {
query += o.useCases.map(u => `&useCases=${encodeURIComponent(u)}`).join('');
}
if (o.cfTypes?.length) {
query += o.cfTypes.map(t => `&cfTypes=${encodeURIComponent(t)}`).join('');
}
if (o.widgetTypes?.length) {
query += o.widgetTypes.map(t => `&widgetTypes=${encodeURIComponent(t)}`).join('');
}
if (o.ruleChainTypes?.length) {
query += o.ruleChainTypes.map(t => `&ruleChainTypes=${encodeURIComponent(t)}`).join('');
}
if (o.tbVersion != null) {
query += `&tbVersion=${o.tbVersion}`;
}
if (o.hardwareTypes?.length) {
query += o.hardwareTypes.map(ht => `&hardwareTypes=${encodeURIComponent(ht)}`).join('');
}
if (o.connectivity?.length) {
query += o.connectivity.map(c => `&connectivity=${encodeURIComponent(c)}`).join('');
}
if (o.vendors?.length) {
query += o.vendors.map(v => `&vendors=${encodeURIComponent(v)}`).join('');
}
if (o.scadaFirst != null) {
query += `&scadaFirst=${o.scadaFirst}`;
}
if (o.creatorVerified) {
query += `&creatorVerified=true`;
}
return query;
}
/** A paged read: the filters, and the page to cut out of them. */
export class MpItemVersionQuery {
constructor(public pageLink: PageLink, public options: MpItemVersionQueryOptions = {}) {}
public toQuery(): string {
let query = this.pageLink.toQuery();
const o = this.options;
if (o.type) {
query += `&type=${o.type}`;
}
if (o.ceOnly != null) {
query += `&ceOnly=${o.ceOnly}`;
}
if (o.creatorId) {
query += `&creatorId=${o.creatorId}`;
}
if (o.categories?.length) {
query += o.categories.map(c => `&categories=${encodeURIComponent(c)}`).join('');
}
if (o.useCases?.length) {
query += o.useCases.map(u => `&useCases=${encodeURIComponent(u)}`).join('');
}
if (o.cfTypes?.length) {
query += o.cfTypes.map(t => `&cfTypes=${encodeURIComponent(t)}`).join('');
}
if (o.widgetTypes?.length) {
query += o.widgetTypes.map(t => `&widgetTypes=${encodeURIComponent(t)}`).join('');
}
if (o.ruleChainTypes?.length) {
query += o.ruleChainTypes.map(t => `&ruleChainTypes=${encodeURIComponent(t)}`).join('');
}
if (o.tbVersion != null) {
query += `&tbVersion=${o.tbVersion}`;
}
if (o.hardwareTypes?.length) {
query += o.hardwareTypes.map(ht => `&hardwareTypes=${encodeURIComponent(ht)}`).join('');
}
if (o.connectivity?.length) {
query += o.connectivity.map(c => `&connectivity=${encodeURIComponent(c)}`).join('');
}
if (o.vendors?.length) {
query += o.vendors.map(v => `&vendors=${encodeURIComponent(v)}`).join('');
}
if (o.scadaFirst != null) {
query += `&scadaFirst=${o.scadaFirst}`;
}
return query;
return this.pageLink.toQuery() + filtersToQuery(this.options);
}
}

2
ui-ngx/src/assets/help/en_US/widget/action/examples/custom_pretty_create_dialog_html.md

@ -4,7 +4,7 @@
{:code-style="max-height: 400px;"}
<form #addEntityForm="ngForm" [formGroup]="addEntityFormGroup"
(ngSubmit)="save()" class="add-entity-form">
<mat-toolbar class="flex flex-row" color="primary">
<mat-toolbar color="tb-primary" class="tb-bottom-border flex flex-row">
<h2>Add entity</h2>
<span class="flex-1"></span>
<button mat-icon-button (click)="cancel()" type="button">

2
ui-ngx/src/assets/help/en_US/widget/action/examples/custom_pretty_edit_dialog_html.md

@ -4,7 +4,7 @@
{:code-style="max-height: 400px;"}
<form #editEntityForm="ngForm" [formGroup]="editEntityFormGroup"
(ngSubmit)="save()" class="edit-entity-form">
<mat-toolbar class="flex flex-row" color="primary">
<mat-toolbar color="tb-primary" class="tb-bottom-border flex flex-row">
<h2>Edit {{entityType.toLowerCase()}} {{entityName}}</h2>
<span class="flex-1"></span>
<button mat-icon-button (click)="cancel()" type="button">

2
ui-ngx/src/assets/help/en_US/widget/action/examples_custom_pretty/custom_pretty_clone_device_html.md

@ -3,7 +3,7 @@
```html
{:code-style="max-height: 400px;"}
<form [formGroup]="cloneDeviceFormGroup" (ngSubmit)="save()" style="min-width:320px;">
<mat-toolbar class="flex flex-row" color="primary">
<mat-toolbar color="tb-primary" class="tb-bottom-border flex flex-row">
<h2>Clone device: {{ deviceName }}</h2>
<span class="flex-1"></span>
<button mat-icon-button (click)="cancel()"

2
ui-ngx/src/assets/help/en_US/widget/action/examples_custom_pretty/custom_pretty_create_dialog_html.md

@ -4,7 +4,7 @@
{:code-style="max-height: 400px;"}
<form #addEntityForm="ngForm" [formGroup]="addEntityFormGroup"
(ngSubmit)="save()" class="add-entity-form">
<mat-toolbar class="flex flex-row" color="primary">
<mat-toolbar color="tb-primary" class="tb-bottom-border flex flex-row">
<h2>Add entity</h2>
<span class="flex-1"></span>
<button mat-icon-button (click)="cancel()" type="button">

2
ui-ngx/src/assets/help/en_US/widget/action/examples_custom_pretty/custom_pretty_create_user_html.md

@ -3,7 +3,7 @@
```html
{:code-style="max-height: 400px;"}
<form [formGroup]="addEntityFormGroup" (ngSubmit)="save()" style="min-width:480px;">
<mat-toolbar class="flex flex-row" color="primary">
<mat-toolbar color="tb-primary" class="tb-bottom-border flex flex-row">
<h2>Add new User</h2>
<span class="flex-1"></span>
<button mat-icon-button (click)="cancel()" type="button">

2
ui-ngx/src/assets/help/en_US/widget/action/examples_custom_pretty/custom_pretty_create_user_js.md

@ -91,7 +91,7 @@ function ActivationLinkDialogController(instance) {
}
let activationLinkDialogTemplate = `<form style="min-width: 400px; position: relative;">
<mat-toolbar color="primary">
<mat-toolbar color="tb-primary" class="tb-bottom-border flex flex-row">
<h2 translate>user.activation-link</h2>
<span class="flex-1"></span>
<button mat-icon-button

2
ui-ngx/src/assets/help/en_US/widget/action/examples_custom_pretty/custom_pretty_edit_dialog_html.md

@ -4,7 +4,7 @@
{:code-style="max-height: 400px;"}
<form #editEntityForm="ngForm" [formGroup]="editEntityFormGroup"
(ngSubmit)="save()" class="edit-entity-form">
<mat-toolbar class="flex flex-row" color="primary">
<mat-toolbar color="tb-primary" class="tb-bottom-border flex flex-row">
<h2>Edit {{entityType.toLowerCase()}} {{entityName}}</h2>
<span class="flex-1"></span>
<button mat-icon-button (click)="cancel()" type="button">

12
ui-ngx/src/assets/help/en_US/widget/action/examples_custom_pretty/custom_pretty_edit_image_html.md

@ -3,7 +3,7 @@
```html
{:code-style="max-height: 400px;"}
<form [formGroup]="editEntity" (ngSubmit)="save()" class="edit-entity-form">
<mat-toolbar class="flex flex-row" color="primary">
<mat-toolbar color="tb-primary" class="tb-bottom-border flex flex-row">
<h2>Edit {{entityName}} image</h2>
<span class="flex-1"></span>
<button mat-icon-button (click)="cancel()" type="button">
@ -22,17 +22,17 @@
</div>
</div>
<div mat-dialog-actions class="flex flex-row items-center justify-end">
<button mat-button mat-raised-button color="primary"
type="submit"
[disabled]="(isLoading$ | async) || editEntity.invalid || !editEntity.dirty">
Save
</button>
<button mat-button color="primary"
type="button"
[disabled]="(isLoading$ | async)"
(click)="cancel()" cdkFocusInitial>
Cancel
</button>
<button mat-button mat-raised-button color="primary"
type="submit"
[disabled]="(isLoading$ | async) || editEntity.invalid || !editEntity.dirty">
Save
</button>
</div>
</form>
{:copy-code}

4
ui-ngx/src/assets/help/en_US/widget/action/mobile_process_image_fn.md

@ -56,7 +56,7 @@ function showImageDialog(title, imageUrl) {
var imageDialogTemplate =
'<div aria-label="Image">' +
'<form #theForm="ngForm">' +
'<mat-toolbar class="flex flex-row" color="primary">' +
'<mat-toolbar color="tb-primary" class="tb-bottom-border flex flex-row">' +
'<h2>{{title}}</h2>' +
'<span class="flex-1"></span>' +
'<button mat-icon-button (click)="close()">' +
@ -74,7 +74,7 @@ var imageDialogTemplate =
'</div>' +
'<div mat-dialog-actions class="flex flex-row">' +
'<span class="flex-1"></span>' +
'<button mat-button (click)="close()" style="margin-right:20px;">Close</button>' +
'<button mat-button color="primary" (click)="close()">Close</button>' +
'</div>' +
'</form>' +
'</div>';

2
ui-ngx/src/assets/help/en_US/widget/action/place_map_item/create_dialog_html.md

@ -4,7 +4,7 @@
{:code-style="max-height: 400px;"}
<form #addEntityForm="ngForm" [formGroup]="addEntityFormGroup"
(ngSubmit)="save()" style="width: 552px">
<mat-toolbar class="flex flex-row" color="primary">
<mat-toolbar color="tb-primary" class="tb-bottom-border flex flex-row">
<h2>Add entity</h2>
<span class="flex-1"></span>
<button mat-icon-button (click)="cancel()" type="button">

102
ui-ngx/src/assets/iot-hub/items-page-dashboards-hero.svg

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 95 KiB

16
ui-ngx/src/assets/locale/locale.constant-en_US.json

@ -2175,7 +2175,6 @@
"manage-public-dashboards": "Manage public dashboards",
"manage-customer-assets": "Manage customer assets",
"manage-customer-edges": "Manage customer edges",
"manage-customer-agents": "Manage agents",
"manage-public-assets": "Manage public assets",
"add-customer-text": "Add new customer",
"no-customers-text": "No customers found",
@ -2220,7 +2219,8 @@
"search": "Search customers",
"selected-customers": "{ count, plural, =1 {1 customer} other {# customers} } selected",
"edges": "Customer edge instances",
"manage-edges": "Manage edges"
"manage-edges": "Manage edges",
"manage-agents": "Manage agents"
},
"customers-hierarchy": {
"customers-hierarchy": "Customers hierarchy",
@ -6272,8 +6272,6 @@
"item": {
"type-widget": "Widget",
"type-widget-plural": "Widgets",
"type-dashboard": "Dashboard",
"type-dashboard-plural": "Dashboards",
"type-solution-template": "Solution Template",
"type-solution-template-plural": "Solution Templates",
"type-calculated-field": "Calculated Field",
@ -6295,6 +6293,8 @@
"search": "Search...",
"search-published-items": "Search published items...",
"see-all-results": "See all results",
"see-all-results-for": "See all {{ count }} results for \"{{ search }}\"",
"see-results-for": "See results for \"{{ search }}\"",
"no-search-results": "No results found for '{{ search }}'",
"no-items-available": "No items available",
"search-results": "Search results",
@ -6317,9 +6317,9 @@
"type": "Type",
"items-per-page": "Items per page",
"filter": "Filter",
"clear-filters": "Clear filters",
"available": "Available",
"items-page-desc-widgets": "Jumpstart your IoT journey with pre-configured widgets designed for your industry. Deploy proven architectures instantly and focus your energy on what matters: your unique business logic.",
"items-page-desc-dashboards": "Explore dashboards to find pre-built visualization templates and interactive UI layouts you can deploy in minutes to bring your IoT data to life.",
"items-page-desc-solution-templates": "Complete IoT solution packages with dashboards, rule chains, and device configurations. Get started with proven architectures.",
"items-page-desc-calculated-fields": "Use pre-configured Calculated Fields to automate complex metrics like fuel efficiency or power factor. Skip the manual logic and keep your dashboards clean and actionable.",
"items-page-desc-alarm-rules": "Use pre-built Alarm Rule templates to detect critical conditions like low battery, threshold breaches, or devices going offline. Skip writing the rule logic and start reacting to incidents the moment they happen.",
@ -6334,29 +6334,28 @@
"contribute": "Contribute",
"creator-profile": "Creator Profile",
"title-widgets": "Widgets",
"title-dashboards": "Dashboards",
"title-calculated-fields": "Calculated Fields",
"title-alarm-rules": "Alarm Rules",
"title-rule-chains": "Rule Chains",
"title-devices": "Devices",
"title-solution-templates": "Solution Templates",
"subtitle-widgets": "Browse community widgets for your dashboards",
"subtitle-dashboards": "Browse ready-to-use dashboards",
"subtitle-solution-templates": "Browse complete IoT solution packages",
"subtitle-calculated-fields": "Browse calculated field templates",
"subtitle-alarm-rules": "Browse alarm rule templates",
"subtitle-rule-chains": "Browse rule chain templates",
"subtitle-devices": "Browse device configurations",
"search-dashboards": "Search dashboards...",
"search-solution-templates": "Search solution templates...",
"search-calculated-fields": "Search calculated fields...",
"search-alarm-rules": "Search alarm rules...",
"search-rule-chains": "Search rule chains...",
"search-devices": "Search devices...",
"sort-most-relevant": "Most relevant",
"sort-most-installed": "Most installed",
"sort-newest": "Newest",
"sort-name": "Name (A-Z)",
"type-filter-label": "Type",
"verified-creators-only": "Verified creators only",
"category": "Category",
"use-case": "Use case",
"vendor": "Vendor",
@ -6451,6 +6450,7 @@
"update-confirm": "Update '{{name}}' to version {{version}}?",
"update-confirm-title": "Update '{{name}}'?",
"update-desc": "Updating this will replace the current version with the latest and reconfigure the associated resources within your tenant",
"update-desc-solution-template": "Updating this solution template will delete and recreate all entities it created, including dashboards, rule chains, devices, and other associated resources within your tenant. Any changes you made to them will be lost",
"update-success-desc": "'{{name}}' has been updated successfully",
"updating": "Updating...",
"update-success-title": "Update Successful",

8
ui-ngx/structure.md

@ -860,7 +860,7 @@ Key selectors: `input[formControlName="name"]`, `mat-slide-toggle[formControlNam
```html
<form style="width: 750px;">
<mat-toolbar color="primary">
<mat-toolbar color="tb-primary" class="tb-bottom-border flex flex-row">
<h2 translate><!-- dialog title --></h2>
<span class="flex-1"></span>
<button mat-icon-button><!-- close --></button>
@ -870,13 +870,13 @@ Key selectors: `input[formControlName="name"]`, `mat-slide-toggle[formControlNam
<!-- form content -->
</div>
<div mat-dialog-actions>
<button mat-button><!-- Cancel --></button>
<button mat-raised-button type="submit"><!-- Add/Save --></button>
<button mat-button color="primary"><!-- Cancel --></button>
<button mat-button mat-raised-button color="primary" type="submit"><!-- Add/Save --></button>
</div>
</form>
```
Key selectors: `[mat-dialog-content]`, `[mat-dialog-actions]`, `button[type="submit"]`, `mat-toolbar[color="primary"] h2`.
Key selectors: `[mat-dialog-content]`, `[mat-dialog-actions]`, `button[type="submit"]`, `mat-toolbar[color="tb-primary"] h2`.
### Common Material Selector Patterns

Loading…
Cancel
Save