Browse Source

Merge f0008af46c into e9a22127ca

pull/16895/merge
Igor Kulikov 1 hour ago
committed by GitHub
parent
commit
76fe70a91c
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 10
      ui-ngx/src/app/core/services/ai-chats.service.ts
  2. 9
      ui-ngx/src/app/core/services/ai-slash.service.ts
  3. 87
      ui-ngx/src/app/core/services/menu.models.ts
  4. 4
      ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.scss
  5. 21
      ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts
  6. 4
      ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts
  7. 3
      ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.ts
  8. 4
      ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.html
  9. 2
      ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts
  10. 2
      ui-ngx/src/app/modules/home/components/ai/solution/solution-info/issues-aggregation.ts
  11. 10
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.ts
  12. 1
      ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant-routing.module.ts
  13. 14
      ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts
  14. 4
      ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-item-row.component.ts
  15. 4
      ui-ngx/src/app/modules/home/pages/custom-menu/default-menu-item-panel.component.ts
  16. 20
      ui-ngx/src/app/modules/home/pages/home-page/components/_home-load.scss
  17. 267
      ui-ngx/src/app/modules/home/pages/home-page/components/alarms-home.component.html
  18. 26
      ui-ngx/src/app/modules/home/pages/home-page/components/alarms-home.component.ts
  19. 3
      ui-ngx/src/app/modules/home/pages/home-page/components/api-usage-home.component.html
  20. 57
      ui-ngx/src/app/modules/home/pages/home-page/components/api-usage-home.component.ts
  21. 3
      ui-ngx/src/app/modules/home/pages/home-page/components/dashboards-home.component.html
  22. 40
      ui-ngx/src/app/modules/home/pages/home-page/components/dashboards-home.component.ts
  23. 40
      ui-ngx/src/app/modules/home/pages/home-page/components/devices-activity-home.component.html
  24. 4
      ui-ngx/src/app/modules/home/pages/home-page/components/devices-activity-home.component.ts
  25. 165
      ui-ngx/src/app/modules/home/pages/home-page/components/devices-home.component.html
  26. 55
      ui-ngx/src/app/modules/home/pages/home-page/components/devices-home.component.ts
  27. 11
      ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.html
  28. 13
      ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.scss
  29. 26
      ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.ts
  30. 7
      ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.html
  31. 99
      ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.ts
  32. 110
      ui-ngx/src/app/modules/home/pages/home-page/components/home-card.component.scss
  33. 165
      ui-ngx/src/app/modules/home/pages/home-page/components/home-card.component.ts
  34. 170
      ui-ngx/src/app/modules/home/pages/home-page/components/home-skeleton.component.scss
  35. 208
      ui-ngx/src/app/modules/home/pages/home-page/components/home-skeleton.component.ts
  36. 66
      ui-ngx/src/app/modules/home/pages/home-page/components/install-items-home.component.html
  37. 25
      ui-ngx/src/app/modules/home/pages/home-page/components/install-items-home.component.ts
  38. 9
      ui-ngx/src/app/modules/home/pages/home-page/components/iot-hub-home.component.html
  39. 6
      ui-ngx/src/app/modules/home/pages/home-page/components/iot-hub-home.component.scss
  40. 27
      ui-ngx/src/app/modules/home/pages/home-page/components/iot-hub-home.component.ts
  41. 3
      ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.html
  42. 37
      ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.ts
  43. 17
      ui-ngx/src/app/modules/home/pages/home-page/components/mobile-app-home.component.html
  44. 30
      ui-ngx/src/app/modules/home/pages/home-page/components/mobile-app-home.component.scss
  45. 29
      ui-ngx/src/app/modules/home/pages/home-page/components/mobile-app-home.component.ts
  46. 5
      ui-ngx/src/app/modules/home/pages/home-page/components/notifications-home.component.html
  47. 49
      ui-ngx/src/app/modules/home/pages/home-page/components/notifications-home.component.ts
  48. 5
      ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.html
  49. 10
      ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.ts
  50. 2
      ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.html
  51. 33
      ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.ts
  52. 42
      ui-ngx/src/app/modules/home/pages/home-page/home-count.service.ts
  53. 155
      ui-ngx/src/app/modules/home/pages/home-page/home-load.service.ts
  54. 2
      ui-ngx/src/app/modules/home/pages/home-page/home-page.module.ts
  55. 20
      ui-ngx/src/app/modules/home/pages/home-page/sys-admin-home.service.ts
  56. 3
      ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts
  57. 1
      ui-ngx/src/app/shared/models/ai-chat.models.ts
  58. 2
      ui-ngx/src/assets/locale/locale.constant-ar_AE.json
  59. 2
      ui-ngx/src/assets/locale/locale.constant-ca_ES.json
  60. 2
      ui-ngx/src/assets/locale/locale.constant-cs_CZ.json
  61. 2
      ui-ngx/src/assets/locale/locale.constant-da_DK.json
  62. 2
      ui-ngx/src/assets/locale/locale.constant-de_DE.json
  63. 2
      ui-ngx/src/assets/locale/locale.constant-el_GR.json
  64. 11
      ui-ngx/src/assets/locale/locale.constant-en_US.json
  65. 2
      ui-ngx/src/assets/locale/locale.constant-es_ES.json
  66. 2
      ui-ngx/src/assets/locale/locale.constant-fr_FR.json
  67. 2
      ui-ngx/src/assets/locale/locale.constant-hi_IN.json
  68. 2
      ui-ngx/src/assets/locale/locale.constant-it_IT.json
  69. 2
      ui-ngx/src/assets/locale/locale.constant-ja_JP.json
  70. 2
      ui-ngx/src/assets/locale/locale.constant-ka_GE.json
  71. 2
      ui-ngx/src/assets/locale/locale.constant-ko_KR.json
  72. 2
      ui-ngx/src/assets/locale/locale.constant-lt_LT.json
  73. 2
      ui-ngx/src/assets/locale/locale.constant-lv_LV.json
  74. 2
      ui-ngx/src/assets/locale/locale.constant-nl_BE.json
  75. 2
      ui-ngx/src/assets/locale/locale.constant-nl_NL.json
  76. 2
      ui-ngx/src/assets/locale/locale.constant-no_NO.json
  77. 2
      ui-ngx/src/assets/locale/locale.constant-pl_PL.json
  78. 2
      ui-ngx/src/assets/locale/locale.constant-pt_BR.json
  79. 2
      ui-ngx/src/assets/locale/locale.constant-ro_RO.json
  80. 2
      ui-ngx/src/assets/locale/locale.constant-sl_SI.json
  81. 2
      ui-ngx/src/assets/locale/locale.constant-tr_TR.json
  82. 2
      ui-ngx/src/assets/locale/locale.constant-uk_UA.json
  83. 2
      ui-ngx/src/assets/locale/locale.constant-zh_CN.json
  84. 2
      ui-ngx/src/assets/locale/locale.constant-zh_TW.json

10
ui-ngx/src/app/core/services/ai-chats.service.ts

@ -299,6 +299,16 @@ export class AiChatsService {
);
}
addPrompt(chatId: string | undefined, text: string | undefined): void {
const prompt = text?.trim();
if (!chatId || !prompt) {
return;
}
this._chats.update(list => list.map(chat => chat.id === chatId
? {...chat, prompt: chat.prompt ?? prompt, prompts: [...(chat.prompts ?? (chat.prompt ? [chat.prompt] : [])), prompt]}
: chat));
}
setTitle(chatId: string, title: string): void {
this._chats.update(list => list.map(chat => chat.id === chatId ? {...chat, title} : chat));
}

9
ui-ngx/src/app/core/services/ai-slash.service.ts

@ -22,6 +22,7 @@ export class AiSlashService {
private dialog = inject(MatDialog);
private composers = new Set<AiSlashComposer>();
private opener: AiSlashOpener | null = null;
private blocks = new Set<object>();
private listening = false;
addComposer(composer: AiSlashComposer): () => void {
@ -40,6 +41,12 @@ export class AiSlashService {
};
}
block(): () => void {
const token = {};
this.blocks.add(token);
return () => this.blocks.delete(token);
}
private listen(): void {
if (this.listening) {
return;
@ -66,7 +73,7 @@ export class AiSlashService {
this.zone.run(() => last.focusEnd());
return;
}
if (this.opener?.canOpen()) {
if (!this.blocks.size && this.opener?.canOpen()) {
event.preventDefault();
this.zone.run(() => this.opener.open());
}

87
ui-ngx/src/app/core/services/menu.models.ts

@ -283,8 +283,8 @@ export const menuSectionMap = new Map<MenuId, MenuSection>([
name: 'image.images',
type: 'link',
path: '/resources/images',
icon: 'filter',
outlinedIcon: 'filter'
icon: 'image',
outlinedIcon: 'image'
}
],
[
@ -724,8 +724,8 @@ export const menuSectionMap = new Map<MenuId, MenuSection>([
name: 'device.devices',
type: 'link',
path: '/entities/devices',
icon: 'devices_other',
outlinedIcon: 'devices_other'
icon: 'memory',
outlinedIcon: 'memory'
}
],
[
@ -735,8 +735,8 @@ export const menuSectionMap = new Map<MenuId, MenuSection>([
name: 'asset.assets',
type: 'link',
path: '/entities/assets',
icon: 'domain',
outlinedIcon: 'domain'
icon: 'mdi:cube-outline',
outlinedIcon: 'mdi:cube-outline'
}
],
[
@ -904,8 +904,8 @@ export const menuSectionMap = new Map<MenuId, MenuSection>([
fullName: 'agent.agents',
type: 'link',
path: '/edgeManagement/agents',
icon: 'memory',
outlinedIcon: 'memory',
icon: 'settings_applications',
outlinedIcon: 'settings_applications',
isNew: true
}
],
@ -917,8 +917,8 @@ export const menuSectionMap = new Map<MenuId, MenuSection>([
fullName: 'agent.all-agents',
type: 'link',
path: '/edgeManagement/agents/all',
icon: 'memory',
outlinedIcon: 'memory'
icon: 'settings_applications',
outlinedIcon: 'settings_applications'
}
],
[
@ -929,8 +929,8 @@ export const menuSectionMap = new Map<MenuId, MenuSection>([
fullName: 'entity-group.agent-groups',
type: 'link',
path: '/edgeManagement/agents/groups',
icon: 'memory',
outlinedIcon: 'memory'
icon: 'settings_applications',
outlinedIcon: 'settings_applications'
}
],
[
@ -941,8 +941,8 @@ export const menuSectionMap = new Map<MenuId, MenuSection>([
fullName: 'entity-group.shared-agent-groups',
type: 'link',
path: '/edgeManagement/agents/shared',
icon: 'memory',
outlinedIcon: 'memory',
icon: 'settings_applications',
outlinedIcon: 'settings_applications',
rootOnly: true
}
],
@ -986,8 +986,8 @@ export const menuSectionMap = new Map<MenuId, MenuSection>([
name: 'ota-update.ota-updates',
type: 'link',
path: '/features/otaUpdates',
icon: 'memory',
outlinedIcon: 'memory'
icon: 'system_update_alt',
outlinedIcon: 'system_update_alt'
}
],
[
@ -1125,8 +1125,8 @@ export const menuSectionMap = new Map<MenuId, MenuSection>([
fullName: 'device.all-devices',
type: 'link',
path: '/entities/devices/all',
icon: 'devices_other',
outlinedIcon: 'devices_other'
icon: 'memory',
outlinedIcon: 'memory'
}
],
[
@ -1137,8 +1137,8 @@ export const menuSectionMap = new Map<MenuId, MenuSection>([
fullName: 'entity-group.device-groups',
type: 'link',
path: '/entities/devices/groups',
icon: 'devices_other',
outlinedIcon: 'devices_other'
icon: 'memory',
outlinedIcon: 'memory'
}
],
[
@ -1149,8 +1149,8 @@ export const menuSectionMap = new Map<MenuId, MenuSection>([
fullName: 'entity-group.shared-device-groups',
type: 'link',
path: '/entities/devices/shared',
icon: 'devices_other',
outlinedIcon: 'devices_other',
icon: 'memory',
outlinedIcon: 'memory',
rootOnly: true
}
],
@ -1162,8 +1162,8 @@ export const menuSectionMap = new Map<MenuId, MenuSection>([
fullName: 'asset.all-assets',
type: 'link',
path: '/entities/assets/all',
icon: 'domain',
outlinedIcon: 'domain'
icon: 'mdi:cube-outline',
outlinedIcon: 'mdi:cube-outline'
}
],
[
@ -1174,8 +1174,8 @@ export const menuSectionMap = new Map<MenuId, MenuSection>([
fullName: 'entity-group.asset-groups',
type: 'link',
path: '/entities/assets/groups',
icon: 'domain',
outlinedIcon: 'domain'
icon: 'mdi:cube-outline',
outlinedIcon: 'mdi:cube-outline'
}
],
[
@ -1186,8 +1186,8 @@ export const menuSectionMap = new Map<MenuId, MenuSection>([
fullName: 'entity-group.shared-asset-groups',
type: 'link',
path: '/entities/assets/shared',
icon: 'domain',
outlinedIcon: 'domain',
icon: 'mdi:cube-outline',
outlinedIcon: 'mdi:cube-outline',
rootOnly: true
}
],
@ -1436,8 +1436,8 @@ export const menuSectionMap = new Map<MenuId, MenuSection>([
name: 'secret-storage.secrets-storage',
type: 'link',
path: '/security-settings/secrets',
icon: 'mdi:key-variant',
outlinedIcon: 'mdi:key-variant'
icon: 'lock',
outlinedIcon: 'lock'
}
],
[
@ -1469,8 +1469,8 @@ export const menuSectionMap = new Map<MenuId, MenuSection>([
name: 'report.reports',
type: 'link',
path: '/reporting',
icon: 'mdi:chart-box-multiple',
outlinedIcon: 'mdi:chart-box-multiple-outline'
icon: 'summarize',
outlinedIcon: 'summarize'
}
],
[
@ -1502,8 +1502,8 @@ export const menuSectionMap = new Map<MenuId, MenuSection>([
name: 'report.reports',
type: 'link',
path: '/reporting/reports',
icon: 'mdi:chart-box-multiple',
outlinedIcon: 'mdi:chart-box-multiple-outline'
icon: 'summarize',
outlinedIcon: 'summarize'
}
],
[
@ -2392,8 +2392,7 @@ export const menuItemToMenuSection = (authState: AuthState,
if (isDefinedAndNotNull(item.visible) && !item.visible) {
return undefined;
}
const section = menuSectionMap.get(item.id);
const result = deepClone(section);
const result = roleSection(authState, menuSectionMap.get(item.id));
if (isNotEmptyStr(item.icon)) {
result.icon = item.icon;
result.outlinedIcon = item.icon;
@ -2426,12 +2425,26 @@ export const menuItemToMenuSection = (authState: AuthState,
}
};
export const defaultMenuSection = (id: MenuId | string, sysAdmin: boolean): MenuSection | undefined =>
roleIcons(deepClone(menuSectionMap.get(id as MenuId)), sysAdmin);
const roleSection = (authState: AuthState, section: MenuSection): MenuSection =>
roleIcons(deepClone(section), authState.authUser.authority === Authority.SYS_ADMIN);
const roleIcons = (section: MenuSection | undefined, sysAdmin: boolean): MenuSection | undefined => {
if (section?.id === MenuId.notifications_center && !sysAdmin) {
section.icon = 'notifications';
section.outlinedIcon = 'notifications';
}
return section;
};
const referenceToMenuSection = (authState: AuthState, userPermissionsService: UserPermissionsService,
reference: MenuReference): MenuSection | undefined => {
if (filterMenuReference(authState, userPermissionsService, [], reference)) {
const section = menuSectionMap.get(MenuId[reference.id]);
if (section) {
const result = deepClone(section);
const result = roleSection(authState, section);
if (reference.pages?.length) {
result.pages = reference.pages.map(page =>
referenceToMenuSection(authState, userPermissionsService, page)).filter(page => !!page);

4
ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.scss

@ -20,6 +20,10 @@
transition: none;
}
&.resizing {
contain: layout style;
}
&.restored {
transition: none;
}

21
ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts

@ -119,11 +119,13 @@ export class AiAssistantPanelComponent {
});
private startComposed(text: string, opened: boolean): void {
if (!opened && this.chat) {
this.chat.composeText(text);
return;
}
this.chat?.keepDraftForCompose();
this.chatId.set(undefined);
if (opened) {
this.chats.load().subscribe();
}
this.chats.load().subscribe();
setTimeout(() => this.chat?.composeText(text), AiAssistantPanelComponent.COMPOSE_DELAY_MS);
}
@ -235,7 +237,8 @@ export class AiAssistantPanelComponent {
this.resizing.set(true);
const grip = event.target as HTMLElement;
const host = this.elementRef.nativeElement as HTMLElement;
const root = document.documentElement;
const page = host.parentElement?.querySelector<HTMLElement>('.tb-site-main.openAiAssistant') ?? null;
const pageFollows = !!page && parseFloat(getComputedStyle(page).marginRight) > 0;
const startX = event.clientX;
const startWidth = this.width();
this.room.set(host.parentElement?.clientWidth ?? window.innerWidth);
@ -248,7 +251,9 @@ export class AiAssistantPanelComponent {
const reflowPage = () => {
pageTimer = undefined;
pageAt = performance.now();
root.style.setProperty('--tb-ai-panel-w', current + 'px');
if (pageFollows) {
page.style.marginRight = current + 'px';
}
};
const paint = () => {
frame = 0;
@ -259,6 +264,7 @@ export class AiAssistantPanelComponent {
};
grip.setPointerCapture(event.pointerId);
document.body.classList.add('tb-ai-resizing');
host.classList.add('resizing');
this.zone.runOutsideAngular(() => {
const move = (e: PointerEvent) => {
const wanted = startWidth + (startX - e.clientX);
@ -279,8 +285,11 @@ export class AiAssistantPanelComponent {
cancelAnimationFrame(frame);
clearTimeout(pageTimer);
document.body.classList.remove('tb-ai-resizing');
host.classList.remove('closing');
host.classList.remove('closing', 'resizing');
host.style.width = '';
if (page) {
page.style.marginRight = '';
}
this.zone.run(() => {
this.resizing.set(false);
if (closing) {

4
ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts

@ -1034,6 +1034,7 @@ export class AiChatComponent implements OnInit, OnDestroy {
private sendWhileWorking(prompt: AiPromptMessage, userMessage: ChatMessage): void {
const chatId = this.chatId();
let ownTurn = false;
this.chats.addPrompt(chatId, prompt.message);
this.aiChat.sendChatMessage(chatId, this.chatRequest(prompt), {ignoreLoading: true, ignoreErrors: true}).pipe(
takeUntil(this.cancelMessage$),
concatMap(event => {
@ -1135,6 +1136,9 @@ export class AiChatComponent implements OnInit, OnDestroy {
return startOrContinue$.pipe(
tap(() => {
this.chats.clearFailure(this.chatId());
if (!again) {
this.chats.addPrompt(this.chatId(), prompt.message);
}
this.startLoading();
}),
switchMap(() => this.aiChat.sendChatMessage(this.chatId(), request, {ignoreLoading: true, ignoreErrors: true})),

3
ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.ts

@ -124,8 +124,7 @@ export class AiLimitOutComponent {
icon: whiteLabeling ? 'palette' : 'lock',
title: grant
? this.translate.instant(`platform-feature.${featureKey}.not-in-ce-grant`)
: (whiteLabeling ? this.translate.instant('platform-feature.white-labeling.not-in-plan')
: this.say('feature-title', {feature: this.say(`feature.${featureKey}`)})),
: this.say('feature-unavailable-title', {feature: this.say(`feature.${featureKey}`)}),
action: sysAdmin ? 'license' : (oldLicense && !grant ? 'pricing' : 'request'),
requestLabel: 'subscription.request-access',
storageKey: addon === AddonType.WHITE_LABELING ? WL_REQUESTED_STORAGE_KEY : PE_PACK_REQUESTED_STORAGE_KEY,

4
ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.html

@ -45,11 +45,11 @@
<td class="wrap sol-installed-name">
@if (link(row.type, row); as url) {
<a class="sol-name sol-ent" [attr.data-pal]="row.palette" [routerLink]="url">
<tb-icon aria-hidden="true">{{ row.icon }}</tb-icon><b>{{ row.primary.additionalData?.name }}</b>
<tb-icon aria-hidden="true">{{ row.icon }}</tb-icon><b>{{ row.primary.additionalData?.name ?? row.primary.additionalData?.email }}</b>
</a>
} @else {
<span class="sol-name" [attr.data-pal]="row.palette">
<tb-icon aria-hidden="true">{{ row.icon }}</tb-icon><b>{{ row.primary.additionalData?.name }}</b>
<tb-icon aria-hidden="true">{{ row.icon }}</tb-icon><b>{{ row.primary.additionalData?.name ?? row.primary.additionalData?.email }}</b>
</span>
}
</td>

2
ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts

@ -524,7 +524,7 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe
}
return Object.values(results).flat()
.filter(entry => entry?.status === 'ERROR' || entry?.status === 'WARN')
.map(entry => ({name: entry.additionalData?.name ?? '', status: entry.status, message: entry.error?.message}));
.map(entry => ({name: entry.additionalData?.name ?? entry.additionalData?.email ?? '', status: entry.status, message: entry.error?.message}));
});
private paneEdgeEffect = effect(() => {

2
ui-ngx/src/app/modules/home/components/ai/solution/solution-info/issues-aggregation.ts

@ -28,7 +28,7 @@ export function aggregateByName(entityType: EntityType, entries: EntityResult[]
const groups = new Map<string, EntityResult[]>();
for (const e of entries) {
const name = e.additionalData?.name ?? '';
const name = e.additionalData?.name ?? e.additionalData?.email ?? '';
let list = groups.get(name);
if (!list) {
list = [];

10
ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.ts

@ -2,6 +2,7 @@
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { DashboardSelectComponent } from '@shared/components/dashboard-select.component';
import { AiSlashService } from '@core/services/ai-slash.service';
import {
AfterViewInit,
ChangeDetectionStrategy,
@ -12,6 +13,7 @@ import {
EventEmitter,
HostBinding,
Inject,
inject,
Injector,
Input,
NgZone,
@ -241,6 +243,9 @@ export class DashboardPageComponent extends PageComponent implements IDashboardC
isFullscreen = false;
isEdit = false;
private aiSlash = inject(AiSlashService);
private releaseSlash: (() => void) | null = null;
private editedWhileEmpty = false;
isEditingWidget = false;
isEditingWidgetClosed = true;
@ -715,6 +720,8 @@ export class DashboardPageComponent extends PageComponent implements IDashboardC
this.panelService.clearKeptEdits('dashboard');
}
this.isEdit = false;
this.releaseSlash?.();
this.releaseSlash = null;
this.isEditingWidget = false;
this.isEditingWidgetClosed = true;
this.forceDashboardMobileMode = false;
@ -741,6 +748,7 @@ export class DashboardPageComponent extends PageComponent implements IDashboardC
ngOnDestroy(): void {
this.destroyed = true;
this.releaseSlash?.();
if (this.aiAssistantPanelEnabled) {
this.panelService.teardown();
}
@ -1344,6 +1352,8 @@ export class DashboardPageComponent extends PageComponent implements IDashboardC
this.panelService.clearKeptEdits('dashboard');
}
this.isEdit = isEdit;
this.releaseSlash?.();
this.releaseSlash = isEdit ? this.aiSlash.block() : null;
this.editedWhileEmpty = false;
if (this.isEdit) {
this.dashboardCtx.stateController.preserveState();

1
ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant-routing.module.ts

@ -12,6 +12,7 @@ const routes: Routes = [
path: 'ai-assistant',
loadChildren: () => import('./ai-assistant-page.module').then(m => m.AiAssistantPageModule),
data: {
title: 'ai-assistant.ai-assistant',
breadcrumb: {
menuId: MenuId.ai_assistant
},

14
ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts

@ -44,6 +44,7 @@ export interface AiRailRow {
pinned: boolean;
pinnedTime?: number;
prompt?: string;
prompts?: string[];
chat?: ChatInfo;
solution?: SolutionInfo;
}
@ -104,7 +105,7 @@ export class AiAssistantComponent implements OnInit, OnDestroy {
rows = computed<AiRailRow[]>(() => [
...this.aiChats.chats().map(chat => ({
id: chat.id, title: chat.title, createdTime: chat.createdTime, pinned: !!chat.pinned, pinnedTime: chat.pinnedTime, prompt: chat.prompt, chat
id: chat.id, title: chat.title, createdTime: chat.createdTime, pinned: !!chat.pinned, pinnedTime: chat.pinnedTime, prompt: chat.prompt, prompts: chat.prompts, chat
})),
...this.aiSolutions.solutions().map(solution => ({
id: solution.id, title: this.aiSolutions.titleOf(solution), createdTime: solution.createdTime ?? 0, pinned: !!solution.pinned, solution
@ -115,7 +116,7 @@ export class AiAssistantComponent implements OnInit, OnDestroy {
const query = this.query().trim().toLowerCase();
const chats = this.rows();
if (query) {
const found = chats.filter(chat => (chat.title ?? '').toLowerCase().includes(query) || (chat.prompt ?? '').toLowerCase().includes(query));
const found = chats.filter(chat => (chat.title ?? '').toLowerCase().includes(query) || !!this.promptWith(chat, query));
return found.length
? [{label: this.translate.instant('ai-assistant.chats-found', {count: found.length}), chats: found}]
: [];
@ -365,8 +366,8 @@ export class AiAssistantComponent implements OnInit, OnDestroy {
snippetOf(row: AiRailRow): {text: string; hit: boolean}[] | null {
const query = this.query().trim().toLowerCase();
const prompt = row.prompt ?? '';
const at = query ? prompt.toLowerCase().indexOf(query) : -1;
const prompt = query ? this.promptWith(row, query) ?? '' : '';
const at = prompt.toLowerCase().indexOf(query);
if (!query || (row.title ?? '').toLowerCase().includes(query) || at < 0) {
return null;
}
@ -382,6 +383,11 @@ export class AiAssistantComponent implements OnInit, OnDestroy {
].filter(part => part.text);
}
private promptWith(row: AiRailRow, query: string): string | undefined {
const prompts = row.prompts?.length ? row.prompts : row.prompt ? [row.prompt] : [];
return prompts.find(prompt => prompt.toLowerCase().includes(query));
}
runAgain(chat: ChatInfo): void {
const start = (prompt: string | undefined) => {
if (!prompt?.trim()) {

4
ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-item-row.component.ts

@ -44,7 +44,7 @@ import {
} from '@shared/models/custom-menu.models';
import { TbPopoverService } from '@shared/components/popover.service';
import { TranslateService } from '@ngx-translate/core';
import { MenuSection, menuSectionMap } from '@core/services/menu.models';
import { defaultMenuSection, MenuSection } from '@core/services/menu.models';
import { CustomTranslatePipe } from '@shared/pipe/custom-translate.pipe';
import { coerceBoolean } from '@shared/decorators/coercion';
import { CdkDragDrop } from '@angular/cdk/drag-drop';
@ -229,7 +229,7 @@ export class CustomMenuItemRowComponent implements ControlValueAccessor, OnInit,
this.menuItemRowFormGroup.setControl('pages', this.preparePagesFormArray(value.pages), {emitEvent: false});
}
if (isDefaultMenuItem(this.modelValue)) {
this.defaultMenuSection = menuSectionMap.get(this.modelValue.id);
this.defaultMenuSection = defaultMenuSection(this.modelValue.id, this.scope === CMScope.SYSTEM);
this.isDefaultMenuItem = true;
this.defaultItemName = this.translate.instant(this.defaultMenuSection.name);
if (!value.icon) {

4
ui-ngx/src/app/modules/home/pages/custom-menu/default-menu-item-panel.component.ts

@ -12,7 +12,7 @@ import {
} from '@shared/models/custom-menu.models';
import { TbPopoverComponent } from '@shared/components/popover.component';
import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms';
import { MenuSection, menuSectionMap } from '@core/services/menu.models';
import { defaultMenuSection, MenuSection } from '@core/services/menu.models';
import { TranslateService } from '@ngx-translate/core';
import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state';
@ -73,7 +73,7 @@ export class DefaultMenuItemPanelComponent implements OnInit {
if (isHomeMenuItem(this.menuItem)) {
this.isHomeMenuItem = true;
}
this.defaultMenuSection = menuSectionMap.get(this.menuItem.id);
this.defaultMenuSection = defaultMenuSection(this.menuItem.id, this.scope === CMScope.SYSTEM);
this.defaultItemName = this.translate.instant(this.defaultMenuSection.name);
this.menuItemFormGroup = this.fb.group({

20
ui-ngx/src/app/modules/home/pages/home-page/components/_home-load.scss

@ -0,0 +1,20 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
.tb-home-load-retry {
padding: 0;
border: none;
background: none;
font: inherit;
color: var(--tb-primary-500, #305680);
cursor: pointer;
&:hover {
text-decoration: underline;
}
&:focus-visible {
outline: 2px solid var(--tb-primary-500, #305680);
outline-offset: 2px;
border-radius: 2px;
}
}

267
ui-ngx/src/app/modules/home/pages/home-page/components/alarms-home.component.html

@ -4,9 +4,10 @@
SPDX-License-Identifier: BUSL-1.1
-->
<tb-home-card [card]="card" [count]="total()">
<tb-home-card [card]="card" [count]="ready() ? total() : null" skeleton="alarms" [hasData]="ready()" [reading]="!ready()"
[refreshing]="refreshing()" [keepHeight]="!expanded() && !severity()" (retry)="refresh()">
<ng-container homeCardActions>
@if (total()) {
@if (ready() && total()) {
<tb-home-toggle [options]="whoseOptions" [value]="mine()" [label]="'home.alarms.whose' | translate" (valueChange)="setMine($event)"></tb-home-toggle>
}
@if (canAddRule) {
@ -16,149 +17,151 @@
</button>
}
</ng-container>
@if (emptyState() === 'rules') {
<div class="tb-home-setup-empty">
<span class="tb-home-setup-empty-glyph" aria-hidden="true"><mat-icon>rule</mat-icon></span>
<div class="tb-home-setup-empty-text">
<p>{{ 'home.alarms.no-rules' | translate }}</p>
<div class="tb-home-setup-empty-actions">
<a [href]="howToLink" target="_blank" rel="noopener">{{ 'home.alarms.how-rules-work' | translate }}<mat-icon class="tb-home-ext" aria-hidden="true">north_east</mat-icon><span class="tb-ai-sr-only">{{ 'home.dashboards.opens-new-tab' | translate }}</span></a>
@if (ready()) {
@if (emptyState() === 'rules') {
<div class="tb-home-setup-empty">
<span class="tb-home-setup-empty-glyph" aria-hidden="true"><mat-icon>rule</mat-icon></span>
<div class="tb-home-setup-empty-text">
<p>{{ 'home.alarms.no-rules' | translate }}</p>
<div class="tb-home-setup-empty-actions">
<a [href]="howToLink" target="_blank" rel="noopener">{{ 'home.alarms.how-rules-work' | translate }}<mat-icon class="tb-home-ext" aria-hidden="true">north_east</mat-icon><span class="tb-ai-sr-only">{{ 'home.dashboards.opens-new-tab' | translate }}</span></a>
</div>
</div>
</div>
</div>
} @else if (emptyState() === 'devices') {
<div class="tb-home-setup-empty">
<span class="tb-home-setup-empty-glyph" aria-hidden="true"><mat-icon>notifications_none</mat-icon></span>
<div class="tb-home-setup-empty-title">{{ 'home.alarms.no-alarms-yet' | translate }}</div>
</div>
} @else if (emptyState() === 'clear') {
<div class="tb-home-all-clear">
<span class="tb-home-all-clear-glyph" aria-hidden="true"><mat-icon>check</mat-icon></span>
<span>{{ 'home.alarms.none-active' | translate }} <a class="tb-alarms-clear-link" routerLink="/alarms/alarms" [queryParams]="{statusList: ['CLEARED']}">{{ 'home.alarms.view-cleared' | translate }}</a></span>
</div>
} @else if (total()) {
<div class="tb-home-tiles">
@for (tile of tiles(); track tile.severity) {
<button type="button" class="tb-home-tile" [class]="tile.severity.toLowerCase()" [class.zero]="!tile.count"
[class.can-reset]="tile.pressed" [disabled]="!tile.count && !tile.pressed"
[attr.aria-pressed]="tile.count || tile.pressed ? tile.pressed : null"
[matTooltip]="(tile.pressed ? 'home.alarms.show-every' : 'home.alarms.show-only') | translate: {severity: (severityLabel(tile.severity) | translate)}"
[matTooltipDisabled]="!tile.count && !tile.pressed" matTooltipPosition="above"
(click)="pick(tile)">
<span class="tb-home-tile-label">{{ severityLabel(tile.severity) | translate }}</span>
<span class="tb-home-tile-count">
{{ tile.count | shortNumber }}
@if (tile.hot) {
<tb-ai-sev-mark class="tb-alarms-tile-mark" severity="CRITICAL"></tb-ai-sev-mark>
}
</span>
</button>
}
</div>
@if (rows().length) {
<table class="tb-home-table tb-alarms-table" [class.mine]="mine()">
<thead>
<tr>
<th class="col-severity sortable" [class.sorted]="sortKey() === 'severity'" [attr.aria-sort]="ariaSort('severity')">
<button type="button" class="th-label" [matTooltip]="'home.alarms.sort-severity' | translate" (click)="sortBy('severity')">
<span class="th-text">{{ 'home.alarms.severity' | translate }}</span>
<mat-icon class="tb-sort-icon">{{ sortKey() === 'severity' && !sortDesc() ? 'arrow_upward' : 'arrow_downward' }}</mat-icon>
</button>
</th>
<th class="col-type">{{ 'home.alarms.type' | translate }}</th>
<th class="col-origin">{{ 'home.alarms.originator' | translate }}</th>
<th class="col-age col-time sortable" [class.sorted]="sortKey() === 'createdTime'" [attr.aria-sort]="ariaSort('createdTime')">
<button type="button" class="th-label" [matTooltip]="'home.alarms.sort-started' | translate" (click)="sortBy('createdTime')">
<span class="th-text">{{ 'home.alarms.started' | translate }}</span>
<mat-icon class="tb-sort-icon">{{ sortKey() === 'createdTime' && !sortDesc() ? 'arrow_upward' : 'arrow_downward' }}</mat-icon>
</button>
</th>
@if (!mine()) {
<th class="col-assignee"><span class="th-text">{{ 'home.alarms.assignee' | translate }}</span></th>
}
<th class="col-ack" [matTooltip]="'home.alarms.acknowledged-tip' | translate">{{ 'home.alarms.ack' | translate }}</th>
<th class="col-actions"></th>
</tr>
</thead>
<tbody>
@for (row of rows(); track row.alarm.id.id) {
<tr (click)="openDetails(row)">
<td class="col-severity">
<span class="tb-alarms-sev">
<tb-ai-sev-mark [severity]="row.alarm.severity"></tb-ai-sev-mark>
<span class="tb-alarms-sev-word">{{ severityLabel(row.alarm.severity) | translate }}</span>
</span>
</td>
<td class="col-type">
<span class="tb-alarms-cell-main">
<a class="tb-alarms-link" href="#" (click)="openDetails(row, $event)">{{ row.alarm.type }}</a>
</span>
<span class="tb-alarms-cell-sub">
} @else if (emptyState() === 'devices') {
<div class="tb-home-setup-empty">
<span class="tb-home-setup-empty-glyph" aria-hidden="true"><mat-icon>notifications_none</mat-icon></span>
<div class="tb-home-setup-empty-title">{{ 'home.alarms.no-alarms-yet' | translate }}</div>
</div>
} @else if (emptyState() === 'clear') {
<div class="tb-home-all-clear">
<span class="tb-home-all-clear-glyph" aria-hidden="true"><mat-icon>check</mat-icon></span>
<span>{{ 'home.alarms.none-active' | translate }} <a class="tb-alarms-clear-link" routerLink="/alarms/alarms" [queryParams]="{statusList: ['CLEARED']}">{{ 'home.alarms.view-cleared' | translate }}</a></span>
</div>
} @else if (total()) {
<div class="tb-home-tiles">
@for (tile of tiles(); track tile.severity) {
<button type="button" class="tb-home-tile" [class]="tile.severity.toLowerCase()" [class.zero]="!tile.count"
[class.can-reset]="tile.pressed" [disabled]="!tile.count && !tile.pressed"
[attr.aria-pressed]="tile.count || tile.pressed ? tile.pressed : null"
[matTooltip]="(tile.pressed ? 'home.alarms.show-every' : 'home.alarms.show-only') | translate: {severity: (severityLabel(tile.severity) | translate)}"
[matTooltipDisabled]="!tile.count && !tile.pressed" matTooltipPosition="above"
(click)="pick(tile)">
<span class="tb-home-tile-label">{{ severityLabel(tile.severity) | translate }}</span>
<span class="tb-home-tile-count">
{{ tile.count | shortNumber }}
@if (tile.hot) {
<tb-ai-sev-mark class="tb-alarms-tile-mark" severity="CRITICAL"></tb-ai-sev-mark>
}
</span>
</button>
}
</div>
@if (rows().length) {
<table class="tb-home-table tb-alarms-table" [class.mine]="mine()">
<thead>
<tr>
<th class="col-severity sortable" [class.sorted]="sortKey() === 'severity'" [attr.aria-sort]="ariaSort('severity')">
<button type="button" class="th-label" [matTooltip]="'home.alarms.sort-severity' | translate" (click)="sortBy('severity')">
<span class="th-text">{{ 'home.alarms.severity' | translate }}</span>
<mat-icon class="tb-sort-icon">{{ sortIcon('severity') }}</mat-icon>
</button>
</th>
<th class="col-type">{{ 'home.alarms.type' | translate }}</th>
<th class="col-origin">{{ 'home.alarms.originator' | translate }}</th>
<th class="col-age col-time sortable" [class.sorted]="sortKey() === 'createdTime'" [attr.aria-sort]="ariaSort('createdTime')">
<button type="button" class="th-label" [matTooltip]="'home.alarms.sort-started' | translate" (click)="sortBy('createdTime')">
<span class="th-text">{{ 'home.alarms.started' | translate }}</span>
<mat-icon class="tb-sort-icon">{{ sortIcon('createdTime') }}</mat-icon>
</button>
</th>
@if (!mine()) {
<th class="col-assignee"><span class="th-text">{{ 'home.alarms.assignee' | translate }}</span></th>
}
<th class="col-ack" [matTooltip]="'home.alarms.acknowledged-tip' | translate">{{ 'home.alarms.ack' | translate }}</th>
<th class="col-actions"></th>
</tr>
</thead>
<tbody>
@for (row of rows(); track row.alarm.id.id) {
<tr (click)="openDetails(row)">
<td class="col-severity">
<span class="tb-alarms-sev">
<tb-ai-sev-mark [severity]="row.alarm.severity"></tb-ai-sev-mark>
<span class="tb-alarms-sev-word">{{ severityLabel(row.alarm.severity) | translate }}</span>
</span>
</td>
<td class="col-type">
<span class="tb-alarms-cell-main">
<a class="tb-alarms-link" href="#" (click)="openDetails(row, $event)">{{ row.alarm.type }}</a>
</span>
<span class="tb-alarms-cell-sub">
@if (row.originatorLink) {
<a class="tb-alarms-link tb-alarms-origin" [routerLink]="row.originatorLink" (click)="stop($event)">{{ row.alarm.originatorDisplayName || row.alarm.originatorName }}</a>
} @else {
<span class="tb-alarms-origin">{{ row.alarm.originatorDisplayName || row.alarm.originatorName }}</span>
}
<span class="tb-alarms-sub-age"> · {{ row.ago }}</span>
</span>
</td>
<td class="col-origin">
@if (row.originatorLink) {
<a class="tb-alarms-link tb-alarms-origin" [routerLink]="row.originatorLink" (click)="stop($event)">{{ row.alarm.originatorDisplayName || row.alarm.originatorName }}</a>
} @else {
<span class="tb-alarms-origin">{{ row.alarm.originatorDisplayName || row.alarm.originatorName }}</span>
}
<span class="tb-alarms-sub-age"> · {{ row.ago }}</span>
</span>
</td>
<td class="col-origin">
@if (row.originatorLink) {
<a class="tb-alarms-link tb-alarms-origin" [routerLink]="row.originatorLink" (click)="stop($event)">{{ row.alarm.originatorDisplayName || row.alarm.originatorName }}</a>
} @else {
<span class="tb-alarms-origin">{{ row.alarm.originatorDisplayName || row.alarm.originatorName }}</span>
</td>
<td class="col-age col-time" [matTooltip]="'home.alarms.started-at' | translate: {time: (row.alarm.createdTime | date: 'd MMM, HH:mm')}">{{ row.ago }}</td>
@if (!mine()) {
<td class="col-assignee">
@if (row.assigneeName) {
<span class="tb-alarms-assignee" [class.me]="row.mine" role="img"
[attr.aria-label]="row.mine ? ('home.alarms.assigned-you' | translate) : ('home.alarms.assigned-to' | translate: {name: row.assigneeName})"
[matTooltip]="row.mine ? ('home.alarms.assigned-you' | translate) : ('home.alarms.assigned-to' | translate: {name: row.assigneeName})">{{ row.initials }}</span>
} @else {
<span class="tb-alarms-assign-cell">
<span class="tb-alarms-dash" [matTooltip]="'home.alarms.not-assigned' | translate">—</span>
@if (canWrite) {
<button mat-icon-button type="button" class="tb-alarms-assign" [matTooltip]="'home.alarms.assign-me' | translate"
[attr.aria-label]="'home.alarms.assign-me' | translate" (click)="assignToMe(row, $event)">
<mat-icon>person_add</mat-icon>
</button>
}
</span>
}
</td>
}
</td>
<td class="col-age col-time" [matTooltip]="'home.alarms.started-at' | translate: {time: (row.alarm.createdTime | date: 'd MMM, HH:mm')}">{{ row.ago }}</td>
@if (!mine()) {
<td class="col-assignee">
@if (row.assigneeName) {
<span class="tb-alarms-assignee" [class.me]="row.mine" role="img"
[attr.aria-label]="row.mine ? ('home.alarms.assigned-you' | translate) : ('home.alarms.assigned-to' | translate: {name: row.assigneeName})"
[matTooltip]="row.mine ? ('home.alarms.assigned-you' | translate) : ('home.alarms.assigned-to' | translate: {name: row.assigneeName})">{{ row.initials }}</span>
<td class="col-ack">
@if (row.alarm.acknowledged) {
<mat-icon class="tb-alarms-acked" role="img" [matTooltip]="'home.alarms.acknowledged-tip' | translate"
[attr.aria-label]="'home.alarms.acknowledged-tip' | translate">check_circle</mat-icon>
} @else if (canWrite) {
<button mat-icon-button type="button" class="tb-alarms-ack" [matTooltip]="'home.alarms.acknowledge' | translate"
[attr.aria-label]="'home.alarms.acknowledge' | translate" (click)="acknowledge(row, $event)">
<mat-icon class="off">radio_button_unchecked</mat-icon>
<mat-icon class="on">check_circle_outline</mat-icon>
</button>
} @else {
<span class="tb-alarms-assign-cell">
<span class="tb-alarms-dash" [matTooltip]="'home.alarms.not-assigned' | translate">—</span>
@if (canWrite) {
<button mat-icon-button type="button" class="tb-alarms-assign" [matTooltip]="'home.alarms.assign-me' | translate"
[attr.aria-label]="'home.alarms.assign-me' | translate" (click)="assignToMe(row, $event)">
<mat-icon>person_add</mat-icon>
</button>
}
</span>
<mat-icon class="tb-alarms-unacked" role="img" [matTooltip]="'home.alarms.not-acknowledged' | translate"
[attr.aria-label]="'home.alarms.not-acknowledged' | translate">radio_button_unchecked</mat-icon>
}
</td>
}
<td class="col-ack">
@if (row.alarm.acknowledged) {
<mat-icon class="tb-alarms-acked" role="img" [matTooltip]="'home.alarms.acknowledged-tip' | translate"
[attr.aria-label]="'home.alarms.acknowledged-tip' | translate">check_circle</mat-icon>
} @else if (canWrite) {
<button mat-icon-button type="button" class="tb-alarms-ack" [matTooltip]="'home.alarms.acknowledge' | translate"
[attr.aria-label]="'home.alarms.acknowledge' | translate" (click)="acknowledge(row, $event)">
<mat-icon class="off">radio_button_unchecked</mat-icon>
<mat-icon class="on">check_circle_outline</mat-icon>
<td class="col-actions">
<button mat-icon-button type="button" class="tb-alarms-menu" [matMenuTriggerFor]="alarmMenu" [matMenuTriggerData]="{row}"
[attr.aria-label]="'home.alarms.actions' | translate" (click)="stop($event)">
<mat-icon>more_vert</mat-icon>
</button>
} @else {
<mat-icon class="tb-alarms-unacked" role="img" [matTooltip]="'home.alarms.not-acknowledged' | translate"
[attr.aria-label]="'home.alarms.not-acknowledged' | translate">radio_button_unchecked</mat-icon>
}
</td>
<td class="col-actions">
<button mat-icon-button type="button" class="tb-alarms-menu" [matMenuTriggerFor]="alarmMenu" [matMenuTriggerData]="{row}"
[attr.aria-label]="'home.alarms.actions' | translate" (click)="stop($event)">
<mat-icon>more_vert</mat-icon>
</button>
</td>
</tr>
}
</tbody>
</table>
} @else if (alarmsLoaded()) {
<div class="tb-home-empty-note">{{ emptyNote().key | translate: emptyNote().params }}</div>
</td>
</tr>
}
</tbody>
</table>
} @else if (alarmsLoaded()) {
<div class="tb-home-empty-note">{{ emptyNote().key | translate: emptyNote().params }}</div>
}
<tb-home-list-footer [total]="listed()" [expanded]="expanded()" link="/alarms/alarms" [params]="viewAllParams()"
(expandedChange)="expanded.set($event)"></tb-home-list-footer>
}
<tb-home-list-footer [total]="listed()" [expanded]="expanded()" link="/alarms/alarms" [params]="viewAllParams()"
(expandedChange)="expanded.set($event)"></tb-home-list-footer>
}
</tb-home-card>

26
ui-ngx/src/app/modules/home/pages/home-page/components/alarms-home.component.ts

@ -47,6 +47,8 @@ const SEVERITIES = [AlarmSeverity.CRITICAL, AlarmSeverity.MAJOR, AlarmSeverity.M
type AlarmSortKey = 'severity' | 'createdTime';
const DEFAULT_DIRECTION: Record<AlarmSortKey, Direction> = {severity: Direction.ASC, createdTime: Direction.DESC};
interface SeverityTile {
severity: AlarmSeverity;
count: number;
@ -113,7 +115,7 @@ export class AlarmsHomeComponent {
readonly severity = signal<AlarmSeverity | null>(null);
readonly expanded = signal(false);
readonly sortKey = signal<AlarmSortKey>('severity');
readonly sortDesc = signal(true);
readonly sortDirection = signal<Direction>(DEFAULT_DIRECTION.severity);
readonly total = signal<number | null>(null);
readonly hasRules = signal<boolean | null>(null);
@ -137,6 +139,8 @@ export class AlarmsHomeComponent {
private readonly alarms = signal<AlarmData[] | null>(null);
readonly listed = signal(0);
readonly alarmsLoaded = computed(() => this.alarms() !== null);
readonly ready = computed(() => this.total() !== null && this.alarms() !== null && this.hasRules() !== null && this.devices() !== null);
readonly refreshing = signal(false);
private readonly now = signal(Date.now());
private totalSubscriber: TelemetrySubscriber | null = null;
@ -179,13 +183,12 @@ export class AlarmsHomeComponent {
private readonly pageLink = computed<AlarmDataPageLink>(() => {
const severity = this.severity();
const key = this.sortKey();
const desc = this.sortDesc();
return {
page: 0,
pageSize: homeListPageSize(this.expanded()),
sortOrder: {
key: {type: EntityKeyType.ALARM_FIELD, key},
direction: key === 'severity' ? (desc ? Direction.ASC : Direction.DESC) : (desc ? Direction.DESC : Direction.ASC)
direction: this.sortDirection()
},
statusList: [AlarmSearchStatus.ACTIVE],
...(severity ? {severityList: [severity]} : {}),
@ -201,7 +204,7 @@ export class AlarmsHomeComponent {
this.devices.set(1);
}
if (this.canReadRules) {
this.alarmRulesService.getAlarmRules(new PageLink(1), undefined, {ignoreLoading: true}).pipe(
this.alarmRulesService.getAlarmRules(new PageLink(1), undefined, {ignoreLoading: true, ignoreErrors: true}).pipe(
catchError(() => of(null))
).subscribe(page => this.hasRules.set(!page || page.totalElements > 0));
} else {
@ -243,18 +246,23 @@ export class AlarmsHomeComponent {
sortBy(key: AlarmSortKey): void {
if (this.sortKey() === key) {
this.sortDesc.set(!this.sortDesc());
this.sortDirection.set(this.sortDirection() === Direction.ASC ? Direction.DESC : Direction.ASC);
} else {
this.sortKey.set(key);
this.sortDesc.set(true);
this.sortDirection.set(DEFAULT_DIRECTION[key]);
}
}
sortIcon(key: AlarmSortKey): string {
const direction = this.sortKey() === key ? this.sortDirection() : DEFAULT_DIRECTION[key];
return direction === Direction.ASC ? 'arrow_upward' : 'arrow_downward';
}
ariaSort(key: AlarmSortKey): string {
if (this.sortKey() !== key) {
return 'none';
}
return this.sortDesc() ? 'descending' : 'ascending';
return this.sortDirection() === Direction.ASC ? 'ascending' : 'descending';
}
addAlarmRule(): void {
@ -330,6 +338,7 @@ export class AlarmsHomeComponent {
private subscribeAlarms(pageLink: AlarmDataPageLink): void {
this.dataSubscriber?.unsubscribe();
this.refreshing.set(this.alarms() !== null);
const cmd = new AlarmDataCmd();
cmd.query = {
entityFilter: null,
@ -345,6 +354,7 @@ export class AlarmsHomeComponent {
if (update.data) {
this.listed.set(update.data.totalElements);
this.alarms.set(update.data.data);
this.refreshing.set(false);
} else if (update.update) {
const byId = new Map(update.update.map(alarm => [alarm.id.id, alarm]));
this.alarms.set((this.alarms() ?? []).map(alarm => byId.get(alarm.id.id) ?? alarm));
@ -373,7 +383,7 @@ export class AlarmsHomeComponent {
return subscriber;
}
private refresh(): void {
refresh(): void {
this.subscribeAlarms(this.pageLink());
this.totalSubscriber?.unsubscribe();
this.totalSubscriber = this.subscribeCount(this.total);

3
ui-ngx/src/app/modules/home/pages/home-page/components/api-usage-home.component.html

@ -4,7 +4,8 @@
SPDX-License-Identifier: BUSL-1.1
-->
<tb-home-card [card]="card">
<tb-home-card [card]="card" skeleton="usage" [hasData]="groups().length > 0" [reading]="reading()" [failed]="failed()"
[readAt]="readAt()" (retry)="read()">
<ng-container homeCardActions>
@if (groups().length) {
<tb-home-toggle class="tb-usage-tabs" [options]="tabOptions" [value]="tab()" [label]="'home.usage.view' | translate"

57
ui-ngx/src/app/modules/home/pages/home-page/components/api-usage-home.component.ts

@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { ChangeDetectionStrategy, Component, computed, DestroyRef, inject, NgZone, signal } from '@angular/core';
import { ChangeDetectionStrategy, Component, computed, DestroyRef, effect, inject, NgZone, signal, untracked } from '@angular/core';
import { UsageInfoService } from '@core/http/usage-info.service';
import { TourService } from '@core/services/tour.service';
import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service';
@ -11,6 +11,7 @@ import { UsageInfo } from '@shared/models/usage.models';
import { HomeCardId } from '@shared/models/user-settings.models';
import { HOME_CARDS } from '@home/pages/home-page/home-cards.models';
import { HomeToggleOption } from '@home/pages/home-page/components/home-toggle.component';
import { HomeLoadService } from '@home/pages/home-page/home-load.service';
const CRITICAL_PERCENT = 90;
@ -47,6 +48,11 @@ const API_ROWS: [string, string, string][] = [
['api-usage.ai-credits', 'aiCreditsCount', 'aiCreditsLimit']
];
interface UsageRead {
usage: UsageInfo;
apiUsage: {[key: string]: number};
}
@Component({
selector: 'tb-api-usage-home',
templateUrl: './api-usage-home.component.html',
@ -71,6 +77,17 @@ export class ApiUsageHomeComponent {
private readonly apiUsage = signal<{[key: string]: number} | null>(null);
private tabChosen = false;
private readonly load = inject(HomeLoadService);
private readonly usageService = inject(UsageInfoService);
private readonly telemetryWsService = inject(TelemetryWebsocketService);
private readonly zone = inject(NgZone);
private subscriber: TelemetrySubscriber | null = null;
private readonly usageRead = signal(false);
private readonly apiRead = signal(false);
readonly failed = signal(false);
readonly readAt = signal<number | null>(null);
readonly reading = computed(() => !this.failed() && (!this.usageRead() || !this.apiRead()));
readonly tab = signal<UsageGroupId>('entities');
readonly groups = computed<UsageGroup[]>(() => {
@ -94,12 +111,41 @@ export class ApiUsageHomeComponent {
});
constructor() {
inject(UsageInfoService).getUsageInfo().subscribe(usage => {
this.usage.set(usage);
const last = this.load.lastRead<UsageRead>(this.card.id);
if (last) {
this.usage.set(last.usage);
this.apiUsage.set(last.apiUsage);
this.readAt.set(this.load.readAt(this.card.id));
this.chooseTab();
}
this.read();
effect(() => {
if (this.usageRead() && this.apiRead()) {
const usage = this.usage();
const apiUsage = this.apiUsage();
untracked(() => {
this.load.keepRead<UsageRead>(this.card.id, {usage, apiUsage});
this.readAt.set(Date.now());
});
}
});
inject(DestroyRef).onDestroy(() => this.subscriber?.unsubscribe());
}
read(): void {
this.failed.set(false);
this.usageRead.set(false);
this.apiRead.set(false);
this.usageService.getUsageInfo({ignoreLoading: true, ignoreErrors: true}).subscribe({
next: usage => {
this.usage.set(usage);
this.usageRead.set(true);
this.chooseTab();
},
error: () => this.failed.set(true)
});
const subscriber = this.subscribeApiUsage(inject(TelemetryWebsocketService), inject(NgZone));
inject(DestroyRef).onDestroy(() => subscriber.unsubscribe());
this.subscriber?.unsubscribe();
this.subscriber = this.subscribeApiUsage(this.telemetryWsService, this.zone);
}
private subscribeApiUsage(telemetryWsService: TelemetryWebsocketService, zone: NgZone): TelemetrySubscriber {
@ -128,6 +174,7 @@ export class ApiUsageHomeComponent {
}
});
this.apiUsage.set(values);
this.apiRead.set(true);
this.chooseTab();
});
subscriber.subscribe();

3
ui-ngx/src/app/modules/home/pages/home-page/components/dashboards-home.component.html

@ -4,7 +4,8 @@
SPDX-License-Identifier: BUSL-1.1
-->
<tb-home-card [card]="card" [count]="total()">
<tb-home-card [card]="card" [count]="total()" skeleton="dashboards" [hasData]="loaded()" [reading]="state.reading()" [failed]="state.failed()"
[readAt]="state.readAt()" [keepHeight]="!expanded() && tab() === 'last' && !picking()" (retry)="state.read()">
<ng-container homeCardActions>
@if (total()) {
<tb-home-toggle [options]="tabOptions" [value]="tab()" [label]="'home.dashboards.view' | translate" (valueChange)="setTab($event)"></tb-home-toggle>

40
ui-ngx/src/app/modules/home/pages/home-page/components/dashboards-home.component.ts

@ -5,7 +5,7 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { TranslateService } from '@ngx-translate/core';
import { of, Subject } from 'rxjs';
import { forkJoin, Observable, of, Subject } from 'rxjs';
import { catchError, debounceTime, map, switchMap } from 'rxjs/operators';
import { AppState } from '@core/core.state';
import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors';
@ -22,6 +22,7 @@ import { HomeCardId, UserDashboardAction, UserDashboardsInfo } from '@shared/mod
import { HOME_CARDS } from '@home/pages/home-page/home-cards.models';
import { homeAgo, homeListShown, homeToast } from '@home/pages/home-page/home-list.models';
import { MINUTE } from '@shared/models/time/time.models';
import { HomeLoadService } from '@home/pages/home-page/home-load.service';
import { HomeToggleOption } from '@home/pages/home-page/components/home-toggle.component';
type DashboardsTab = 'last' | 'starred';
@ -44,6 +45,12 @@ interface StarCandidate {
ago: string | null;
}
interface DashboardsRead {
info: UserDashboardsInfo;
others: {id: string; title: string}[];
total: number;
}
@Component({
selector: 'tb-dashboards-home',
templateUrl: './dashboards-home.component.html',
@ -94,6 +101,13 @@ export class DashboardsHomeComponent {
readonly loaded = computed(() => this.total() !== null && this.info() !== null);
private readonly load = inject(HomeLoadService);
readonly state = this.load.reader<DashboardsRead>(this.card.id, () => this.request(), read => {
this.info.set(read.info);
this.others.set(read.others);
this.total.set(read.total);
});
private readonly starredIds = computed(() => new Set((this.info()?.starred ?? []).map(dashboard => dashboard.id)));
private readonly visits = computed(() => new Map((this.info()?.last ?? []).map(dashboard => [dashboard.id, dashboard.lastVisited])));
@ -144,16 +158,7 @@ export class DashboardsHomeComponent {
constructor() {
if (this.dashboardsLink && this.authUser?.authority !== Authority.SYS_ADMIN) {
this.userSettingsService.getUserDashboardsInfo({ignoreLoading: true}).subscribe(info => {
this.info.set({last: info?.last ?? [], starred: info?.starred ?? []});
});
this.dashboardService.getUserDashboards(this.authUser.userId, null,
new PageLink(FILL_SIZE, 0, null, {property: 'createdTime', direction: Direction.DESC}), {ignoreLoading: true}).pipe(
catchError(() => of(null))
).subscribe(page => {
this.others.set((page?.data ?? []).map(dashboard => ({id: dashboard.id.id, title: dashboard.title})));
this.total.set(page?.totalElements ?? 0);
});
this.state.start();
} else {
this.info.set({last: [], starred: []});
this.total.set(0);
@ -179,6 +184,19 @@ export class DashboardsHomeComponent {
inject(DestroyRef).onDestroy(() => clearInterval(tick));
}
private request(): Observable<DashboardsRead> {
const config = {ignoreLoading: true, ignoreErrors: true};
return forkJoin([
this.userSettingsService.getUserDashboardsInfo(config),
this.dashboardService.getUserDashboards(this.authUser.userId, null,
new PageLink(FILL_SIZE, 0, null, {property: 'createdTime', direction: Direction.DESC}), config)
]).pipe(map(([info, page]) => ({
info: {last: info?.last ?? [], starred: info?.starred ?? []},
others: (page?.data ?? []).map(dashboard => ({id: dashboard.id.id, title: dashboard.title})),
total: page?.totalElements ?? 0
})));
}
setTab(tab: DashboardsTab): void {
this.tab.set(tab);
this.closePicker();

40
ui-ngx/src/app/modules/home/pages/home-page/components/devices-activity-home.component.html

@ -4,7 +4,7 @@
SPDX-License-Identifier: BUSL-1.1
-->
<tb-home-card [card]="card">
<tb-home-card [card]="card" skeleton="activity" [hasData]="loaded()" [reading]="!loaded()" (retry)="retry()">
<span homeCardTitleExtra class="tb-activity-period">{{ 'home.activity.period' | translate }}</span>
<ng-container homeCardActions>
@if (loaded() && !empty() && series.length > 1) {
@ -12,23 +12,25 @@
(valueChange)="setTab($event)"></tb-home-toggle>
}
</ng-container>
@if (empty()) {
<div class="tb-home-setup-empty">
<span class="tb-home-setup-empty-glyph" aria-hidden="true"><mat-icon>show_chart</mat-icon></span>
<div class="tb-home-setup-empty-title">{{ (sysAdmin ? 'home.activity.no-messages' : 'home.activity.none') | translate }}</div>
</div>
} @else {
<div class="tb-activity-pair" [class.single]="series.length === 1" [attr.data-tab]="tab()">
@for (series of series; track series.id) {
<div class="tb-activity-series" [attr.data-series]="series.id">
<div class="tb-activity-name">{{ series.label | translate }}</div>
@if (series.id === 'devices') {
<div #devicesChart class="tb-activity-chart" role="img" [attr.aria-label]="series.label | translate"></div>
} @else {
<div #messagesChart class="tb-activity-chart" role="img" [attr.aria-label]="series.label | translate"></div>
}
</div>
}
</div>
@if (loaded()) {
@if (empty()) {
<div class="tb-home-setup-empty">
<span class="tb-home-setup-empty-glyph" aria-hidden="true"><mat-icon>show_chart</mat-icon></span>
<div class="tb-home-setup-empty-title">{{ (sysAdmin ? 'home.activity.no-messages' : 'home.activity.none') | translate }}</div>
</div>
} @else {
<div class="tb-activity-pair" [class.single]="series.length === 1" [attr.data-tab]="tab()">
@for (series of series; track series.id) {
<div class="tb-activity-series" [attr.data-series]="series.id">
<div class="tb-activity-name">{{ series.label | translate }}</div>
@if (series.id === 'devices') {
<div #devicesChart class="tb-activity-chart" role="img" [attr.aria-label]="series.label | translate"></div>
} @else {
<div #messagesChart class="tb-activity-chart" role="img" [attr.aria-label]="series.label | translate"></div>
}
</div>
}
</div>
}
}
</tb-home-card>

4
ui-ngx/src/app/modules/home/pages/home-page/components/devices-activity-home.component.ts

@ -249,6 +249,10 @@ export class DevicesActivityHomeComponent implements AfterViewInit {
return `${day}, ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
}
retry(): void {
this.subscribe();
}
setTab(tab: ActivitySeries): void {
this.tab.set(tab);
setTimeout(() => Object.values(this.charts).forEach(chart => chart.resize()));

165
ui-ngx/src/app/modules/home/pages/home-page/components/devices-home.component.html

@ -4,7 +4,8 @@
SPDX-License-Identifier: BUSL-1.1
-->
<tb-home-card [card]="card" [count]="total()">
<tb-home-card [card]="card" [count]="ready() ? total() : null" skeleton="devices" [hasData]="ready()" [reading]="!ready()"
[refreshing]="refreshing()" [keepHeight]="!expanded() && !filter()" (retry)="refresh()">
<ng-container homeCardActions>
@if (canAdd) {
<a mat-button color="primary" class="tb-home-add" routerLink="/entities/devices/all" [queryParams]="{action: 'add'}">
@ -13,90 +14,92 @@
</a>
}
</ng-container>
@if (total() === 0) {
<div class="tb-home-setup-empty">
<span class="tb-home-setup-empty-glyph" aria-hidden="true"><mat-icon>memory</mat-icon></span>
@if (canAdd) {
<div class="tb-home-setup-empty-text">
<p>{{ 'home.devices.none' | translate }}</p>
<div class="tb-home-setup-empty-actions">
<a [href]="howToLink" target="_blank" rel="noopener">{{ 'home.devices.how-to' | translate }}<mat-icon class="tb-home-ext" aria-hidden="true">north_east</mat-icon><span class="tb-ai-sr-only">{{ 'home.dashboards.opens-new-tab' | translate }}</span></a>
@if (ready()) {
@if (total() === 0) {
<div class="tb-home-setup-empty">
<span class="tb-home-setup-empty-glyph" aria-hidden="true"><mat-icon>memory</mat-icon></span>
@if (canAdd) {
<div class="tb-home-setup-empty-text">
<p>{{ 'home.devices.none' | translate }}</p>
<div class="tb-home-setup-empty-actions">
<a [href]="howToLink" target="_blank" rel="noopener">{{ 'home.devices.how-to' | translate }}<mat-icon class="tb-home-ext" aria-hidden="true">north_east</mat-icon><span class="tb-ai-sr-only">{{ 'home.dashboards.opens-new-tab' | translate }}</span></a>
</div>
</div>
} @else {
<div class="tb-home-setup-empty-title">{{ 'home.devices.none-assigned' | translate }}</div>
}
</div>
} @else if (total()) {
<div class="tb-home-tiles">
@for (tile of tiles(); track tile.state) {
<button type="button" class="tb-home-tile" [class]="tile.state" [class.zero]="!tile.count" [class.can-reset]="tile.pressed"
[disabled]="!tile.count && !tile.pressed" [attr.aria-pressed]="tile.count || tile.pressed ? tile.pressed : null"
[matTooltip]="(tile.pressed ? 'home.devices.show-every' : 'home.devices.show-only-' + tile.state) | translate"
[matTooltipDisabled]="!tile.count && !tile.pressed" matTooltipPosition="above" (click)="pick(tile)">
<span class="tb-home-tile-label">{{ 'home.devices.' + tile.state | translate }}</span>
<span class="tb-home-tile-count">{{ tile.count | shortNumber }}</span>
</button>
}
</div>
@if (allActive()) {
<div class="tb-home-all-clear">
<span class="tb-home-all-clear-glyph" aria-hidden="true"><mat-icon>check</mat-icon></span>
<span>{{ (total() === 1 ? 'home.devices.one-active' : 'home.devices.all-active') | translate: {count: total()} }}</span>
</div>
} @else {
<div class="tb-home-setup-empty-title">{{ 'home.devices.none-assigned' | translate }}</div>
}
</div>
} @else if (total()) {
<div class="tb-home-tiles">
@for (tile of tiles(); track tile.state) {
<button type="button" class="tb-home-tile" [class]="tile.state" [class.zero]="!tile.count" [class.can-reset]="tile.pressed"
[disabled]="!tile.count && !tile.pressed" [attr.aria-pressed]="tile.count || tile.pressed ? tile.pressed : null"
[matTooltip]="(tile.pressed ? 'home.devices.show-every' : 'home.devices.show-only-' + tile.state) | translate"
[matTooltipDisabled]="!tile.count && !tile.pressed" matTooltipPosition="above" (click)="pick(tile)">
<span class="tb-home-tile-label">{{ 'home.devices.' + tile.state | translate }}</span>
<span class="tb-home-tile-count">{{ tile.count | shortNumber }}</span>
</button>
}
</div>
@if (allActive()) {
<div class="tb-home-all-clear">
<span class="tb-home-all-clear-glyph" aria-hidden="true"><mat-icon>check</mat-icon></span>
<span>{{ (total() === 1 ? 'home.devices.one-active' : 'home.devices.all-active') | translate: {count: total()} }}</span>
</div>
}
@if (rows().length) {
<table class="tb-home-table tb-devices-table">
<thead>
<tr>
<th class="col-name sortable" [class.sorted]="sortKey() === 'name'" [attr.aria-sort]="ariaSort('name')">
<button type="button" class="th-label" [matTooltip]="'home.devices.sort-name' | translate" (click)="sortBy('name')">
<span>{{ 'home.devices.name' | translate }}</span>
<mat-icon class="tb-sort-icon">{{ sortIcon('name') }}</mat-icon>
</button>
</th>
<th class="col-profile">{{ 'home.devices.profile' | translate }}</th>
<th class="col-state"><span class="th-text">{{ 'home.devices.state' | translate }}</span></th>
<th class="col-time sortable" [class.sorted]="sortKey() === 'last'" [attr.aria-sort]="ariaSort('last')">
<button type="button" class="th-label" [matTooltip]="'home.devices.sort-last' | translate" (click)="sortBy('last')">
<span>{{ 'home.devices.last-activity' | translate }}</span>
<mat-icon class="tb-sort-icon">{{ sortIcon('last') }}</mat-icon>
</button>
</th>
</tr>
</thead>
<tbody>
@for (row of rows(); track row.id) {
<tr (click)="open(row)">
<td class="col-name">
<span class="tb-devices-cell-main">
@if (row.url) {
<a class="tb-home-cell-link" [routerLink]="row.url" (click)="$event.stopPropagation()">{{ row.name }}</a>
} @else {
{{ row.name }}
}
</span>
<span class="tb-devices-cell-sub">{{ row.profile }}</span>
</td>
<td class="col-profile">{{ row.profile }}</td>
<td class="col-state">
<span class="tb-devices-state" [class.active]="row.active" [class.inactive]="!row.active">
<span class="tb-devices-state-word">{{ (row.active ? 'home.devices.active' : 'home.devices.inactive') | translate }}</span>
</span>
</td>
@if (row.lastActivity) {
<td class="col-time" [matTooltip]="'home.devices.last-activity-at' | translate: {time: (row.lastActivity | date: 'd MMM, HH:mm')}">{{ row.ago }}</td>
} @else {
<td class="col-time"><span class="tb-devices-never" [matTooltip]="'home.devices.no-data' | translate">{{ 'home.devices.never' | translate }}</span></td>
}
@if (rows().length) {
<table class="tb-home-table tb-devices-table">
<thead>
<tr>
<th class="col-name sortable" [class.sorted]="sortKey() === 'name'" [attr.aria-sort]="ariaSort('name')">
<button type="button" class="th-label" [matTooltip]="'home.devices.sort-name' | translate" (click)="sortBy('name')">
<span>{{ 'home.devices.name' | translate }}</span>
<mat-icon class="tb-sort-icon">{{ sortIcon('name') }}</mat-icon>
</button>
</th>
<th class="col-profile">{{ 'home.devices.profile' | translate }}</th>
<th class="col-state"><span class="th-text">{{ 'home.devices.state' | translate }}</span></th>
<th class="col-time sortable" [class.sorted]="sortKey() === 'last'" [attr.aria-sort]="ariaSort('last')">
<button type="button" class="th-label" [matTooltip]="'home.devices.sort-last' | translate" (click)="sortBy('last')">
<span>{{ 'home.devices.last-activity' | translate }}</span>
<mat-icon class="tb-sort-icon">{{ sortIcon('last') }}</mat-icon>
</button>
</th>
</tr>
}
</tbody>
</table>
} @else if (loaded()) {
<div class="tb-home-empty-note">{{ ('home.devices.none-' + (filter() ?? 'active')) | translate }}</div>
</thead>
<tbody>
@for (row of rows(); track row.id) {
<tr (click)="open(row)">
<td class="col-name">
<span class="tb-devices-cell-main">
@if (row.url) {
<a class="tb-home-cell-link" [routerLink]="row.url" (click)="$event.stopPropagation()">{{ row.name }}</a>
} @else {
{{ row.name }}
}
</span>
<span class="tb-devices-cell-sub">{{ row.profile }}</span>
</td>
<td class="col-profile">{{ row.profile }}</td>
<td class="col-state">
<span class="tb-devices-state" [class.active]="row.active" [class.inactive]="!row.active">
<span class="tb-devices-state-word">{{ (row.active ? 'home.devices.active' : 'home.devices.inactive') | translate }}</span>
</span>
</td>
@if (row.lastActivity) {
<td class="col-time" [matTooltip]="'home.devices.last-activity-at' | translate: {time: (row.lastActivity | date: 'd MMM, HH:mm')}">{{ row.ago }}</td>
} @else {
<td class="col-time"><span class="tb-devices-never" [matTooltip]="'home.devices.no-data' | translate">{{ 'home.devices.never' | translate }}</span></td>
}
</tr>
}
</tbody>
</table>
} @else if (loaded()) {
<div class="tb-home-empty-note">{{ ('home.devices.none-' + (filter() ?? 'active')) | translate }}</div>
}
<tb-home-list-footer [total]="listed()" [expanded]="expanded()" [link]="devicesLink" [params]="viewAllParams()"
(expandedChange)="expanded.set($event)"></tb-home-list-footer>
}
<tb-home-list-footer [total]="listed()" [expanded]="expanded()" [link]="devicesLink" [params]="viewAllParams()"
(expandedChange)="expanded.set($event)"></tb-home-list-footer>
}
</tb-home-card>

55
ui-ngx/src/app/modules/home/pages/home-page/components/devices-home.component.ts

@ -123,12 +123,24 @@ export class DevicesHomeComponent {
readonly loaded = computed(() => this.lists().length > 0 && this.lists().every(list => list !== null));
readonly listed = computed(() => this.listTotals().reduce((sum, count, index) =>
private readonly settled = signal(false);
private readonly waiting = signal(new Set<number>());
readonly ready = computed(() => this.total() !== null && this.inactive() !== null && this.active() !== null
&& (this.total() === 0 || this.loaded() || this.settled()));
readonly refreshing = computed(() => this.settled() && this.waiting().size > 0);
private readonly held = signal<{rows: DeviceHomeRow[]; listed: number} | null>(null);
readonly listed = computed(() => this.held()?.listed ?? this.listTotals().reduce((sum, count, index) =>
this.listQueries[index]?.counted ? sum + count : sum, 0));
private listQueries: DeviceQuery[] = [];
readonly rows = computed<DeviceHomeRow[]>(() => {
readonly rows = computed<DeviceHomeRow[]>(() => this.held()?.rows ?? this.freshRows());
private readonly freshRows = computed<DeviceHomeRow[]>(() => {
const keyType = this.stateKeyType();
const now = this.now();
const merged = this.lists().flatMap((list, index) => {
@ -219,6 +231,22 @@ export class DevicesHomeComponent {
return this.sortKey() === 'last' && !this.sortDesc() ? 'arrow_upward' : 'arrow_downward';
}
refresh(): void {
const keyType = this.stateKeyType();
if (keyType) {
if (this.total() === null) {
this.homeCounts.reread(EntityType.DEVICE);
}
if (this.inactive() === null) {
this.homeCounts.reread(EntityType.DEVICE, this.activeFilter(keyType, false));
}
if (this.active() === null) {
this.homeCounts.reread(EntityType.DEVICE, this.activeFilter(keyType, true));
}
}
this.subscribeLists(this.queries(), homeListPageSize(this.expanded()));
}
open(row: DeviceHomeRow): void {
if (row.url) {
this.router.navigateByUrl(row.url);
@ -232,11 +260,13 @@ export class DevicesHomeComponent {
this.dataSubscribers = [];
return;
}
if (this.settled() && !this.held()) {
this.held.set({rows: this.rows(), listed: this.listed()});
}
this.listQueries = queries;
const previous = this.lists();
const previousTotals = this.listTotals();
this.lists.set(queries.map((_, index) => previous[index] ?? null));
this.listTotals.set(queries.map((_, index) => previousTotals[index] ?? 0));
this.waiting.set(new Set(queries.map((_, index) => index)));
this.lists.set(queries.map(() => null));
this.listTotals.set(queries.map(() => 0));
this.dataSubscribers = queries.map((query, index) => {
const cmd = new EntityDataCmd();
const pageLink: EntityDataPageLink = {
@ -267,8 +297,8 @@ export class DevicesHomeComponent {
subscriber.entityData$.subscribe(update => {
if (update.data) {
this.setList(index, update.data.data, update.data.totalElements);
} else if (update.update) {
const list = this.lists()[index] ?? [];
} else if (update.update && this.lists()[index]) {
const list = this.lists()[index];
const byId = new Map(update.update.map(data => [data.entityId.id, data]));
this.setList(index, list.map(data => this.merge(data, byId.get(data.entityId.id))), null);
}
@ -282,6 +312,15 @@ export class DevicesHomeComponent {
const lists = [...this.lists()];
lists[index] = data;
this.lists.set(lists);
if (this.waiting().has(index)) {
const waiting = new Set(this.waiting());
waiting.delete(index);
this.waiting.set(waiting);
}
if (this.loaded()) {
this.settled.set(true);
this.held.set(null);
}
if (total !== null) {
const totals = [...this.listTotals()];
totals[index] = total;

11
ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.html

@ -4,16 +4,17 @@
SPDX-License-Identifier: BUSL-1.1
-->
<tb-home-card [card]="card" [hideable]="true" [countText]="progress()">
<tb-home-card [card]="card" [hideable]="true" [countText]="progress()" [reading]="state.reading()" [failed]="state.failed()" [readAt]="state.readAt()"
[footText]="footText()" (retry)="state.read()">
@if (loaded()) {
<ol class="tb-gs-steps">
<ol class="tb-gs-steps" [class.pending]="!known()">
@for (step of steps; track step.key; let i = $index) {
<li [class.done]="isDone(i)" [class.open]="open() === i">
<div class="tb-gs-row">
<button type="button" class="tb-gs-mark" role="checkbox" [attr.aria-checked]="isDone(i)"
[attr.aria-label]="'home.get-started.done-aria' | translate: {title: ('home.get-started.' + step.key + '.title' | translate)}"
[matTooltip]="(isDone(i) ? 'home.get-started.mark-undone' : 'home.get-started.mark-done') | translate"
(click)="toggle(i)">
[disabled]="!state.fresh()" (click)="toggle(i)">
@if (isDone(i)) {
<mat-icon>check</mat-icon>
} @else {
@ -43,7 +44,7 @@
}
<span class="tb-gs-spacer"></span>
@if (!isDone(i)) {
<button mat-button type="button" class="tb-gs-done" (click)="toggle(i)">
<button mat-button type="button" class="tb-gs-done" [disabled]="!state.fresh()" (click)="toggle(i)">
<mat-icon>check</mat-icon>{{ 'home.get-started.done' | translate }}
</button>
}
@ -56,7 +57,7 @@
</ol>
@if (allDone()) {
<div class="tb-gs-again">
<button mat-button type="button" (click)="startOver()"><mat-icon>restart_alt</mat-icon>{{ 'home.get-started.start-over' | translate }}</button>
<button mat-button type="button" [disabled]="!state.fresh()" (click)="startOver()"><mat-icon>restart_alt</mat-icon>{{ 'home.get-started.start-over' | translate }}</button>
</div>
}
}

13
ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.scss

@ -61,11 +61,15 @@
color: inherit;
}
&:hover {
&:hover:not(:disabled) {
border-color: var(--tb-ok, #198038);
color: var(--tb-ok, #198038);
}
&:disabled {
cursor: default;
}
&:focus-visible {
outline: 2px solid var(--tb-primary-500);
outline-offset: 2px;
@ -78,6 +82,13 @@ li.done .tb-gs-mark {
color: var(--tb-ok, #198038);
}
.tb-gs-steps.pending .tb-gs-mark {
border-color: transparent;
background: rgba(0, 0, 0, 0.06);
color: transparent;
cursor: default;
}
.tb-gs-title {
display: flex;
flex: 1;

26
ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.ts

@ -13,6 +13,7 @@ import {
untracked
} from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { map } from 'rxjs/operators';
import { ClipboardService } from 'ngx-clipboard';
import { UserSettingsService } from '@core/http/user-settings.service';
import { WhiteLabelingService } from '@core/http/white-labeling.service';
@ -21,6 +22,7 @@ import { baseUrl } from '@core/utils';
import { GettingStarted, HomeCardId } from '@shared/models/user-settings.models';
import { HOME_CARDS } from '@home/pages/home-page/home-cards.models';
import { homeToast } from '@home/pages/home-page/home-list.models';
import { HomeLoadService } from '@home/pages/home-page/home-load.service';
import { decorateCodeBlocks } from '@home/components/ai/ai-code-block';
export interface GetStartedStep {
@ -68,6 +70,14 @@ export class GetStartedHomeComponent {
readonly loaded = computed(() => this.settings() !== null);
readonly state = inject(HomeLoadService).reader<GettingStarted>(this.card.id,
() => this.userSettingsService.getGettingStarted({ignoreLoading: true, ignoreErrors: true}).pipe(
map(settings => ({lastSelectedIndex: settings?.lastSelectedIndex ?? 0, maxSelectedIndex: settings?.maxSelectedIndex ?? 0}))
),
settings => this.settings.set(settings));
readonly known = computed(() => !!this.state.last || this.state.fresh());
readonly footText = computed(() => this.state.failed() && !this.known() ? this.translate.instant('home.load.progress-failed') : null);
readonly done = computed(() => Math.min(this.steps.length, Math.max(0, this.settings()?.maxSelectedIndex ?? 0)));
readonly allDone = computed(() => this.done() >= this.steps.length);
@ -81,7 +91,7 @@ export class GetStartedHomeComponent {
});
readonly progress = computed(() => {
if (!this.loaded() || !this.done()) {
if (!this.known() || !this.done()) {
return null;
}
return this.allDone()
@ -90,10 +100,8 @@ export class GetStartedHomeComponent {
});
constructor() {
this.userSettingsService.getGettingStarted({ignoreLoading: true}).subscribe({
next: settings => this.settings.set({lastSelectedIndex: settings?.lastSelectedIndex ?? 0, maxSelectedIndex: settings?.maxSelectedIndex ?? 0}),
error: () => this.settings.set({lastSelectedIndex: 0, maxSelectedIndex: 0})
});
this.settings.set({lastSelectedIndex: 0, maxSelectedIndex: 0});
this.state.start();
effect(() => {
this.open();
untracked(() => afterNextRender(() => decorateCodeBlocks(this.host.nativeElement, this.translate,
@ -110,8 +118,13 @@ export class GetStartedHomeComponent {
}
select(index: number): void {
if (index !== this.open()) {
if (index === this.open()) {
return;
}
if (this.state.fresh()) {
this.save({...this.settings(), lastSelectedIndex: index});
} else {
this.settings.set({...this.settings(), lastSelectedIndex: index});
}
}
@ -135,6 +148,7 @@ export class GetStartedHomeComponent {
private save(settings: GettingStarted): void {
this.settings.set(settings);
this.state.keep(settings);
this.userSettingsService.updateGettingStarted(settings, {ignoreLoading: true}).subscribe();
}
}

7
ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.html

@ -4,9 +4,10 @@
SPDX-License-Identifier: BUSL-1.1
-->
<tb-home-card [card]="cardDefinition()" [hideable]="true" [countText]="progress()">
<tb-home-card [card]="card" [hideable]="true" [countText]="progress()" skeleton="get-started-sys-admin" [hasData]="loaded()"
[reading]="reading()" [failed]="failed()" [readAt]="readAt()" (retry)="read()">
@if (loaded()) {
<div class="tb-sgs-bar" role="progressbar" [attr.aria-label]="cardDefinition().name | translate" aria-valuemin="0"
<div class="tb-sgs-bar" role="progressbar" [attr.aria-label]="card.name | translate" aria-valuemin="0"
[attr.aria-valuemax]="total" [attr.aria-valuenow]="doneCount()">
<i [style.width.%]="doneCount() / total * 100"></i>
</div>
@ -61,7 +62,7 @@
}
<span class="tb-sgs-spacer"></span>
@if (!step.needed && stepState !== 'done') {
<button mat-button type="button" class="tb-sgs-skip" (click)="skip(step)">
<button mat-button type="button" class="tb-sgs-skip" [disabled]="!canSkip()" (click)="skip(step)">
{{ (stepState === 'skipped' ? 'home.get-started-sys-admin.undo-skip' : 'home.get-started-sys-admin.skip') | translate }}
</button>
}

99
ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.ts

@ -5,24 +5,22 @@ import {
Component,
computed,
DestroyRef,
ElementRef,
inject,
signal
} from '@angular/core';
import { Store } from '@ngrx/store';
import { TranslateService } from '@ngx-translate/core';
import { of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AppState } from '@core/core.state';
import { ActionPreferencesUpdateHomeCards } from '@core/auth/auth.actions';
import { UserSettingsService } from '@core/http/user-settings.service';
import { AdminService } from '@core/http/admin.service';
import { WhiteLabelingService } from '@core/http/white-labeling.service';
import { EntityType } from '@shared/models/entity-type.models';
import { FeaturesInfo } from '@shared/models/settings.models';
import { HomeCardId } from '@shared/models/user-settings.models';
import { HOME_CARDS } from '@home/pages/home-page/home-cards.models';
import { HomeCountService } from '@home/pages/home-page/home-count.service';
import { readStored, writeStored } from '@core/local-storage/stored';
import { HomeLoadService } from '@home/pages/home-page/home-load.service';
import { SysAdminHomeService } from '@home/pages/home-page/sys-admin-home.service';
type SysAdminStepKey = 'tenant' | 'email' | 'sms' | 'wl' | '2fa' | 'oauth' | 'slack';
@ -47,12 +45,11 @@ const STEPS: SysAdminStep[] = [
{key: 'slack', needed: false, link: '/settings/notifications', guide: 'user-guide/ui/slack-settings/', feature: 'notificationEnabled'}
];
const LOADING_HEIGHT = 398;
const HEIGHT_KEY = 'tb-home-get-started-sys-admin-height';
const storedHeight = (): number => {
return Number(readStored(HEIGHT_KEY)) || LOADING_HEIGHT;
};
interface SysAdminStartRead {
tenants: number;
features: FeaturesInfo;
skipped: string[];
}
export type StepState = 'done' | 'skipped' | 'todo';
@ -65,7 +62,7 @@ export type StepState = 'done' | 'skipped' | 'todo';
})
export class GetStartedSysAdminHomeComponent {
private readonly card = HOME_CARDS[HomeCardId.GET_STARTED_SYS_ADMIN];
readonly card = HOME_CARDS[HomeCardId.GET_STARTED_SYS_ADMIN];
readonly total = STEPS.length;
@ -86,7 +83,14 @@ export class GetStartedSysAdminHomeComponent {
readonly loaded = computed(() => this.tenants() !== null && this.features() !== null && this.skipped() !== null);
readonly cardDefinition = computed(() => this.loaded() ? this.card : {...this.card, height: storedHeight()});
private readonly load = inject(HomeLoadService);
private readonly fresh = signal({tenants: false, features: false, skipped: false});
readonly reading = computed(() => !this.failed() && Object.values(this.fresh()).some(value => !value));
readonly failed = signal(false);
readonly canSkip = computed(() => this.fresh().skipped);
readonly readAt = signal<number | null>(null);
private readonly adminService = inject(AdminService);
private readonly homeCounts = inject(HomeCountService);
readonly states = computed<Record<SysAdminStepKey, StepState>>(() => {
const features = this.features();
@ -121,18 +125,35 @@ export class GetStartedSysAdminHomeComponent {
readonly tenantCount = computed(() => this.tenants() ?? 0);
constructor() {
const config = {ignoreErrors: true, ignoreLoading: true};
inject(SysAdminHomeService).featuresInfo$.subscribe(features => this.features.set(features ?? {} as FeaturesInfo));
this.userSettingsService.getGettingStarted(config).pipe(catchError(() => of(null)))
.subscribe(settings => this.skipped.set(settings?.skipped ?? []));
const destroyRef = inject(DestroyRef);
inject(HomeCountService).watchEntityCount(EntityType.TENANT, count => this.tenants.set(count), destroyRef);
const host = inject<ElementRef<HTMLElement>>(ElementRef);
const observer = new ResizeObserver(() => this.rememberHeight(host.nativeElement));
observer.observe(host.nativeElement);
destroyRef.onDestroy(() => {
observer.disconnect();
});
const last = this.load.lastRead<SysAdminStartRead>(this.card.id);
if (last) {
this.tenants.set(last.tenants);
this.features.set(last.features);
this.skipped.set(last.skipped);
this.readAt.set(this.load.readAt(this.card.id));
}
inject(SysAdminHomeService).featuresInfo$.subscribe(features => this.setFeatures(features));
this.readSkipped();
this.homeCounts.watchEntityCount(EntityType.TENANT, count => {
this.tenants.set(count);
this.markFresh('tenants');
}, inject(DestroyRef));
}
read(): void {
this.failed.set(false);
if (!this.fresh().features) {
this.adminService.getFeaturesInfo({ignoreErrors: true, ignoreLoading: true}).subscribe({
next: features => this.setFeatures(features),
error: () => this.failed.set(true)
});
}
if (!this.fresh().skipped) {
this.readSkipped();
}
if (!this.fresh().tenants) {
this.homeCounts.reread(EntityType.TENANT);
}
}
state(step: SysAdminStep): StepState {
@ -156,15 +177,37 @@ export class GetStartedSysAdminHomeComponent {
const next = skipped.includes(step.key) ? skipped.filter(key => key !== step.key) : [...skipped, step.key];
this.skipped.set(next);
this.selected.set(null);
if (this.loaded()) {
this.load.keepRead<SysAdminStartRead>(this.card.id, {tenants: this.tenants(), features: this.features(), skipped: next});
}
this.userSettingsService.updateGettingStarted({skipped: next}).subscribe();
}
private rememberHeight(element: HTMLElement): void {
const height = Math.round(element.getBoundingClientRect().height);
if (!this.loaded() || !height) {
private readSkipped(): void {
this.userSettingsService.getGettingStarted({ignoreErrors: true, ignoreLoading: true}).subscribe({
next: settings => {
this.skipped.set(settings?.skipped ?? []);
this.markFresh('skipped');
},
error: () => this.failed.set(true)
});
}
private setFeatures(features: FeaturesInfo | null): void {
if (!features) {
this.failed.set(true);
return;
}
writeStored(HEIGHT_KEY, String(height));
this.features.set(features);
this.markFresh('features');
}
private markFresh(part: 'tenants' | 'features' | 'skipped'): void {
this.fresh.set({...this.fresh(), [part]: true});
if (Object.values(this.fresh()).every(value => value)) {
this.load.keepRead<SysAdminStartRead>(this.card.id, {tenants: this.tenants(), features: this.features(), skipped: this.skipped()});
this.readAt.set(Date.now());
}
}
close(): void {

110
ui-ngx/src/app/modules/home/pages/home-page/components/home-card.component.scss

@ -1,5 +1,7 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
@use './home-load';
:host {
display: block;
min-width: 0;
@ -165,3 +167,111 @@
padding-top: var(--tb-home-card-padding, 20px);
}
}
:host(.tb-mark-all-icon) .tb-home-card-header {
flex-wrap: nowrap;
}
:host(.tb-mark-all-icon) .tb-home-card-title-group {
flex: 1 1 auto;
}
:host(.tb-mark-all-icon) .tb-home-card-title > span:not(.tb-home-card-count) {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.tb-home-load-failed {
display: flex;
flex: none;
align-items: center;
gap: 12px;
padding: 2px 0;
font: 400 14px/20px var(--tb-font, Roboto, sans-serif);
letter-spacing: 0.2px;
color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6));
}
.tb-home-load-failed-glyph {
display: inline-flex;
flex: none;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
border-radius: 50%;
background: rgba(0, 0, 0, 0.06);
color: var(--tb-ink-54, rgba(0, 0, 0, 0.54));
.mat-icon {
width: 20px;
height: 20px;
font-size: 20px;
}
}
.tb-home-load-failed-text {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 2px;
}
.tb-home-load-stale {
display: flex;
align-items: center;
gap: 8px;
padding-top: 8px;
border-top: 1px solid var(--tb-line-soft, rgba(0, 0, 0, 0.05));
font: 400 14px/20px var(--tb-font, Roboto, sans-serif);
color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6));
.mat-icon {
width: 16px;
height: 16px;
font-size: 16px;
color: var(--tb-ink-38, rgba(0, 0, 0, 0.38));
}
.tb-home-load-retry {
margin-left: auto;
}
}
.tb-landed ::ng-deep > :not(.tb-home-card-header) {
animation: tb-home-load-land var(--motion-enter, 240ms) var(--ease-standard, cubic-bezier(0.2, 0, 0, 1)) both;
}
@keyframes tb-home-load-land {
from {
opacity: 0;
}
}
.tb-refreshing ::ng-deep > :not(.tb-home-card-header) {
pointer-events: none;
animation: tb-home-load-dim var(--motion-base, 150ms) var(--ease-standard, cubic-bezier(0.2, 0, 0, 1)) 300ms both;
}
@keyframes tb-home-load-dim {
to {
opacity: 0.45;
}
}
@media (prefers-reduced-motion: reduce) {
.tb-landed ::ng-deep > :not(.tb-home-card-header) {
animation: none;
}
.tb-refreshing ::ng-deep > :not(.tb-home-card-header) {
animation: none;
opacity: 0.45;
}
}
:host ::ng-deep tb-home-list-footer + .tb-home-load-stale {
padding-top: 0;
border-top: none;
}

165
ui-ngx/src/app/modules/home/pages/home-page/components/home-card.component.ts

@ -1,6 +1,20 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { ChangeDetectionStrategy, Component, inject, input } from '@angular/core';
import {
afterNextRender,
ChangeDetectionStrategy,
Component,
computed,
DestroyRef,
effect,
ElementRef,
inject,
input,
output,
signal,
untracked,
viewChild
} from '@angular/core';
import { Store } from '@ngrx/store';
import { ToastNotificationService } from '@core/services/toast-notification.service';
import { TranslateService } from '@ngx-translate/core';
@ -8,12 +22,20 @@ import { AppState } from '@core/core.state';
import { ActionPreferencesUpdateHomeCards } from '@core/auth/auth.actions';
import { homeToast } from '@home/pages/home-page/home-list.models';
import { HomeCardDefinition } from '@home/pages/home-page/home-cards.models';
import { HomeSkeletonShape } from '@home/pages/home-page/components/home-skeleton.component';
import { HomeLoadService } from '@home/pages/home-page/home-load.service';
import { aiClockText } from '@home/components/ai/ai-text';
const READ_TIMEOUT_MS = 20_000;
const SHIMMER_AFTER_MS = 400;
@Component({
selector: 'tb-home-card',
template: `
<section class="tb-home-card" [class.hideable]="hideable()" [attr.data-home-card]="card().id" [style.min-height.px]="card().height"
[attr.aria-label]="card().name | translate">
<section #section class="tb-home-card" [class.hideable]="hideable()" [attr.data-home-card]="card().id"
[style.min-height.px]="minHeight()" [style.height.px]="keptHeight()" [style.box-sizing]="keptHeight() ? 'border-box' : null"
[class.tb-landed]="landed()" [class.tb-refreshing]="refreshing()"
[attr.aria-busy]="showSkeleton() || refreshing() ? 'true' : null" [attr.aria-label]="card().name | translate">
<div class="tb-home-card-header" [class.expanded]="expanded()">
<div class="tb-home-card-title-group">
@if (card().link) {
@ -46,7 +68,25 @@ import { HomeCardDefinition } from '@home/pages/home-page/home-cards.models';
<ng-content select="[homeCardActions]"></ng-content>
</div>
</div>
@if (showSkeleton()) {
<tb-home-skeleton [shape]="skeleton()" [delay]="skeletonDelay()"></tb-home-skeleton>
} @else if (showFailed()) {
<div class="tb-home-load-failed" role="status">
<span class="tb-home-load-failed-glyph" aria-hidden="true"><mat-icon>cloud_off</mat-icon></span>
<div class="tb-home-load-failed-text">
<span>{{ 'home.load.failed' | translate: {name: (card().name | translate)} }}</span>
<button type="button" class="tb-home-load-retry" (click)="onRetry()">{{ 'home.load.retry' | translate }}</button>
</div>
</div>
}
<ng-content></ng-content>
@if (showStale()) {
<div class="tb-home-load-stale" role="status">
<mat-icon aria-hidden="true">cloud_off</mat-icon>
<span>{{ staleText() }}</span>
<button type="button" class="tb-home-load-retry" (click)="onRetry()">{{ 'home.load.retry' | translate }}</button>
</div>
}
</section>
`,
styleUrls: ['./home-card.component.scss'],
@ -65,9 +105,128 @@ export class HomeCardComponent {
countText = input<string | null>(null);
skeleton = input<HomeSkeletonShape | null>(null);
reading = input(false);
failed = input(false);
hasData = input(true);
readAt = input<number | null>(null);
refreshing = input(false);
keepHeight = input(true);
footText = input<string | null>(null);
retry = output<void>();
private store = inject(Store<AppState>);
private translate = inject(TranslateService);
private toast = inject(ToastNotificationService);
private load = inject(HomeLoadService);
private section = viewChild<ElementRef<HTMLElement>>('section');
private readonly timedOut = signal(false);
private readonly readStart = signal(0);
private readonly width = signal(0);
private readonly skeletonShown = signal(false);
readonly landed = signal(false);
private readonly bad = computed(() => this.failed() || this.timedOut());
readonly showSkeleton = computed(() => !!this.skeleton() && !this.hasData() && !this.bad());
readonly showFailed = computed(() => !this.hasData() && this.bad());
readonly showStale = computed(() => this.hasData() && this.bad() && (!!this.readAt() || !!this.footText()));
readonly skeletonDelay = computed(() => Math.max(0, SHIMMER_AFTER_MS - (Date.now() - this.readStart())));
readonly keptHeight = computed(() => this.showSkeleton() && this.width() ? this.load.height(this.card().id, this.width()) : null);
readonly minHeight = computed(() => this.keptHeight() ? null : this.card().height ?? null);
readonly staleText = computed(() => {
const at = this.readAt();
if (this.footText()) {
return this.footText();
}
if (!at) {
return '';
}
const lang = this.translate.currentLang;
const time = aiClockText(at, lang);
const date = new Date(at);
if (date.toDateString() === new Date().toDateString()) {
return this.translate.instant('home.load.stale-today', {time});
}
const day = date.toLocaleDateString(lang?.replace('_', '-'), {day: 'numeric', month: 'short'});
return this.translate.instant('home.load.stale-date', {date: day, time});
});
private timer: ReturnType<typeof setTimeout> | null = null;
constructor() {
const destroyRef = inject(DestroyRef);
effect(() => {
const reading = this.reading();
untracked(() => this.watchRead(reading));
});
effect(() => {
const skeleton = this.showSkeleton();
const hasData = this.hasData();
untracked(() => {
if (skeleton) {
this.skeletonShown.set(true);
this.landed.set(false);
} else if (hasData && this.skeletonShown()) {
this.skeletonShown.set(false);
this.landed.set(true);
}
});
});
let observer: ResizeObserver | null = null;
afterNextRender(() => {
const element = this.section()?.nativeElement;
if (!element) {
return;
}
this.width.set(element.offsetWidth);
observer = new ResizeObserver(() => {
if (element.offsetWidth !== this.width()) {
this.width.set(element.offsetWidth);
}
if (this.skeleton() && this.keepHeight() && !this.expanded() && this.hasData() && !this.reading() && !this.bad() && !this.refreshing()) {
this.load.keepHeight(this.card().id, element.offsetWidth, element.offsetHeight);
}
});
observer.observe(element);
});
destroyRef.onDestroy(() => {
this.watchRead(false);
observer?.disconnect();
});
}
onRetry(): void {
this.retry.emit();
this.watchRead(true);
}
private watchRead(reading: boolean): void {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this.timedOut.set(false);
if (reading) {
this.readStart.set(Date.now());
this.timer = setTimeout(() => this.timedOut.set(true), READ_TIMEOUT_MS);
}
}
hide(): void {
const id = this.card().id;

170
ui-ngx/src/app/modules/home/pages/home-page/components/home-skeleton.component.scss

@ -0,0 +1,170 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
:host {
--sk-fill: rgba(0, 0, 0, 0.06);
box-sizing: border-box;
position: relative;
display: flex;
flex: 1 1 auto;
flex-direction: column;
gap: 12px;
min-height: 0;
overflow: hidden;
&::after {
content: '';
position: absolute;
inset: 0 auto 0 0;
width: 300%;
pointer-events: none;
background: linear-gradient(90deg, transparent 33.3%, rgba(255, 255, 255, 0.8) 50%, transparent 66.7%);
transform: translateX(-66.667%);
animation: tb-home-shimmer var(--loop-shimmer, 2.4s) linear infinite;
animation-delay: var(--sk-delay, 400ms);
}
}
@keyframes tb-home-shimmer {
from {
transform: translateX(-66.667%);
}
to {
transform: none;
}
}
.tb-sk-bar, .tb-sk-dot, .tb-sk-block, .tb-sk-tile {
display: block;
flex: none;
background: var(--sk-fill);
}
.tb-sk-bar {
max-width: 100%;
height: 10px;
border-radius: 5px;
}
.tb-sk-dot {
border-radius: 50%;
}
.tb-sk-block {
max-width: 100%;
border-radius: 8px;
}
.tb-sk-tiles {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.tb-sk-tile {
width: 104px;
height: 60px;
border-radius: 8px;
}
.tb-sk-rows {
display: flex;
flex: 1 1 auto;
flex-direction: column;
min-height: 0;
}
.tb-sk-row {
display: flex;
flex: 1 1 40px;
align-items: center;
gap: 16px;
min-height: 30px;
max-height: 56px;
border-bottom: 1px solid var(--tb-line-soft, rgba(0, 0, 0, 0.05));
&:last-child {
border-bottom: none;
}
}
.tb-sk-row > .end, .tb-sk-foot > .end {
margin-left: auto;
}
.tb-sk-rows > .tb-sk-head {
flex: none;
min-height: 32px;
.tb-sk-bar {
height: 8px;
}
}
.tb-sk-rows.tall .tb-sk-row {
flex-basis: 56px;
min-height: 44px;
max-height: 80px;
}
.tb-sk-rows.plain .tb-sk-row {
flex-basis: 36px;
min-height: 28px;
max-height: 48px;
border-bottom: none;
}
.tb-sk-foot {
display: flex;
align-items: center;
min-height: 36px;
margin-top: auto;
padding-top: 8px;
border-top: 1px solid var(--tb-line-soft, rgba(0, 0, 0, 0.05));
}
.tb-sk-stack {
display: flex;
flex: 1;
flex-direction: column;
gap: 8px;
min-width: 0;
}
.tb-sk-kicker {
display: flex;
align-items: center;
min-height: 20px;
}
.tb-sk-chart {
display: flex;
flex: 1 1 auto;
flex-direction: column;
gap: 8px;
min-height: 0;
}
.tb-sk-chart-plot {
display: flex;
flex: 1 1 110px;
flex-direction: column;
justify-content: space-between;
min-height: 60px;
i {
display: block;
height: 1px;
background: var(--sk-fill);
}
}
.tb-sk-chart-x {
display: flex;
justify-content: space-between;
}
@media (prefers-reduced-motion: reduce) {
:host::after {
display: none;
}
}

208
ui-ngx/src/app/modules/home/pages/home-page/components/home-skeleton.component.ts

@ -0,0 +1,208 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { ChangeDetectionStrategy, Component, computed, input } from '@angular/core';
export type HomeSkeletonShape = 'alarms' | 'devices' | 'notifications' | 'activity' | 'dashboards' | 'links' | 'usage'
| 'system' | 'system-cluster' | 'install' | 'license' | 'get-started-sys-admin' | 'qr';
type Width = number | string;
type Part =
{kind: 'bar'; width: Width; end?: boolean}
| {kind: 'dot'; size: number; end?: boolean}
| {kind: 'block'; width: Width; height: Width}
| {kind: 'stack'; parts: Part[]};
type Section =
{kind: 'tiles'; count: number}
| {kind: 'rows'; rows: Part[][]; head?: Part[]; look?: 'tall' | 'plain'}
| {kind: 'chart'}
| {kind: 'foot'}
| {kind: 'kicker'; width: number}
| {kind: 'part'; part: Part};
const bar = (width: Width, end = false): Part => ({kind: 'bar', width, end});
const dot = (size: number, end = false): Part => ({kind: 'dot', size, end});
const block = (width: Width, height: Width): Part => ({kind: 'block', width, height});
const stack = (...parts: Part[]): Part => ({kind: 'stack', parts});
const rows = (widths: string[], cells: (width: string, index: number) => Part[], head?: Part[], look?: 'tall' | 'plain'): Section =>
({kind: 'rows', rows: widths.map((width, index) => cells(width, index)), head, look});
const SHAPES: Record<HomeSkeletonShape, Section[]> = {
alarms: [
{kind: 'tiles', count: 2},
rows(['30%', '24%', '34%', '26%', '28%'], width => [dot(16), bar(width), bar('16%'), bar(36, true), dot(20)],
[bar(56), bar('12%'), bar('12%'), bar(48, true)]),
{kind: 'foot'}
],
devices: [
{kind: 'tiles', count: 2},
rows(['34%', '28%', '38%', '30%', '32%'], width => [bar(width), bar('20%'), dot(10), bar(40, true)],
[bar(40), bar('14%'), bar(72, true)]),
{kind: 'foot'}
],
notifications: [
rows(['72%', '60%', '80%', '56%', '66%'], (width, index) =>
[dot(32), stack(bar(width), bar(['44%', '36%', '52%', '40%', '30%'][index])), bar(28, true)], undefined, 'tall'),
{kind: 'foot'}
],
activity: [
{kind: 'chart'}
],
dashboards: [
rows(['46%', '38%', '52%', '34%', '42%'], width => [dot(16), bar(width), bar(48, true)], [bar(40), bar(72, true)]),
{kind: 'foot'}
],
links: [
rows(['48%', '60%', '40%'], width => [block(20, 20), bar(width)], undefined, 'plain')
],
usage: [
{kind: 'kicker', width: 64},
rows(['34%', '28%', '24%', '38%', '30%'], width => [bar(width), bar(48), bar('28%', true)], undefined, 'plain')
],
system: [
{kind: 'tiles', count: 3},
{kind: 'chart'}
],
'system-cluster': [
rows(['30%', '26%', '34%', '28%', '32%', '24%'], width => [bar(width), bar('18%'), bar(36, true), bar(36), bar(36)],
[bar(64), bar('12%'), bar(28, true), bar(28), bar(28)])
],
install: [
{kind: 'tiles', count: 6},
{kind: 'kicker', width: 80},
rows(['40%', '52%', '34%'], width => [dot(16), bar(width)], undefined, 'plain')
],
license: [
{kind: 'part', part: block('100%', 72)},
rows(['30%', '24%', '36%', '28%', '20%'], width => [bar(width), bar(56), bar('30%', true)], undefined, 'plain')
],
qr: [
{kind: 'part', part: block('100%', '100%')}
],
'get-started-sys-admin': [
{kind: 'part', part: block('100%', 6)},
{kind: 'kicker', width: 160},
rows(['50%', '38%', '44%', '56%', '40%', '48%', '36%'], width => [dot(22), bar(width)], undefined, 'plain')
]
};
@Component({
selector: 'tb-home-skeleton',
template: `
<ng-template #partTpl let-part>
@switch (part.kind) {
@case ('bar') {
<i class="tb-sk-bar" [class.end]="part.end" [style.width]="size(part.width)"></i>
}
@case ('dot') {
<i class="tb-sk-dot" [class.end]="part.end" [style.width.px]="part.size" [style.height.px]="part.size"></i>
}
@case ('block') {
<i class="tb-sk-block" [style.width]="size(part.width)" [style.height]="size(part.height)"></i>
}
@case ('stack') {
<span class="tb-sk-stack">
@for (child of part.parts; track $index) {
<ng-container *ngTemplateOutlet="partTpl; context: {$implicit: child}"></ng-container>
}
</span>
}
}
</ng-template>
@for (section of sections(); track $index) {
@switch (section.kind) {
@case ('tiles') {
<span class="tb-sk-tiles">
@for (tile of tiles(section); track $index) {
<i class="tb-sk-tile"></i>
}
</span>
}
@case ('rows') {
<span class="tb-sk-rows" [class.tall]="look(section) === 'tall'" [class.plain]="look(section) === 'plain'">
@if (head(section); as head) {
<span class="tb-sk-row tb-sk-head">
@for (part of head; track $index) {
<ng-container *ngTemplateOutlet="partTpl; context: {$implicit: part}"></ng-container>
}
</span>
}
@for (row of rowsOf(section); track $index) {
<span class="tb-sk-row">
@for (part of row; track $index) {
<ng-container *ngTemplateOutlet="partTpl; context: {$implicit: part}"></ng-container>
}
</span>
}
</span>
}
@case ('chart') {
<span class="tb-sk-chart">
<span class="tb-sk-chart-plot"><i></i><i></i><i></i><i></i></span>
<span class="tb-sk-chart-x">
@for (label of chartLabels; track $index) {
<i class="tb-sk-bar" style="width: 36px"></i>
}
</span>
</span>
}
@case ('foot') {
<span class="tb-sk-foot"><i class="tb-sk-bar" style="width: 84px"></i><i class="tb-sk-bar end" style="width: 56px"></i></span>
}
@case ('kicker') {
<span class="tb-sk-kicker"><i class="tb-sk-bar" [style.width.px]="kickerWidth(section)"></i></span>
}
@case ('part') {
<ng-container *ngTemplateOutlet="partTpl; context: {$implicit: partOf(section)}"></ng-container>
}
}
}
`,
styleUrls: ['./home-skeleton.component.scss'],
host: {
'class': 'tb-sk',
'aria-hidden': 'true',
'[style.--sk-delay.ms]': 'delay()'
},
standalone: false,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class HomeSkeletonComponent {
shape = input.required<HomeSkeletonShape>();
delay = input(400);
readonly sections = computed(() => SHAPES[this.shape()]);
readonly chartLabels = [0, 1, 2, 3, 4];
size(value: Width): string {
return typeof value === 'number' ? `${value}px` : value;
}
tiles(section: Section): number[] {
return section.kind === 'tiles' ? Array.from({length: section.count}, (_, index) => index) : [];
}
rowsOf(section: Section): Part[][] {
return section.kind === 'rows' ? section.rows : [];
}
head(section: Section): Part[] | null {
return section.kind === 'rows' ? section.head ?? null : null;
}
look(section: Section): string | null {
return section.kind === 'rows' ? section.look ?? null : null;
}
kickerWidth(section: Section): number {
return section.kind === 'kicker' ? section.width : 0;
}
partOf(section: Section): Part | null {
return section.kind === 'part' ? section.part : null;
}
}

66
ui-ngx/src/app/modules/home/pages/home-page/components/install-items-home.component.html

@ -4,44 +4,46 @@
SPDX-License-Identifier: BUSL-1.1
-->
<tb-home-card [card]="card">
<tb-home-card [card]="card" skeleton="install" [hasData]="ready()" [reading]="!ready()" (retry)="retry()">
<ng-container homeCardActions>
<a mat-button color="primary" class="tb-install-add" routerLink="/tenants" [queryParams]="{action: 'add'}">
<mat-icon>add</mat-icon>{{ 'home.install.add-tenant' | translate }}
</a>
</ng-container>
<div class="tb-install-counts">
@for (item of counts; track item.entityType) {
@let count = item.count();
@if (item.link && count) {
<a class="tb-home-tile" [routerLink]="item.link">
<span class="tb-home-tile-label">{{ item.label | translate }}</span>
<span class="tb-home-tile-count">{{ count | shortNumber }}</span>
</a>
} @else {
<div class="tb-home-tile static" [class.zero]="count === 0">
<span class="tb-home-tile-label">{{ item.label | translate }}</span>
<span class="tb-home-tile-count">{{ count === null ? '–' : (count | shortNumber) }}</span>
</div>
}
}
</div>
@if (withFeatures()) {
<div class="tb-install-head">
<span>{{ 'home.install.features' | translate }}</span>
@if (loaded()) {
<span class="tb-install-head-count">{{ 'home.install.features-count' | translate: {on: configured(), total: features().length} }}</span>
}
</div>
<div class="tb-install-features" role="list">
@for (feature of features(); track feature.key) {
<a class="tb-install-feature" role="listitem" [class.on]="feature.on" [class.pending]="feature.on === null" [routerLink]="feature.link"
[matTooltip]="(feature.on === null ? 'home.install.checking' : feature.on ? 'widgets.configured-features.feature-configured' : 'widgets.configured-features.feature-not-configured') | translate">
<mat-icon class="tb-install-feature-icon">{{ feature.on ? 'check_circle' : 'radio_button_unchecked' }}</mat-icon>
<span class="tb-install-feature-text">{{ feature.label | translate }}</span>
<span class="tb-ai-sr-only">{{ (feature.on === null ? 'home.install.checking' : feature.on ? 'home.install.configured' : 'home.install.not-configured') | translate }}</span>
</a>
@if (ready()) {
<div class="tb-install-counts">
@for (item of counts; track item.entityType) {
@let count = item.count();
@if (item.link && count) {
<a class="tb-home-tile" [routerLink]="item.link">
<span class="tb-home-tile-label">{{ item.label | translate }}</span>
<span class="tb-home-tile-count">{{ count | shortNumber }}</span>
</a>
} @else {
<div class="tb-home-tile static" [class.zero]="count === 0">
<span class="tb-home-tile-label">{{ item.label | translate }}</span>
<span class="tb-home-tile-count">{{ count === null ? '–' : (count | shortNumber) }}</span>
</div>
}
}
</div>
@if (withFeatures()) {
<div class="tb-install-head">
<span>{{ 'home.install.features' | translate }}</span>
@if (loaded()) {
<span class="tb-install-head-count">{{ 'home.install.features-count' | translate: {on: configured(), total: features().length} }}</span>
}
</div>
<div class="tb-install-features" role="list">
@for (feature of features(); track feature.key) {
<a class="tb-install-feature" role="listitem" [class.on]="feature.on" [class.pending]="feature.on === null" [routerLink]="feature.link"
[matTooltip]="(feature.on === null ? 'home.install.checking' : feature.on ? 'widgets.configured-features.feature-configured' : 'widgets.configured-features.feature-not-configured') | translate">
<mat-icon class="tb-install-feature-icon">{{ feature.on ? 'check_circle' : 'radio_button_unchecked' }}</mat-icon>
<span class="tb-install-feature-text">{{ feature.label | translate }}</span>
<span class="tb-ai-sr-only">{{ (feature.on === null ? 'home.install.checking' : feature.on ? 'home.install.configured' : 'home.install.not-configured') | translate }}</span>
</a>
}
</div>
}
}
</tb-home-card>

25
ui-ngx/src/app/modules/home/pages/home-page/components/install-items-home.component.ts

@ -7,6 +7,7 @@ import { HomeCardId } from '@shared/models/user-settings.models';
import { HOME_CARDS } from '@home/pages/home-page/home-cards.models';
import { HomeCountService } from '@home/pages/home-page/home-count.service';
import { SysAdminHomeService } from '@home/pages/home-page/sys-admin-home.service';
import { AdminService } from '@core/http/admin.service';
interface InstallCount {
label: string;
@ -63,10 +64,28 @@ export class InstallItemsHomeComponent {
readonly configured = computed(() => this.features().filter(feature => feature.on).length);
readonly ready = computed(() => this.counts.every(item => item.count() !== null) && (!this.withFeatures() || this.loaded()));
private readonly adminService = inject(AdminService);
private readonly homeCounts = inject(HomeCountService);
private readonly destroyRef = inject(DestroyRef);
constructor() {
inject(SysAdminHomeService).featuresInfo$.subscribe(info => this.featuresInfo.set(info));
const homeCounts = inject(HomeCountService);
const destroyRef = inject(DestroyRef);
this.counts.forEach(item => homeCounts.watchEntityCount(item.entityType, count => item.count.set(count), destroyRef));
this.watchCounts();
}
retry(): void {
if (!this.loaded()) {
this.adminService.getFeaturesInfo({ignoreErrors: true, ignoreLoading: true}).subscribe({
next: info => this.featuresInfo.set(info),
error: () => {}
});
}
this.counts.filter(item => item.count() === null).forEach(item => this.homeCounts.reread(item.entityType));
}
private watchCounts(): void {
this.counts.forEach(item => this.homeCounts.watchEntityCount(item.entityType, count => item.count.set(count), this.destroyRef));
}
}

9
ui-ngx/src/app/modules/home/pages/home-page/components/iot-hub-home.component.html

@ -4,7 +4,8 @@
SPDX-License-Identifier: BUSL-1.1
-->
<tb-home-card [card]="card" [hideable]="true" [expanded]="searching()">
<tb-home-card [card]="card" [hideable]="true" [expanded]="searching()" [hasData]="!failed() || loaded()" [reading]="reading()"
[failed]="failed()" [readAt]="readAt()" (retry)="read()">
<ng-container homeCardActions>
@if (searching()) {
<label class="tb-iot-hub-search" [class.has-text]="!!query().trim()" (focusout)="onSearchFocusOut($event)">
@ -29,9 +30,7 @@
</button>
}
</ng-container>
@if (failed()) {
<p class="tb-iot-hub-unavailable">{{ 'home.iot-hub.unavailable' | translate }}</p>
} @else {
@if (!failed() || loaded()) {
<div class="tb-iot-hub-row">
<a class="tb-iot-hub-row-title" routerLink="/iot-hub/solution-templates">{{ 'home.iot-hub.templates' | translate }}</a>
<tb-home-hscroll [label]="'home.iot-hub.templates' | translate">
@ -115,7 +114,7 @@
<nav class="tb-iot-hub-kinds" [attr.aria-label]="'home.iot-hub.also' | translate">
@for (kind of kinds; track kind.type) {
<a class="tb-iot-hub-kind" [routerLink]="['/iot-hub', kind.route]">
<mat-icon aria-hidden="true">{{ kind.icon }}</mat-icon>
<tb-icon aria-hidden="true">{{ kind.icon }}</tb-icon>
<span>{{ kind.name | translate }}</span>
</a>
}

6
ui-ngx/src/app/modules/home/pages/home-page/components/iot-hub-home.component.scss

@ -312,12 +312,6 @@
}
}
.tb-iot-hub-unavailable {
margin: 0;
font: 400 14px/20px var(--tb-font, Roboto, sans-serif);
color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6));
}
.tb-iot-hub-find.mat-mdc-icon-button.mat-mdc-button-base {
--mdc-icon-button-state-layer-size: 32px;
--mat-icon-button-state-layer-size: 32px;

27
ui-ngx/src/app/modules/home/pages/home-page/components/iot-hub-home.component.ts

@ -7,7 +7,7 @@ import { HomeCardId } from '@shared/models/user-settings.models';
import { HOME_CARDS } from '@home/pages/home-page/home-cards.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service';
import { ItemType } from '@shared/models/iot-hub/iot-hub-item.models';
import { getItemTypeIcon, ItemType } from '@shared/models/iot-hub/iot-hub-item.models';
import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models';
import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { Direction, SortOrder } from '@shared/models/page/sort-order';
@ -62,10 +62,10 @@ export interface IotHubKind {
}
const KINDS: IotHubKind[] = [
{type: ItemType.WIDGET, name: 'home.iot-hub.widgets', icon: 'widgets', route: 'widgets'},
{type: ItemType.CALCULATED_FIELD, name: 'home.iot-hub.calculated-fields', icon: 'functions', route: 'calculated-fields'},
{type: ItemType.ALARM_RULE, name: 'home.iot-hub.alarm-rules', icon: 'notification_important', route: 'alarm-rules'},
{type: ItemType.RULE_CHAIN, name: 'home.iot-hub.rule-chains', icon: 'account_tree', route: 'rule-chains'}
{type: ItemType.WIDGET, name: 'home.iot-hub.widgets', icon: getItemTypeIcon(ItemType.WIDGET), route: 'widgets'},
{type: ItemType.CALCULATED_FIELD, name: 'home.iot-hub.calculated-fields', icon: getItemTypeIcon(ItemType.CALCULATED_FIELD), route: 'calculated-fields'},
{type: ItemType.ALARM_RULE, name: 'home.iot-hub.alarm-rules', icon: getItemTypeIcon(ItemType.ALARM_RULE), route: 'alarm-rules'},
{type: ItemType.RULE_CHAIN, name: 'home.iot-hub.rule-chains', icon: getItemTypeIcon(ItemType.RULE_CHAIN), route: 'rule-chains'}
];
interface HubTile {
@ -95,6 +95,8 @@ export class IoTHubHomeComponent {
readonly deviceTotal = signal(0);
readonly loaded = signal(false);
readonly failed = signal(false);
readonly reading = signal(false);
readonly readAt = signal<number | null>(null);
readonly searching = signal(false);
readonly query = signal('');
@ -109,7 +111,7 @@ export class IoTHubHomeComponent {
private installedDeviceCounts: Record<string, number> = {};
constructor() {
this.load();
this.read();
}
isInstalled(item: MpItemVersionView): boolean {
@ -174,11 +176,14 @@ export class IoTHubHomeComponent {
}
}
private load(): void {
read(): void {
const cached = readSnapshot();
if (cached) {
this.apply(cached);
this.readAt.set(cached.at);
}
this.reading.set(true);
this.failed.set(false);
const config = {ignoreLoading: true, ignoreErrors: true};
const sortOrder: SortOrder = {property: 'totalInstallCount', direction: Direction.DESC};
const query = (type: ItemType) => new MpItemVersionQuery(new PageLink(SHOWN, 0, null, sortOrder), {type});
@ -190,12 +195,12 @@ export class IoTHubHomeComponent {
const snapshot = {at: Date.now(), templates: templates.data, devices: devices.data, deviceTotal: devices.totalElements};
writeSnapshot(snapshot);
this.apply(snapshot);
this.readAt.set(snapshot.at);
this.reading.set(false);
},
error: () => {
if (!cached) {
this.failed.set(true);
this.loaded.set(true);
}
this.failed.set(true);
this.reading.set(false);
}
});
this.loadInstalled();

3
ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.html

@ -4,7 +4,8 @@
SPDX-License-Identifier: BUSL-1.1
-->
<tb-home-card [card]="cardDefinition()">
<tb-home-card [card]="card" skeleton="license" [hasData]="!!info()" [reading]="state.reading()" [failed]="state.failed()" [readAt]="state.readAt()"
(retry)="state.read()">
<ng-container homeCardActions>
@if (managed() && updatedAgo()) {
<span class="tb-license-updated">

37
ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.ts

@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { ChangeDetectionStrategy, Component, computed, DestroyRef, ElementRef, inject, signal } from '@angular/core';
import { ChangeDetectionStrategy, Component, computed, DestroyRef, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Store } from '@ngrx/store';
import { interval } from 'rxjs';
@ -19,7 +19,7 @@ import {
usageItemTypeTranslationMap
} from '@shared/models/subscription.models';
import { HOME_CARDS } from '@home/pages/home-page/home-cards.models';
import { readStored, writeStored } from '@core/local-storage/stored';
import { HomeLoadService } from '@home/pages/home-page/home-load.service';
import {
LicenseActionsService,
licenseLimitCritical,
@ -27,13 +27,6 @@ import {
licenseMeterWidth
} from '@home/components/license/license-actions.service';
const LOADING_HEIGHT = 398;
const HEIGHT_KEY = 'tb-home-license-height';
const storedHeight = (): number => {
return Number(readStored(HEIGHT_KEY)) || LOADING_HEIGHT;
};
const AGO_REFRESH_MS = 30_000;
const PLANS_URL = 'https://thingsboard.io/pricing/?product=thingsboard-pe';
@ -112,10 +105,12 @@ export class LicenseHomeComponent {
readonly refreshing = signal(false);
private readonly now = signal(Date.now());
readonly cardDefinition = computed(() => {
const card = HOME_CARDS[HomeCardId.LICENSE];
return this.info() ? card : {...card, height: storedHeight()};
});
readonly card = HOME_CARDS[HomeCardId.LICENSE];
private readonly load = inject(HomeLoadService);
readonly state = this.load.reader<SubscriptionInfo>(this.card.id,
() => this.adminService.getSubscriptionInfo({ignoreLoading: true, ignoreErrors: true}),
info => this.info.set(info));
readonly kind = computed(() => {
const info = this.info();
@ -218,13 +213,8 @@ export class LicenseHomeComponent {
constructor() {
const destroyRef = inject(DestroyRef);
this.adminService.getSubscriptionInfo({ignoreLoading: true}).pipe(takeUntilDestroyed(destroyRef))
.subscribe(info => this.info.set(info));
this.state.start();
interval(AGO_REFRESH_MS).pipe(takeUntilDestroyed(destroyRef)).subscribe(() => this.now.set(Date.now()));
const host = inject<ElementRef<HTMLElement>>(ElementRef);
const observer = new ResizeObserver(() => this.rememberHeight(host.nativeElement));
observer.observe(host.nativeElement);
destroyRef.onDestroy(() => observer.disconnect());
}
refresh(): void {
@ -232,6 +222,7 @@ export class LicenseHomeComponent {
this.adminService.refreshLicense({ignoreLoading: true}).subscribe({
next: info => {
this.info.set(info);
this.state.keep(info);
this.refreshing.set(false);
},
error: () => this.refreshing.set(false)
@ -266,14 +257,6 @@ export class LicenseHomeComponent {
window.open(PLANS_URL, '_blank');
}
private rememberHeight(element: HTMLElement): void {
const height = Math.round(element.getBoundingClientRect().height);
if (!this.info() || !height) {
return;
}
writeStored(HEIGHT_KEY, String(height));
}
private limit(info: SubscriptionInfo, itemType: UsageItemType, used: number, max: number, addEnabled: boolean,
label = usageItemTypeTranslationMap.get(itemType)): LicenseLimit | null {
if (max == null || max < 0) {

17
ui-ngx/src/app/modules/home/pages/home-page/components/mobile-app-home.component.html

@ -4,12 +4,23 @@
SPDX-License-Identifier: BUSL-1.1
-->
<tb-home-card [card]="card" [hideable]="true">
<tb-home-card [card]="card" [hideable]="true" [hasData]="!!settings()" [reading]="state.reading()" [failed]="state.failed()"
[readAt]="state.readAt()" (retry)="read()">
@if (settings()) {
<div class="tb-app-widget" [class.badges-left]="badgesLeft()">
<div class="tb-app-widget-row">
<div class="tb-app-qr" role="img" [attr.aria-label]="'home.mobile-app.qr' | translate"
[innerHTML]="qrCode() | safe: 'html'" (click)="openDeepLink()"></div>
@if (qrCode()) {
<div class="tb-app-qr" role="img" [attr.aria-label]="'home.mobile-app.qr' | translate"
[innerHTML]="qrCode() | safe: 'html'" (click)="openDeepLink()"></div>
} @else if (qrFailed()) {
<div class="tb-app-qr failed" role="status">
<mat-icon aria-hidden="true">cloud_off</mat-icon>
<span>{{ 'home.load.qr-failed' | translate }}</span>
<button type="button" class="tb-home-load-retry" (click)="retryQr()">{{ 'home.load.retry' | translate }}</button>
</div>
} @else {
<tb-home-skeleton class="tb-app-qr-skeleton" shape="qr"></tb-home-skeleton>
}
@if (badges()) {
<div class="tb-store-badges">
@if (settings().iosEnabled) {

30
ui-ngx/src/app/modules/home/pages/home-page/components/mobile-app-home.component.scss

@ -1,5 +1,7 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
@use './home-load';
:host {
display: block;
min-width: 0;
@ -38,6 +40,34 @@
width: 100%;
height: 100%;
}
&.failed {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 4px;
padding: 8px;
border-radius: 8px;
background: var(--tb-line-soft, rgba(0, 0, 0, 0.05));
text-align: center;
font: 400 12px/16px var(--tb-font, Roboto, sans-serif);
color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6));
.mat-icon {
width: 20px;
height: 20px;
font-size: 20px;
color: var(--tb-ink-38, rgba(0, 0, 0, 0.38));
}
}
}
.tb-app-qr-skeleton {
flex: none;
width: 96px;
height: 96px;
}
.tb-store-badges {

29
ui-ngx/src/app/modules/home/pages/home-page/components/mobile-app-home.component.ts

@ -8,6 +8,7 @@ import { BadgePosition, QrCodeSettings } from '@shared/models/mobile-app.models'
import { MINUTE } from '@shared/models/time/time.models';
import { HomeCardId } from '@shared/models/user-settings.models';
import { HOME_CARDS } from '@home/pages/home-page/home-cards.models';
import { HomeLoadService } from '@home/pages/home-page/home-load.service';
@Component({
selector: 'tb-mobile-app-home',
@ -27,6 +28,12 @@ export class MobileAppHomeComponent {
readonly qrCode = signal('');
readonly qrFailed = signal(false);
readonly state = inject(HomeLoadService).reader<QrCodeSettings>(this.card.id,
() => this.mobileAppService.getMergedMobileAppSettings({ignoreLoading: true, ignoreErrors: true}),
settings => this.settings.set(settings));
readonly badges = computed(() => {
const settings = this.settings();
return !!settings?.qrCodeConfig?.badgeEnabled && (settings.iosEnabled || settings.androidEnabled);
@ -44,7 +51,7 @@ export class MobileAppHomeComponent {
private destroyed = false;
constructor() {
this.mobileAppService.getMergedMobileAppSettings().subscribe(settings => this.settings.set(settings));
this.state.start();
this.loadDeepLink();
inject(DestroyRef).onDestroy(() => {
this.destroyed = true;
@ -52,6 +59,17 @@ export class MobileAppHomeComponent {
});
}
read(): void {
this.state.read();
if (!this.qrCode()) {
this.loadDeepLink();
}
}
retryQr(): void {
this.loadDeepLink();
}
openDeepLink(): void {
if (this.deepLink && window.matchMedia('(pointer: coarse)').matches) {
window.open(this.deepLink, '_blank');
@ -60,7 +78,12 @@ export class MobileAppHomeComponent {
private loadDeepLink(): void {
clearTimeout(this.deepLinkTimer);
this.mobileAppService.getMobileAppDeepLink().subscribe(link => {
this.qrFailed.set(false);
this.mobileAppService.getMobileAppDeepLink({ignoreLoading: true, ignoreErrors: true}).subscribe({error: () => {
if (!this.destroyed && !this.qrCode()) {
this.qrFailed.set(true);
}
}, next: link => {
if (this.destroyed) {
return;
}
@ -74,6 +97,6 @@ export class MobileAppHomeComponent {
if (ttl > 0) {
this.deepLinkTimer = setTimeout(() => this.loadDeepLink(), ttl);
}
});
}});
}
}

5
ui-ngx/src/app/modules/home/pages/home-page/components/notifications-home.component.html

@ -4,9 +4,10 @@
SPDX-License-Identifier: BUSL-1.1
-->
<tb-home-card [card]="card" [count]="total()" [class.tb-mark-all-icon]="markAllIcon()">
<tb-home-card [card]="card" [count]="loaded() ? total() : null" [class.tb-mark-all-icon]="markAllIcon()" skeleton="notifications"
[hasData]="loaded()" [reading]="!loaded()" [keepHeight]="!expanded()" (retry)="refresh()">
<ng-container homeCardActions>
@if (rows().length) {
@if (loaded() && rows().length) {
<button mat-button color="primary" type="button" class="tb-notifications-mark-all"
[matTooltip]="markAllIcon() ? ('notification.mark-all-as-read' | translate) : ''" (click)="markAllAsRead()">
<mat-icon>done_all</mat-icon>

49
ui-ngx/src/app/modules/home/pages/home-page/components/notifications-home.component.ts

@ -71,6 +71,7 @@ export class NotificationsHomeComponent {
readonly expanded = signal(false);
readonly openId = signal<string | null>(null);
readonly markAllIcon = signal(false);
private markAllWidth = 0;
readonly loaded = computed(() => this.notifications() !== null);
@ -82,15 +83,11 @@ export class NotificationsHomeComponent {
return list.slice(0, homeListShown(this.listed(), this.expanded())).map(notification => this.toRow(notification, now));
});
private subscriber = NotificationSubscriber.createNotificationsSubscription(this.notificationWsService, this.zone, LIMIT);
private subscriber: NotificationSubscriber;
constructor() {
const destroyRef = inject(DestroyRef);
this.subscriber.notifications$.pipe(
filter((value): value is Notification[] => Array.isArray(value))
).subscribe(list => this.notifications.set([...list]));
this.subscriber.notificationCount$.subscribe(count => this.total.set(count));
this.subscriber.subscribe();
this.connect();
const tick = setInterval(() => this.now.set(Date.now()), MINUTE);
let observer: ResizeObserver | null = null;
afterNextRender(() => {
@ -162,18 +159,42 @@ export class NotificationsHomeComponent {
}
}
refresh(): void {
this.subscriber.unsubscribe();
this.connect();
}
private connect(): void {
this.subscriber = NotificationSubscriber.createNotificationsSubscription(this.notificationWsService, this.zone, LIMIT);
this.subscriber.notifications$.pipe(
filter((value): value is Notification[] => Array.isArray(value))
).subscribe(list => this.notifications.set([...list]));
this.subscriber.notificationCount$.subscribe(count => this.total.set(count));
this.subscriber.subscribe();
}
private measureHeader(): void {
const element: HTMLElement = this.host.nativeElement;
const title = element.querySelector('.tb-home-card-title-group');
const button = element.querySelector('.tb-notifications-mark-all');
if (!title || !button) {
const header = element.querySelector<HTMLElement>('.tb-home-card-header');
const title = element.querySelector<HTMLElement>('.tb-home-card-title-group');
const button = element.querySelector<HTMLElement>('.tb-notifications-mark-all');
if (!header || !title || !button) {
return;
}
this.zone.run(() => this.markAllIcon.set(false));
requestAnimationFrame(() => {
const wrapped = button.getBoundingClientRect().top >= title.getBoundingClientRect().bottom - 4;
this.zone.run(() => this.markAllIcon.set(wrapped));
});
if (!this.markAllIcon()) {
this.markAllWidth = button.getBoundingClientRect().width;
}
if (!this.markAllWidth) {
return;
}
const gap = parseFloat(getComputedStyle(header).columnGap) || 0;
const titleGap = parseFloat(getComputedStyle(title).columnGap) || 0;
const parts = Array.from(title.children) as HTMLElement[];
const titleWidth = parts.reduce((width, part) => width + part.scrollWidth, 0) + titleGap * Math.max(parts.length - 1, 0);
const icon = titleWidth + gap + this.markAllWidth > header.clientWidth;
if (icon !== this.markAllIcon()) {
this.zone.run(() => this.markAllIcon.set(icon));
}
}
private toRow(notification: Notification, now: number): NotificationHomeRow {

5
ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.html

@ -4,7 +4,8 @@
SPDX-License-Identifier: BUSL-1.1
-->
<tb-home-card [card]="card" [hideable]="true" [expanded]="editing()" [class.editing]="editing()">
<tb-home-card [card]="card" [hideable]="true" [expanded]="editing()" [class.editing]="editing()" skeleton="links"
[hasData]="loaded()" [reading]="state.reading()" [failed]="state.failed()" [readAt]="state.readAt()" (retry)="state.read()">
<ng-container homeCardActions>
@if (loaded()) {
@if (editing()) {
@ -12,7 +13,7 @@
{{ 'action.done' | translate }}
</button>
} @else {
<button mat-icon-button type="button" class="tb-quick-links-edit"
<button mat-icon-button type="button" class="tb-quick-links-edit" [disabled]="!state.fresh()"
[matTooltip]="'home.quick-links.edit' | translate" matTooltipPosition="above"
[attr.aria-label]="'home.quick-links.edit' | translate" (click)="toggleEdit()">
<mat-icon>edit</mat-icon>

10
ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.ts

@ -39,6 +39,7 @@ import {
quickWebLinkId
} from '@home/pages/home-page/quick-links.models';
import { homeToast } from '@home/pages/home-page/home-list.models';
import { HomeLoadService } from '@home/pages/home-page/home-load.service';
import {
QuickLinkDialogComponent,
QuickLinkDialogData
@ -79,6 +80,12 @@ export class QuickLinksHomeComponent {
readonly loaded = computed(() => this.settings() !== null);
readonly state = inject(HomeLoadService).reader<QuickLinks>(this.card.id,
() => this.userSettingsService.getQuickLinks({ignoreLoading: true, ignoreErrors: true}).pipe(
map(quickLinks => this.withDefaults(quickLinks))
),
settings => this.settings.set(settings));
readonly links = computed<QuickLinkView[]>(() => {
const settings = this.settings();
const pages = this.pages();
@ -102,7 +109,7 @@ export class QuickLinksHomeComponent {
readonly full = computed(() => this.links().length >= QUICK_LINKS_MAX);
constructor() {
this.userSettingsService.getQuickLinks().subscribe(quickLinks => this.settings.set(this.withDefaults(quickLinks)));
this.state.start();
effect(() => {
this.links();
this.editing();
@ -199,6 +206,7 @@ export class QuickLinksHomeComponent {
private save(quickLinks: QuickLinks): void {
this.settings.set(quickLinks);
this.state.keep(quickLinks);
this.userSettingsService.updateQuickLinks(quickLinks).subscribe();
}

2
ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.html

@ -4,7 +4,7 @@
SPDX-License-Identifier: BUSL-1.1
-->
<tb-home-card [card]="cardDefinition()">
<tb-home-card [card]="card" [skeleton]="skeleton" [hasData]="loaded()" [reading]="!loaded()" [keepHeight]="!expanded()" (retry)="retry()">
@if (loaded()) {
<span homeCardTitleExtra class="tb-system-period">{{ cluster() ? ('home.system.services' | translate: {count: services().length}) : ('home.system.last-hour' | translate) }}</span>
}

33
ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.ts

@ -6,11 +6,13 @@ import {
Component,
computed,
DestroyRef,
effect,
ElementRef,
inject,
NgZone,
Renderer2,
signal,
untracked,
viewChild
} from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@ -25,6 +27,8 @@ import { UpdateMessage } from '@shared/models/settings.models';
import { HomeCardId } from '@shared/models/user-settings.models';
import { ECharts, echartsModule, EChartsOption } from '@home/components/widget/lib/chart/echarts-widget.models';
import { HOME_CARDS } from '@home/pages/home-page/home-cards.models';
import { HomeLoadService } from '@home/pages/home-page/home-load.service';
import { HomeSkeletonShape } from '@home/pages/home-page/components/home-skeleton.component';
import { SysAdminHomeService } from '@home/pages/home-page/sys-admin-home.service';
import { homeChartHoverSymbol, homeChartTooltipHtml, homeChartTooltipOptions } from '@home/pages/home-page/home-chart.models';
@ -66,7 +70,6 @@ const METRICS: MetricConfig[] = [
const SERVICE_KEYS: Record<SystemMetric, 'cpuUsage' | 'memoryUsage' | 'discUsage'> = {cpu: 'cpuUsage', ram: 'memoryUsage', disk: 'discUsage'};
const LATEST_KEYS = ['clusterMode', 'clusterSystemData', 'cpuUsage', 'cpuCount', 'memoryUsage', 'totalMemory', 'discUsage', 'totalDiscSpace'];
const LABEL_STEP = 15 * MINUTE;
const LOADING_HEIGHT = 304;
const SERVICES_PREVIEW = 8;
const SERVICES_SLACK = 2;
const SERVICES_LIMIT = 20;
@ -113,10 +116,15 @@ export class SystemStatusHomeComponent {
readonly loaded = computed(() => this.latest() !== null);
readonly cardDefinition = computed(() => {
const card = HOME_CARDS[HomeCardId.SYSTEM_STATUS];
return this.loaded() ? card : {...card, height: LOADING_HEIGHT};
});
readonly card = HOME_CARDS[HomeCardId.SYSTEM_STATUS];
private readonly load = inject(HomeLoadService);
private readonly clusterKey = `${this.card.id}-cluster`;
readonly skeleton: HomeSkeletonShape = this.load.lastRead<boolean>(this.clusterKey) ? 'system-cluster' : 'system';
private subscriber: TelemetrySubscriber | null = null;
readonly services = computed<ClusterService[]>(() => {
const data = this.latest()?.clusterSystemData;
@ -219,19 +227,30 @@ export class SystemStatusHomeComponent {
constructor() {
this.sysAdminHome.update$.subscribe(update => this.update.set(update));
const subscriber = this.subscribe();
this.subscriber = this.subscribe();
effect(() => {
if (this.loaded()) {
const cluster = this.cluster();
untracked(() => this.load.keepRead(this.clusterKey, cluster));
}
});
const tick = setInterval(() => this.window.set({start: Date.now() - HOUR, end: Date.now()}), MINUTE);
const resizeObserver = new ResizeObserver(() => this.chart?.resize());
resizeObserver.observe(this.host.nativeElement);
afterRenderEffect(() => this.render());
inject(DestroyRef).onDestroy(() => {
subscriber.unsubscribe();
this.subscriber?.unsubscribe();
clearInterval(tick);
resizeObserver.disconnect();
this.chart?.dispose();
});
}
retry(): void {
this.subscriber?.unsubscribe();
this.subscriber = this.subscribe();
}
sortBy(key: ServiceSortKey): void {
const [current, direction] = this.sort();
if (current === key) {

42
ui-ngx/src/app/modules/home/pages/home-page/home-count.service.ts

@ -23,21 +23,12 @@ export class HomeCountService {
private counts = new Map<string, SharedCount>();
watchEntityCount(entityType: EntityType, onCount: (count: number) => void, destroyRef: DestroyRef, keyFilters?: KeyFilter[]): () => void {
const key = JSON.stringify([entityType, keyFilters ?? null]);
const key = this.key(entityType, keyFilters);
let shared = this.counts.get(key);
if (!shared) {
const cmd = new EntityCountCmd();
cmd.query = {entityFilter: {type: AliasFilterType.entityType, entityType}, keyFilters};
const subscriber = new TelemetrySubscriber(this.telemetryWsService, this.zone);
subscriber.subscriptionCommands.push(cmd);
const created: SharedCount = {subscriber, listeners: new Set()};
subscriber.entityCount$.subscribe(update => {
created.last = update.count ?? 0;
created.listeners.forEach(listener => listener(created.last));
});
subscriber.subscribe();
this.counts.set(key, created);
shared = created;
shared = {subscriber: null, listeners: new Set()};
this.start(shared, entityType, keyFilters);
this.counts.set(key, shared);
} else if (shared.last !== undefined) {
onCount(shared.last);
}
@ -57,4 +48,29 @@ export class HomeCountService {
destroyRef.onDestroy(release);
return release;
}
reread(entityType: EntityType, keyFilters?: KeyFilter[]): void {
const shared = this.counts.get(this.key(entityType, keyFilters));
if (shared && shared.last === undefined) {
shared.subscriber.unsubscribe();
this.start(shared, entityType, keyFilters);
}
}
private start(shared: SharedCount, entityType: EntityType, keyFilters?: KeyFilter[]): void {
const cmd = new EntityCountCmd();
cmd.query = {entityFilter: {type: AliasFilterType.entityType, entityType}, keyFilters};
const subscriber = new TelemetrySubscriber(this.telemetryWsService, this.zone);
subscriber.subscriptionCommands.push(cmd);
subscriber.entityCount$.subscribe(update => {
shared.last = update.count ?? 0;
shared.listeners.forEach(listener => listener(shared.last));
});
subscriber.subscribe();
shared.subscriber = subscriber;
}
private key(entityType: EntityType, keyFilters?: KeyFilter[]): string {
return JSON.stringify([entityType, keyFilters ?? null]);
}
}

155
ui-ngx/src/app/modules/home/pages/home-page/home-load.service.ts

@ -0,0 +1,155 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { inject, Injectable, signal } from '@angular/core';
import { Observable } from 'rxjs';
import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state';
import { getCurrentAuthUser } from '@core/auth/auth.selectors';
const KEPT_KEY = 'tb_home_load_kept';
const READ_KEY = 'tb_home_load_read';
const READ_EVERY_MS = 60_000;
interface Kept {
h: Record<string, number>;
at: Record<string, number>;
}
export class HomeRead<T> {
readonly reading = signal(false);
readonly failed = signal(false);
readonly fresh = signal(false);
readonly readAt = signal<number | null>(null);
readonly last: T | null;
constructor(private load: HomeLoadService,
private card: string,
private request: () => Observable<T>,
private apply: (data: T) => void) {
this.last = load.lastRead<T>(card);
}
start(): void {
if (this.last) {
this.apply(this.last);
this.readAt.set(this.load.readAt(this.card));
}
this.read();
}
read(): void {
this.reading.set(true);
this.failed.set(false);
this.request().subscribe({
next: data => {
this.apply(data);
this.keep(data);
this.fresh.set(true);
this.reading.set(false);
},
error: () => {
this.failed.set(true);
this.reading.set(false);
}
});
}
keep(data: T): void {
this.load.keepRead(this.card, data);
this.readAt.set(Date.now());
}
}
/**
* What Home keeps between visits, per user: each card's height at its width, so a skeleton takes the room the card had and
* the read lands without moving the page; when each card was last read, for the foot of a failed refresh; and the last read
* itself for the cards that show it at once (the person's own and slow-changing things).
*/
@Injectable({
providedIn: 'root'
})
export class HomeLoadService {
private store = inject(Store<AppState>);
private kept: Kept = this.readKept();
private persistTimer: ReturnType<typeof setTimeout> | null = null;
height(card: string, width: number): number | null {
return this.kept.h[this.heightKey(card, width)] ?? null;
}
keepHeight(card: string, width: number, height: number): void {
const key = this.heightKey(card, width);
if (height > 0 && this.kept.h[key] !== height) {
this.kept.h[key] = height;
this.persist();
}
}
readAt(card: string): number | null {
return this.kept.at[this.cardKey(card)] ?? null;
}
markRead(card: string): void {
const key = this.cardKey(card);
const now = Date.now();
if (!this.kept.at[key] || now - this.kept.at[key] > READ_EVERY_MS) {
this.kept.at[key] = now;
this.persist();
}
}
lastRead<T>(card: string): T | null {
try {
const value = localStorage.getItem(`${READ_KEY}_${this.cardKey(card)}`);
return value ? JSON.parse(value) as T : null;
} catch {
return null;
}
}
keepRead<T>(card: string, data: T): void {
try {
localStorage.setItem(`${READ_KEY}_${this.cardKey(card)}`, JSON.stringify(data));
} catch {
return;
}
this.markRead(card);
}
reader<T>(card: string, request: () => Observable<T>, apply: (data: T) => void): HomeRead<T> {
return new HomeRead(this, card, request, apply);
}
private cardKey(card: string): string {
return `${getCurrentAuthUser(this.store)?.userId ?? ''}|${card}`;
}
private heightKey(card: string, width: number): string {
return `${this.cardKey(card)}|${Math.round(width / 24)}`;
}
private readKept(): Kept {
try {
const kept = JSON.parse(localStorage.getItem(KEPT_KEY) || '{}') || {};
return {h: kept.h || {}, at: kept.at || {}};
} catch {
return {h: {}, at: {}};
}
}
private persist(): void {
if (this.persistTimer) {
clearTimeout(this.persistTimer);
}
this.persistTimer = setTimeout(() => {
this.persistTimer = null;
try {
localStorage.setItem(KEPT_KEY, JSON.stringify(this.kept));
} catch {
return;
}
}, 200);
}
}

2
ui-ngx/src/app/modules/home/pages/home-page/home-page.module.ts

@ -12,6 +12,7 @@ import { SysAdminHomeComponent } from '@home/pages/home-page/pages/sys-admin-hom
import { TenantAdminHomeComponent } from '@home/pages/home-page/pages/tenant-admin-home.component';
import { CustomerUserHomeComponent } from '@home/pages/home-page/pages/customer-user-home.component';
import { HomeCardComponent } from '@home/pages/home-page/components/home-card.component';
import { HomeSkeletonComponent } from '@home/pages/home-page/components/home-skeleton.component';
import { WelcomeHomeComponent } from '@home/pages/home-page/components/welcome-home.component';
import { StatusLineHomeComponent } from '@home/pages/home-page/components/status-line-home.component';
import { AiAssistantHomeComponent } from '@home/pages/home-page/components/ai-assistant-home.component';
@ -48,6 +49,7 @@ import { AiComposerModule } from '@home/components/ai/ai-composer.module';
TenantAdminHomeComponent,
CustomerUserHomeComponent,
HomeCardComponent,
HomeSkeletonComponent,
WelcomeHomeComponent,
StatusLineHomeComponent,
AiAssistantHomeComponent,

20
ui-ngx/src/app/modules/home/pages/home-page/sys-admin-home.service.ts

@ -2,12 +2,17 @@
// SPDX-License-Identifier: BUSL-1.1
import { inject, Injectable, signal } from '@angular/core';
import { Observable, of } from 'rxjs';
import { catchError, shareReplay } from 'rxjs/operators';
import { catchError, shareReplay, startWith, tap } from 'rxjs/operators';
import { AdminService } from '@core/http/admin.service';
import { FeaturesInfo, UpdateMessage } from '@shared/models/settings.models';
import { HomeCardId } from '@shared/models/user-settings.models';
import { HomeLoadService } from '@home/pages/home-page/home-load.service';
import { environment as env } from '@env/environment';
let hiddenRelease: string | null = null;
const releaseOf = (version: string | null | undefined): string => (version ?? '').match(/^\d+(\.\d+)*/)?.[0] ?? '';
@Injectable()
export class SysAdminHomeService {
@ -18,13 +23,24 @@ export class SysAdminHomeService {
shareReplay(1)
);
private load = inject(HomeLoadService);
private lastUpdate = this.keptUpdate();
readonly update$: Observable<UpdateMessage | null> = this.adminService.checkUpdates({ignoreErrors: true, ignoreLoading: true}).pipe(
catchError(() => of(null)),
tap(update => this.load.keepRead(HomeCardId.PRODUCT_RELEASE, update)),
catchError(() => of(this.lastUpdate)),
startWith(this.lastUpdate),
shareReplay(1)
);
readonly hiddenRelease = signal<string | null>(hiddenRelease);
private keptUpdate(): UpdateMessage | null {
const kept = this.load.lastRead<UpdateMessage>(HomeCardId.PRODUCT_RELEASE);
return kept && releaseOf(kept.currentVersion) === releaseOf(env.tbVersion) ? kept : null;
}
setHiddenRelease(version: string | null): void {
hiddenRelease = version;
this.hiddenRelease.set(version);

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

@ -1,5 +1,6 @@
// 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
import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/core';
import { Router } from '@angular/router';
import { MatAutocompleteTrigger } from '@angular/material/autocomplete';

1
ui-ngx/src/app/shared/models/ai-chat.models.ts

@ -40,6 +40,7 @@ export interface ChatInfo extends ChatConfiguration {
pinned?: boolean;
pinnedTime?: number;
prompt?: string;
prompts?: string[];
status?: ChatStatus;
statusReason?: string;
updatedTime?: number;

2
ui-ngx/src/assets/locale/locale.constant-ar_AE.json

@ -2462,7 +2462,7 @@
"entity-title": "تم الوصول إلى حد {{entities}}",
"notice-count": "{{title}}: {{limit}} من {{limit}}.",
"notice": "{{title}}.",
"feature-title": "لا تتضمن خطتك {{feature}}",
"feature-unavailable-title": "الميزة «{{feature}}» غير متاحة",
"feature": {
"white-labeling": "تخصيص العلامة التجارية",
"integrations": "التكاملات",

2
ui-ngx/src/assets/locale/locale.constant-ca_ES.json

@ -2462,7 +2462,7 @@
"entity-title": "S'ha assolit el límit de {{entities}}",
"notice-count": "{{title}}: {{limit}} de {{limit}}.",
"notice": "{{title}}.",
"feature-title": "{{feature}}: fora del vostre pla",
"feature-unavailable-title": "{{feature}}: no disponible",
"feature": {
"white-labeling": "Marca blanca",
"integrations": "Integracions",

2
ui-ngx/src/assets/locale/locale.constant-cs_CZ.json

@ -2462,7 +2462,7 @@
"entity-title": "Dosažen limit: {{entities}}",
"notice-count": "{{title}}: {{limit}} z {{limit}}.",
"notice": "{{title}}.",
"feature-title": "Funkce {{feature}} není součástí vašeho tarifu",
"feature-unavailable-title": "Funkce {{feature}} není k dispozici",
"feature": {
"white-labeling": "Vlastní branding",
"integrations": "Integrace",

2
ui-ngx/src/assets/locale/locale.constant-da_DK.json

@ -2462,7 +2462,7 @@
"entity-title": "{{entities}}: grænsen er nået",
"notice-count": "{{title}}: {{limit}} af {{limit}}.",
"notice": "{{title}}.",
"feature-title": "{{feature}} er ikke inkluderet i din plan",
"feature-unavailable-title": "{{feature}} er ikke tilgængelig",
"feature": {
"white-labeling": "White labeling",
"integrations": "Integrationer",

2
ui-ngx/src/assets/locale/locale.constant-de_DE.json

@ -2462,7 +2462,7 @@
"entity-title": "Limit für {{entities}} erreicht",
"notice-count": "{{title}}: {{limit}} von {{limit}}.",
"notice": "{{title}}.",
"feature-title": "Nicht in Ihrem Tarif enthalten: {{feature}}",
"feature-unavailable-title": "Nicht verfügbar: {{feature}}",
"feature": {
"white-labeling": "White-Labeling",
"integrations": "Integrationen",

2
ui-ngx/src/assets/locale/locale.constant-el_GR.json

@ -2462,7 +2462,7 @@
"entity-title": "Επιτεύχθηκε το όριο ({{entities}})",
"notice-count": "{{title}}: {{limit}} από {{limit}}.",
"notice": "{{title}}.",
"feature-title": "{{feature}}: δεν περιλαμβάνεται στο πρόγραμμα συνδρομής σας",
"feature-unavailable-title": "Η λειτουργία «{{feature}}» δεν είναι διαθέσιμη",
"feature": {
"white-labeling": "White labeling",
"integrations": "Ενσωματώσεις",

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

@ -2444,7 +2444,7 @@
"entity-title": "{{entities}} limit reached",
"notice-count": "{{title}}: {{limit}} of {{limit}}.",
"notice": "{{title}}.",
"feature-title": "{{feature}} not included in your plan",
"feature-unavailable-title": "{{feature}} is not available",
"feature": {
"white-labeling": "White labeling",
"integrations": "Integrations",
@ -9231,7 +9231,6 @@
"open-results": "Open results in IoT Hub",
"all-devices": "All {{count}} devices",
"also": "Also in IoT Hub",
"unavailable": "IoT Hub is not available right now.",
"templates": "Solution templates",
"device-library": "Device library",
"widgets": "Widgets",
@ -9282,6 +9281,14 @@
"license": "License",
"install-items": "Install"
},
"load": {
"failed": "{{name}} didn't load.",
"retry": "Retry",
"stale-today": "Not refreshed since {{time}}.",
"stale-date": "Not refreshed since {{date}}, {{time}}.",
"qr-failed": "Didn't load.",
"progress-failed": "Your progress didn't load."
},
"alarms": {
"whose": "Whose alarms",
"all": "All",

2
ui-ngx/src/assets/locale/locale.constant-es_ES.json

@ -2462,7 +2462,7 @@
"entity-title": "Límite alcanzado: {{entities}}",
"notice-count": "{{title}}: {{limit}} de {{limit}}.",
"notice": "{{title}}.",
"feature-title": "Tu plan no incluye {{feature}}",
"feature-unavailable-title": "{{feature}}: no disponible",
"feature": {
"white-labeling": "Marca blanca",
"integrations": "Integraciones",

2
ui-ngx/src/assets/locale/locale.constant-fr_FR.json

@ -2462,7 +2462,7 @@
"entity-title": "Limite atteinte : {{entities}}",
"notice-count": "{{title}} : {{limit}} sur {{limit}}.",
"notice": "{{title}}.",
"feature-title": "Non inclus dans votre forfait : {{feature}}",
"feature-unavailable-title": "{{feature}} : non disponible",
"feature": {
"white-labeling": "Marque blanche",
"integrations": "Intégrations",

2
ui-ngx/src/assets/locale/locale.constant-hi_IN.json

@ -2462,7 +2462,7 @@
"entity-title": "{{entities}} की सीमा पूरी हो गई",
"notice-count": "{{title}}: {{limit}} में से {{limit}}।",
"notice": "{{title}}।",
"feature-title": "{{feature}} आपके प्लान में शामिल नहीं है",
"feature-unavailable-title": "{{feature}} उपलब्ध नहीं है",
"feature": {
"white-labeling": "व्हाइट लेबलिंग",
"integrations": "इंटीग्रेशन",

2
ui-ngx/src/assets/locale/locale.constant-it_IT.json

@ -2462,7 +2462,7 @@
"entity-title": "Limite di {{entities}} raggiunto",
"notice-count": "{{title}}: {{limit}} su {{limit}}.",
"notice": "{{title}}.",
"feature-title": "Funzionalità non inclusa nel tuo piano: {{feature}}",
"feature-unavailable-title": "{{feature}}: non disponibile",
"feature": {
"white-labeling": "White labeling",
"integrations": "Integrazioni",

2
ui-ngx/src/assets/locale/locale.constant-ja_JP.json

@ -2462,7 +2462,7 @@
"entity-title": "{{entities}}の上限に達しました",
"notice-count": "{{title}}: {{limit}}件中{{limit}}件。",
"notice": "{{title}}。",
"feature-title": "{{feature}}はご利用のプランに含まれていません",
"feature-unavailable-title": "{{feature}}は利用できません",
"feature": {
"white-labeling": "ホワイトラベリング",
"integrations": "統合",

2
ui-ngx/src/assets/locale/locale.constant-ka_GE.json

@ -2462,7 +2462,7 @@
"entity-title": "{{entities}} — ლიმიტი მიღწეულია",
"notice-count": "{{title}}: {{limit}} {{limit}}-დან.",
"notice": "{{title}}.",
"feature-title": "{{feature}} არ შედის თქვენს სატარიფო გეგმაში",
"feature-unavailable-title": "ფუნქცია „{{feature}}“ მიუწვდომელია",
"feature": {
"white-labeling": "ბრენდირება",
"integrations": "ინტეგრაციები",

2
ui-ngx/src/assets/locale/locale.constant-ko_KR.json

@ -2462,7 +2462,7 @@
"entity-title": "{{entities}} 한도 도달",
"notice-count": "{{title}}: {{limit}}/{{limit}}.",
"notice": "{{title}}.",
"feature-title": "{{feature}}이(가) 현재 플랜에 포함되지 않음",
"feature-unavailable-title": "{{feature}}을(를) 사용할 수 없습니다",
"feature": {
"white-labeling": "화이트 라벨링",
"integrations": "통합",

2
ui-ngx/src/assets/locale/locale.constant-lt_LT.json

@ -2462,7 +2462,7 @@
"entity-title": "Pasiektas limitas: {{entities}}",
"notice-count": "{{title}}: {{limit}} iš {{limit}}.",
"notice": "{{title}}.",
"feature-title": "{{feature}} nėra jūsų plane",
"feature-unavailable-title": "Funkcija „{{feature}}“ nepasiekiama",
"feature": {
"white-labeling": "Prekės ženklo tinkinimo",
"integrations": "Integracijų",

2
ui-ngx/src/assets/locale/locale.constant-lv_LV.json

@ -2462,7 +2462,7 @@
"entity-title": "{{entities}}: sasniegts ierobežojums",
"notice-count": "{{title}}: {{limit}} no {{limit}}.",
"notice": "{{title}}.",
"feature-title": "Funkcija nav iekļauta jūsu plānā: {{feature}}",
"feature-unavailable-title": "Funkcija “{{feature}}” nav pieejama",
"feature": {
"white-labeling": "Pielāgošana",
"integrations": "Integrācijas",

2
ui-ngx/src/assets/locale/locale.constant-nl_BE.json

@ -2462,7 +2462,7 @@
"entity-title": "Limiet voor {{entities}} bereikt",
"notice-count": "{{title}}: {{limit}} van {{limit}}.",
"notice": "{{title}}.",
"feature-title": "{{feature}} niet inbegrepen in je abonnement",
"feature-unavailable-title": "{{feature}} is niet beschikbaar",
"feature": {
"white-labeling": "White labeling",
"integrations": "Integraties",

2
ui-ngx/src/assets/locale/locale.constant-nl_NL.json

@ -2462,7 +2462,7 @@
"entity-title": "Limiet voor {{entities}} bereikt",
"notice-count": "{{title}}: {{limit}} van {{limit}}.",
"notice": "{{title}}.",
"feature-title": "{{feature}} niet inbegrepen in je abonnement",
"feature-unavailable-title": "{{feature}} is niet beschikbaar",
"feature": {
"white-labeling": "White labeling",
"integrations": "Integraties",

2
ui-ngx/src/assets/locale/locale.constant-no_NO.json

@ -2462,7 +2462,7 @@
"entity-title": "{{entities}}: grensen er nådd",
"notice-count": "{{title}}: {{limit}} av {{limit}}.",
"notice": "{{title}}.",
"feature-title": "{{feature}} er ikke inkludert i planen din",
"feature-unavailable-title": "{{feature}} er ikke tilgjengelig",
"feature": {
"white-labeling": "White labeling",
"integrations": "Integrasjoner",

2
ui-ngx/src/assets/locale/locale.constant-pl_PL.json

@ -2462,7 +2462,7 @@
"entity-title": "{{entities}} — osiągnięto limit",
"notice-count": "{{title}}: {{limit}} z {{limit}}.",
"notice": "{{title}}.",
"feature-title": "{{feature}}: poza zakresem Twojego planu",
"feature-unavailable-title": "Funkcja {{feature}} jest niedostępna",
"feature": {
"white-labeling": "Branding",
"integrations": "Integracje",

2
ui-ngx/src/assets/locale/locale.constant-pt_BR.json

@ -2462,7 +2462,7 @@
"entity-title": "Limite de {{entities}} atingido",
"notice-count": "{{title}}: {{limit}} de {{limit}}.",
"notice": "{{title}}.",
"feature-title": "{{feature}}: fora do seu plano",
"feature-unavailable-title": "{{feature}}: indisponível",
"feature": {
"white-labeling": "Personalização de marca",
"integrations": "Integrações",

2
ui-ngx/src/assets/locale/locale.constant-ro_RO.json

@ -2462,7 +2462,7 @@
"entity-title": "Limita pentru {{entities}} a fost atinsă",
"notice-count": "{{title}}: {{limit}} din {{limit}}.",
"notice": "{{title}}.",
"feature-title": "Funcția {{feature}} nu este inclusă în planul dumneavoastră",
"feature-unavailable-title": "{{feature}}: indisponibil",
"feature": {
"white-labeling": "Personalizare marcă",
"integrations": "Integrări",

2
ui-ngx/src/assets/locale/locale.constant-sl_SI.json

@ -2462,7 +2462,7 @@
"entity-title": "Dosežena omejitev: {{entities}}",
"notice-count": "{{title}}: {{limit}} od {{limit}}.",
"notice": "{{title}}.",
"feature-title": "Funkcija »{{feature}}« ni vključena v vaš paket",
"feature-unavailable-title": "Funkcija {{feature}} ni na voljo",
"feature": {
"white-labeling": "Prilagajanje znamke",
"integrations": "Integracije",

2
ui-ngx/src/assets/locale/locale.constant-tr_TR.json

@ -2462,7 +2462,7 @@
"entity-title": "{{entities}} limitine ulaşıldı",
"notice-count": "{{title}}: {{limit}} / {{limit}}.",
"notice": "{{title}}.",
"feature-title": "{{feature}} planınıza dahil değil",
"feature-unavailable-title": "{{feature}} kullanılamıyor",
"feature": {
"white-labeling": "White labeling",
"integrations": "Entegrasyonlar",

2
ui-ngx/src/assets/locale/locale.constant-uk_UA.json

@ -2462,7 +2462,7 @@
"entity-title": "Досягнуто ліміту: {{entities}}",
"notice-count": "{{title}}: {{limit}} з {{limit}}.",
"notice": "{{title}}.",
"feature-title": "Функція «{{feature}}» не входить до вашого тарифного плану",
"feature-unavailable-title": "Функція «{{feature}}» недоступна",
"feature": {
"white-labeling": "Брендування",
"integrations": "Інтеграції",

2
ui-ngx/src/assets/locale/locale.constant-zh_CN.json

@ -2462,7 +2462,7 @@
"entity-title": "{{entities}}已达上限",
"notice-count": "{{title}}:{{limit}} / {{limit}}。",
"notice": "{{title}}。",
"feature-title": "您的套餐不包含{{feature}}",
"feature-unavailable-title": "{{feature}}不可用",
"feature": {
"white-labeling": "白标",
"integrations": "集成",

2
ui-ngx/src/assets/locale/locale.constant-zh_TW.json

@ -15605,7 +15605,7 @@
"entity-title": "已達 {{entities}} 上限",
"notice-count": "{{title}}:{{limit}}/{{limit}}。",
"notice": "{{title}}。",
"feature-title": "您的方案未包含{{feature}}",
"feature-unavailable-title": "{{feature}}無法使用",
"feature": {
"white-labeling": "白標",
"integrations": "整合",

Loading…
Cancel
Save