Browse Source

feat: AI chat color questions show swatches and open the color picker for another color, image actions preview the saved images, the website brand read shows its colors and logo candidates, and a white labeling change from the chat always reloads the white labeling page, also after an auto-approved reset

pull/16833/head
Igor Kulikov 3 weeks ago
parent
commit
57d16400cf
  1. 12
      ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html
  2. 52
      ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts
  3. 1
      ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts
  4. 15
      ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts
  5. 38
      ui-ngx/src/app/modules/home/components/ai/ai-question.component.html
  6. 62
      ui-ngx/src/app/modules/home/components/ai/ai-question.component.ts
  7. 2
      ui-ngx/src/app/modules/home/pages/admin/white-labeling.component.ts
  8. 1
      ui-ngx/src/app/shared/models/solution-creator.models.ts
  9. 16
      ui-ngx/src/assets/locale/locale.constant-en_US.json
  10. 50
      ui-ngx/src/theme/ai-theme.scss

12
ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html

@ -130,6 +130,18 @@
<tb-markdown usePlainMarkdown [data]="block.text"></tb-markdown>
</div>
}
@case ('images') {
<div class="k-detail-images">
@for (image of block.rows; track image.url) {
<figure>
<img [src]="image.url | image: {preview: true} | async" [alt]="image.label ? say(image.label) : ''">
@if (image.label) {
<figcaption>{{ say(image.label) }}</figcaption>
}
</figure>
}
</div>
}
@case ('note') {
<p class="k-detail-note">{{ say(block.text) }}</p>
}

52
ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts

@ -83,7 +83,13 @@ export type AiDetailBlock =
| {type: 'code'; label: string; text: string}
| {type: 'note'; text: AiDetailText}
| {type: 'text'; text: string}
| {type: 'json'; label: string; text: string};
| {type: 'json'; label: string; text: string}
| {type: 'images'; rows: AiDetailImage[]};
export interface AiDetailImage {
label?: AiDetailText;
url: string;
}
export interface AiDetailView {
hood?: AiDetailText;
@ -209,6 +215,16 @@ function entity(id: unknown, entityType: unknown, names: AiDetailNames): AiDetai
return {id: key, entityType: type ?? known?.entityType, name: known?.name};
}
function galleryImage(value: unknown): string | undefined {
const url = str(value);
return url && /^(tb-image;)?\/api\/images\//.test(url) ? url : undefined;
}
function images(rows: {label?: AiDetailText; value: unknown}[]): AiDetailBlock[] {
const found: AiDetailImage[] = rows.map(row => ({label: row.label, url: galleryImage(row.value)})).filter(row => !!row.url);
return found.length ? [{type: 'images', rows: found}] : [];
}
function text(key: string, params?: Record<string, AiDetailParam>): AiDetailText {
return {key: K + key, params};
}
@ -1124,7 +1140,8 @@ function describe(tool: string, values: Values, result: unknown, names: AiDetail
if (saved.tested === true) {
rows.push({label: K + 'fact.tested', value: K + 'yes'});
}
return {hood: text('save', {what: K + 'kind.' + kind, name}), blocks: rows.length ? [{type: 'facts', rows}] : generic(result, 'result')};
const pictures = images([{value: values.image}]);
return {hood: text('save', {what: K + 'kind.' + kind, name}), blocks: rows.length ? [{type: 'facts', rows}, ...pictures] : [...generic(result, 'result'), ...pictures]};
}
case 'save_relations': {
if (!isObject(result)) {
@ -1171,12 +1188,38 @@ function describe(tool: string, values: Values, result: unknown, names: AiDetail
}
case 'read_white_labeling':
return {hood: text('read-white-labeling'), blocks: json('settings', result)};
case 'read_website_brand': {
const site = str(isObject(result) ? result.url : undefined) ?? str(values.url) ?? '—';
if (!isObject(result)) {
return {hood: text('read-website-brand', {site}), blocks: generic(result, 'result')};
}
const blocks: AiDetailBlock[] = [];
if (str(result.pageNotRead)) {
blocks.push({type: 'note', text: text('website-not-read')});
}
const colors = [str(result.themeColor) ? `${result.themeColor} · theme-color` : undefined,
...(Array.isArray(result.iconColors) ? result.iconColors.filter(isObject).map(color => `${color.color} · icon ${color.percent}%`) : []),
...Object.entries(isObject(result.colorVariables) ? result.colorVariables : {}).map(([name, color]) => `${color} · ${name}`),
...(Array.isArray(result.colors) ? result.colors.filter(isObject).map(color => `${color.color} · ×${color.uses}`) : [])]
.filter(Boolean).slice(0, MAX_ROWS);
if (colors.length) {
blocks.push({type: 'list', label: text('website-colors'), rows: colors});
}
const logos = (Array.isArray(result.logos) ? result.logos.filter(isObject) : [])
.map(logo => str(logo.url) ?? `<svg> · ${logo.source}`).slice(0, MAX_ROWS);
if (logos.length) {
blocks.push({type: 'list', label: text('website-logos'), rows: logos});
}
return {hood: text('read-website-brand', {site}), blocks};
}
case 'save_white_labeling': {
const {target, reset, ...changes} = values;
if (reset) {
return {hood: text(target === 'LOGIN' ? 'reset-white-labeling-login' : 'reset-white-labeling'), blocks: []};
}
return {hood: text(target === 'LOGIN' ? 'save-white-labeling-login' : 'save-white-labeling'), blocks: [{type: 'facts', rows: facts(changes)}]};
return {hood: text(target === 'LOGIN' ? 'save-white-labeling-login' : 'save-white-labeling'), blocks: [{type: 'facts', rows: facts(changes)},
...images([{label: text('image-logo'), value: values.logoImage}, {label: text('image-collapsed-logo'), value: values.collapsedLogoImage},
{label: text('image-favicon'), value: values.favicon}])]};
}
case 'read_ota': {
if (!isObject(result)) {
@ -1278,7 +1321,8 @@ function describe(tool: string, values: Values, result: unknown, names: AiDetail
case 'save_image': {
const saved = isObject(result) ? result : {};
const rows: AiDetailFact[] = str(saved.link) ? [{label: K + 'fact.link', value: saved.link, mono: true}] : [];
return {hood: text('save-image', {name: str(saved.title) ?? str(values.title) ?? '—'}), blocks: rows.length ? [{type: 'facts', rows}] : generic(result, 'result')};
return {hood: text('save-image', {name: str(saved.title) ?? str(values.title) ?? '—'}),
blocks: rows.length ? [{type: 'facts', rows}, ...images([{value: saved.link}])] : generic(result, 'result')};
}
case 'reprocess_calculated_field':
return {hood: text('reprocess', {entity: of(values.calculatedFieldId, 'CALCULATED_FIELD'), from: dateText(values.startTime ?? values.startTs), to: endText(values.endTime ?? values.endTs)}), blocks: generic(result, 'result')};

1
ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts

@ -68,6 +68,7 @@ const TOOL_WORDS: Record<string, string> = {
read_gateway_status: 'read-gateway-status',
read_ota: 'read-ota',
read_white_labeling: 'read-white-labeling',
read_website_brand: 'read-website-brand',
save_white_labeling: 'save-white-labeling',
save_ota_package: 'save-ota-package',
assign_ota_package: 'assign-ota-package',

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

@ -376,6 +376,7 @@ export class AiChatComponent implements OnInit, OnDestroy {
private shownChatId: string | undefined;
private replyingChatId: string | undefined;
private affectedEntities: EntityId[] = [];
private appliedEffects = new Set<string>();
private logScrollBottom: number | undefined;
private newTurnsEffect = effect(() => {
@ -951,8 +952,11 @@ export class AiChatComponent implements OnInit, OnDestroy {
case 'toolExecutionResult':
this.completedExecutions.update(map => ({...map, [event.data.executionId]: event.data}));
if (event.data.executionStatus === 'SUCCESS') {
const approval = this.messages().find(message => message.from === 'APPROVAL' && message.data.executionId === event.data.executionId);
this.applySideEffects(approval?.from === 'APPROVAL' ? approval.data.tool : undefined, approval?.from === 'APPROVAL' ? approval.data.arguments : undefined);
const call = this.messages().find(message => (message.from === 'APPROVAL' || message.from === 'ACTION')
&& message.data.executionId === event.data.executionId);
if (call?.from === 'APPROVAL' || call?.from === 'ACTION') {
this.applySideEffects(event.data.executionId, call.data.tool, call.data.arguments);
}
}
if (event.data.affectedEntities?.length) {
this.affectedEntities.push(...event.data.affectedEntities);
@ -1042,10 +1046,11 @@ export class AiChatComponent implements OnInit, OnDestroy {
}
}
private applySideEffects(tool: string | undefined, args: unknown): void {
if (tool !== 'save_white_labeling') {
private applySideEffects(executionId: string, tool: string | undefined, args: unknown): void {
if (tool !== 'save_white_labeling' || this.appliedEffects.has(executionId)) {
return;
}
this.appliedEffects.add(executionId);
const target = (aiParse(args) as {target?: string})?.target === 'LOGIN' ? 'LOGIN' : 'GENERAL';
if (target === 'GENERAL') {
this.whiteLabelingService.loadUserWhiteLabelingParams().subscribe();
@ -1057,7 +1062,7 @@ export class AiChatComponent implements OnInit, OnDestroy {
if (finished.status === 'SUCCESS') {
const started = this.messages().find(message => message.from === 'ACTION' && message.data.executionId === finished.executionId);
if (started?.from === 'ACTION') {
this.applySideEffects(started.data.tool, started.data.arguments);
this.applySideEffects(finished.executionId, started.data.tool, started.data.arguments);
}
}
if (finished.affectedEntities?.length) {

38
ui-ngx/src/app/modules/home/components/ai/ai-question.component.html

@ -15,7 +15,7 @@
@for (item of answers; track item.question.id) {
<div class="k-q">
<span class="k-qt">{{ item.question.question }}</span>
<span class="k-opts"><button type="button" class="ob-chip" aria-pressed="true" disabled>{{ shown(item) }}</button></span>
<span class="k-opts"><button type="button" class="ob-chip" aria-pressed="true" disabled>@if (!item.question.secret && colorOf(item.answer); as color) {<span class="k-swatch" [style.background]="color" aria-hidden="true"></span>}{{ shown(item) }}</button></span>
</div>
}
</div>
@ -76,7 +76,18 @@
}
</div>
<div class="k-ask-a">
@if (isFree(step)) {
@if (isFree(step) && isColor(step)) {
<div class="k-optrow">
<button #freeColor type="button" class="ob-chip" [attr.aria-pressed]="!!otherText(step)" [disabled]="disabled()"
(click)="pickColor(step, freeColor)">
@if (colorOf(otherText(step)); as color) {
<span class="k-swatch" [style.background]="color" aria-hidden="true"></span>{{ color }}
} @else {
<mat-icon aria-hidden="true">palette</mat-icon>{{ 'ai-assistant.question.pick-color' | translate }}
}
</button>
</div>
} @else if (isFree(step)) {
<div class="k-optcards list">
<div class="k-optcard other free" (click)="$any($event.currentTarget).querySelector('.k-opt-input')?.focus()">
<span class="k-optbody">
@ -100,7 +111,7 @@
<button type="button" role="checkbox" class="k-optcard multi" [attr.aria-checked]="isChosen(step, option.label)"
[disabled]="disabled()" (click)="toggle(step, option.label)">
<span class="k-optdot"><mat-icon aria-hidden="true">check</mat-icon></span>
<span class="k-optbody"><b>{{ option.label }}</b>@if (option.hint) {<span>{{ option.hint }}</span>}</span>
<span class="k-optbody"><b>@if (colorOf(option.label); as color) {<span class="k-swatch" [style.background]="color" aria-hidden="true"></span>}{{ option.label }}</b>@if (option.hint) {<span>{{ option.hint }}</span>}</span>
</button>
}
<div class="k-optcard multi other" role="checkbox" [attr.aria-checked]="isOther(step)" (click)="multiArea.focus()">
@ -119,12 +130,23 @@
@for (option of step.options; track option.label) {
<button type="button" role="radio" class="ob-chip" [attr.aria-checked]="!isOther(step) && valueOf(step) === option.label"
[attr.aria-pressed]="!isOther(step) && valueOf(step) === option.label"
[disabled]="disabled()" (click)="pick(step, option.label)">{{ option.label }}</button>
[disabled]="disabled()" (click)="pick(step, option.label)">@if (colorOf(option.label); as color) {<span class="k-swatch" [style.background]="color" aria-hidden="true"></span>}{{ option.label }}</button>
}
@if (isColor(step)) {
<button #otherColor type="button" role="radio" class="ob-chip" [attr.aria-checked]="isOther(step)" [attr.aria-pressed]="isOther(step)"
[disabled]="disabled()" (click)="pickColor(step, otherColor)">
@if (isOther(step) && colorOf(otherText(step)); as color) {
<span class="k-swatch" [style.background]="color" aria-hidden="true"></span>{{ color }}
} @else {
<mat-icon aria-hidden="true">palette</mat-icon>{{ 'ai-assistant.question.other-color' | translate }}
}
</button>
} @else {
<button type="button" role="radio" class="ob-chip" [attr.aria-checked]="isOther(step)" [attr.aria-pressed]="isOther(step)"
[disabled]="disabled()" (click)="pickOther(step)">{{ 'ai-assistant.question.other-chip' | translate }}</button>
}
<button type="button" role="radio" class="ob-chip" [attr.aria-checked]="isOther(step)" [attr.aria-pressed]="isOther(step)"
[disabled]="disabled()" (click)="pickOther(step)">{{ 'ai-assistant.question.other-chip' | translate }}</button>
</div>
@if (isOther(step)) {
@if (isOther(step) && !isColor(step)) {
<textarea #rowArea class="k-opt-input k-other-area" rows="1" spellcheck="false" [disabled]="disabled()"
[value]="otherText(step)" [placeholder]="'ai-assistant.question.other-hint' | translate"
[attr.aria-label]="step.question + ' · ' + ('ai-assistant.question.other' | translate)"
@ -139,7 +161,7 @@
<button type="button" role="radio" class="k-optcard" [attr.aria-checked]="!isOther(step) && valueOf(step) === option.label"
[disabled]="disabled()" (click)="pick(step, option.label)">
<span class="k-optdot"></span>
<span class="k-optbody"><b>{{ option.label }}</b>@if (option.hint) {<span>{{ option.hint }}</span>}</span>
<span class="k-optbody"><b>@if (colorOf(option.label); as color) {<span class="k-swatch" [style.background]="color" aria-hidden="true"></span>}{{ option.label }}</b>@if (option.hint) {<span>{{ option.hint }}</span>}</span>
</button>
}
<div class="k-optcard other" role="radio" [attr.aria-checked]="isOther(step)" (click)="otherArea.focus()">

62
ui-ngx/src/app/modules/home/components/ai/ai-question.component.ts

@ -1,11 +1,20 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { Component, computed, EventEmitter, inject, input, Output, signal } from '@angular/core';
import { Component, computed, EventEmitter, inject, input, Output, Renderer2, signal, ViewContainerRef } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { AiQuestion, AiQuestionAnswer } from '@shared/models/solution-creator.models';
import { TbPopoverService } from '@shared/components/popover.service';
import { ColorPickerPanelComponent } from '@shared/components/color-picker/color-picker-panel.component';
import tinycolor from 'tinycolor2';
const MULTI_SEPARATOR = ', ';
const HEX_COLOR = /#[0-9a-f]{6}(?![0-9a-z])|#[0-9a-f]{3}(?![0-9a-z])/i;
export function aiColorOf(text: string | undefined): string | null {
return text?.match(HEX_COLOR)?.[0] ?? null;
}
export function aiAnswersText(answers: AiQuestionAnswer[]): string {
return answers.map(item => item.question.question.trim() + ' ' + item.answer.trim()).join('\n');
}
@ -60,6 +69,11 @@ export class AiQuestionComponent {
@Output() skip = new EventEmitter<AiQuestionAnswer[]>();
private translate = inject(TranslateService);
private popoverService = inject(TbPopoverService);
private renderer = inject(Renderer2);
private viewContainerRef = inject(ViewContainerRef);
colorOf = aiColorOf;
at = signal(0);
move = signal<'next' | 'back' | null>(null);
@ -124,7 +138,7 @@ export class AiQuestionComponent {
}
isChipRow(question: AiQuestion): boolean {
return !question.multiple && question.options.length >= 2 && question.options.length <= 4
return !question.multiple && question.options.length >= 2 && question.options.length <= (this.isColor(question) ? 6 : 4)
&& question.options.every(option => option.label.length <= 24);
}
@ -137,6 +151,50 @@ export class AiQuestionComponent {
this.picked.update(values => ({...values, [question.id]: label}));
}
isColor(question: AiQuestion): boolean {
return !question.multiple && !question.secret
&& (!!question.color || (!!question.options?.length && question.options.every(option => !!aiColorOf(option.label))));
}
pickColor(question: AiQuestion, trigger: HTMLElement): void {
if (this.disabled()) {
return;
}
if (this.popoverService.hasPopover(trigger)) {
this.popoverService.hidePopover(trigger);
return;
}
const current = aiColorOf(this.isOther(question) ? this.otherText(question) : this.valueOf(question)) ?? '#305680';
const popover = this.popoverService.displayPopover({
trigger,
renderer: this.renderer,
hostView: this.viewContainerRef,
componentType: ColorPickerPanelComponent,
preferredPlacement: ['bottomLeft', 'bottom', 'topLeft', 'top'],
context: {color: current, disableAlpha: true, colorCancelButton: true},
showCloseButton: false,
popoverContentStyle: {padding: '12px 4px 12px 12px'},
isModal: true
});
popover.tbComponentRef.instance.popover = popover;
popover.tbComponentRef.instance.colorSelected.subscribe((color: string) => {
popover.hide();
const hex = tinycolor(color).toHexString();
if (!question.options?.length) {
this.typed.update(values => ({...values, [question.id]: hex}));
return;
}
const option = question.options.find(item => aiColorOf(item.label)?.toLowerCase() === hex);
if (option) {
this.pick(question, option.label);
} else {
this.picked.update(values => ({...values, [question.id]: null}));
this.typed.update(values => ({...values, [question.id]: hex}));
}
});
popover.tbComponentRef.instance.colorCancelDialog.subscribe(() => popover.hide());
}
pickOther(question: AiQuestion): void {
if (question.multiple || this.isFree(question)) {
return;

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

@ -120,7 +120,7 @@ export class WhiteLabelingComponent extends PageComponent implements OnInit, Has
this.buildWhiteLabelingSettingsForm();
this.loadWhiteLabelingParams();
this.aiAssistantPanelService.whiteLabelingSaved$.pipe(
filter(target => (target === 'LOGIN') === !!this.isLoginWl && !this.wlSettings.dirty),
filter(target => (target === 'LOGIN') === !!this.isLoginWl),
takeUntilDestroyed(this.destroyRef)
).subscribe(() => this.loadWhiteLabelingParams());
}

1
ui-ngx/src/app/shared/models/solution-creator.models.ts

@ -75,6 +75,7 @@ export interface AiQuestion {
recommended?: string | string[];
multiple?: boolean;
secret?: boolean;
color?: boolean;
}
export interface AiQuestionAnswer {

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

@ -693,6 +693,8 @@
"ai-assistant": {
"question": {
"other-chip": "Other…",
"other-color": "Other color…",
"pick-color": "Pick a color",
"needs-answer": "Needs an answer",
"count": "{{at}} of {{of}}",
"other": "Something else",
@ -888,6 +890,13 @@
"read-ota": "{ count, plural, =1 {Checked the update of one device} other {Checked the update of # devices} }",
"read-ota-packages": "Read the OTA packages",
"read-white-labeling": "Read the white labeling",
"read-website-brand": "Read the brand of {{site}}",
"website-colors": "Colors",
"website-logos": "Logo candidates",
"image-logo": "Logo",
"image-collapsed-logo": "Collapsed logo",
"image-favicon": "Favicon",
"website-not-read": "The site blocked automated reading, so only its icon was read",
"save-white-labeling": "Changed the platform's white labeling",
"save-white-labeling-login": "Changed the login page's white labeling",
"reset-white-labeling": "Reset the platform's white labeling to the defaults",
@ -1313,6 +1322,10 @@
"run": "Reading the white labeling",
"done": "Read the white labeling"
},
"read-website-brand": {
"run": "Reading the website's brand",
"done": "Read the website's brand"
},
"save-white-labeling": {
"run": "Saving the white labeling",
"done": "Saved the white labeling"
@ -1669,6 +1682,9 @@
"pageBackgroundColor": "Page background",
"darkForeground": "Dark text",
"showNameBottom": "Name below the form",
"domain": "Domain",
"baseUrl": "Base URL",
"prohibitDifferentUrl": "Base URL only",
"url": "URL",
"tag": "Tag",
"entities": "Entities",

50
ui-ngx/src/theme/ai-theme.scss

@ -4363,6 +4363,21 @@ cursor: pointer;
}
}
.k-ask .k-swatch {
display: inline-block;
flex: none;
width: 16px;
height: 16px;
margin-right: 2px;
border-radius: 50%;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.16);
vertical-align: -3px;
}
.k-ask .k-optbody b .k-swatch {
margin-right: 8px;
}
.k-ask .k-opthint {
margin: 8px 0 0;
font-size: 14px;
@ -4591,6 +4606,41 @@ tb-ai-action-detail.k-detail {
margin-top: 0;
}
.k-detail-images {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin: 4px 0;
figure {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 4px;
margin: 0;
}
img {
display: block;
max-width: 160px;
max-height: 64px;
min-width: 24px;
min-height: 24px;
padding: 6px;
box-sizing: content-box;
object-fit: contain;
border: 1px solid var(--tb-line);
border-radius: 8px;
background: var(--tb-surface);
}
figcaption {
font-size: 12px;
line-height: 16px;
color: var(--k-grey);
}
}
.k-detail-more,
.k-detail-note {
margin: 8px 0 0;

Loading…
Cancel
Save