committed by
GitHub
45 changed files with 21284 additions and 10011 deletions
@ -0,0 +1,88 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
||||
|
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
package org.thingsboard.server.controller; |
||||
|
|
||||
|
import com.fasterxml.jackson.databind.JsonNode; |
||||
|
import lombok.RequiredArgsConstructor; |
||||
|
import org.springframework.http.CacheControl; |
||||
|
import org.springframework.http.ContentDisposition; |
||||
|
import org.springframework.http.HttpHeaders; |
||||
|
import org.springframework.http.HttpStatus; |
||||
|
import org.springframework.http.MediaType; |
||||
|
import org.springframework.http.ResponseEntity; |
||||
|
import org.springframework.security.access.prepost.PreAuthorize; |
||||
|
import org.springframework.web.bind.annotation.DeleteMapping; |
||||
|
import org.springframework.web.bind.annotation.GetMapping; |
||||
|
import org.springframework.web.bind.annotation.PathVariable; |
||||
|
import org.springframework.web.bind.annotation.PostMapping; |
||||
|
import org.springframework.web.bind.annotation.RequestMapping; |
||||
|
import org.springframework.web.bind.annotation.RequestPart; |
||||
|
import org.springframework.web.bind.annotation.ResponseStatus; |
||||
|
import org.springframework.web.bind.annotation.RestController; |
||||
|
import org.springframework.web.multipart.MultipartFile; |
||||
|
import org.thingsboard.server.common.data.exception.ThingsboardException; |
||||
|
import org.thingsboard.server.common.data.permission.Operation; |
||||
|
import org.thingsboard.server.common.data.permission.Resource; |
||||
|
import org.thingsboard.server.queue.util.TbCoreComponent; |
||||
|
import org.thingsboard.server.service.ai.resource.AiResourceService; |
||||
|
import org.thingsboard.server.service.security.model.SecurityUser; |
||||
|
|
||||
|
import java.nio.charset.StandardCharsets; |
||||
|
import java.time.Duration; |
||||
|
import java.util.UUID; |
||||
|
|
||||
|
@RequiredArgsConstructor |
||||
|
@RestController |
||||
|
@TbCoreComponent |
||||
|
@RequestMapping("/api/ai/resources") |
||||
|
class AiResourceController extends BaseController { |
||||
|
|
||||
|
private final AiResourceService aiResourceService; |
||||
|
|
||||
|
@PreAuthorize("hasAuthority('TENANT_ADMIN')") |
||||
|
@GetMapping("/config") |
||||
|
public JsonNode getConfig() throws ThingsboardException { |
||||
|
SecurityUser user = getCurrentUser(); |
||||
|
accessControlService.checkPermission(user, Resource.AI, Operation.READ); |
||||
|
return aiResourceService.getConfig(user); |
||||
|
} |
||||
|
|
||||
|
@PreAuthorize("hasAuthority('TENANT_ADMIN')") |
||||
|
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) |
||||
|
@ResponseStatus(HttpStatus.CREATED) |
||||
|
public JsonNode uploadResource(@RequestPart("file") MultipartFile file) throws ThingsboardException { |
||||
|
SecurityUser user = getCurrentUser(); |
||||
|
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE); |
||||
|
return aiResourceService.upload(file, user); |
||||
|
} |
||||
|
|
||||
|
@PreAuthorize("hasAuthority('TENANT_ADMIN')") |
||||
|
@GetMapping("/{resourceId}") |
||||
|
public ResponseEntity<byte[]> downloadResource(@PathVariable UUID resourceId) throws ThingsboardException { |
||||
|
SecurityUser user = getCurrentUser(); |
||||
|
accessControlService.checkPermission(user, Resource.AI, Operation.READ); |
||||
|
AiResourceService.AiResourceContent content = aiResourceService.download(resourceId, user); |
||||
|
return ResponseEntity.ok() |
||||
|
.contentType(MediaType.parseMediaType(content.mediaType())) |
||||
|
.header(HttpHeaders.CONTENT_DISPOSITION, disposition(content.name())) |
||||
|
.header("X-Content-Type-Options", "nosniff") |
||||
|
.cacheControl(CacheControl.maxAge(Duration.ofHours(1)).cachePrivate()) |
||||
|
.body(content.data()); |
||||
|
} |
||||
|
|
||||
|
private static String disposition(String name) { |
||||
|
ContentDisposition.Builder builder = ContentDisposition.attachment(); |
||||
|
boolean ascii = StandardCharsets.US_ASCII.newEncoder().canEncode(name); |
||||
|
return (ascii ? builder.filename(name) : builder.filename(name, StandardCharsets.UTF_8)).build().toString(); |
||||
|
} |
||||
|
|
||||
|
@PreAuthorize("hasAuthority('TENANT_ADMIN')") |
||||
|
@DeleteMapping("/{resourceId}") |
||||
|
@ResponseStatus(HttpStatus.NO_CONTENT) |
||||
|
public void deleteResource(@PathVariable UUID resourceId) throws ThingsboardException { |
||||
|
SecurityUser user = getCurrentUser(); |
||||
|
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE); |
||||
|
aiResourceService.delete(resourceId, user); |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,24 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
||||
|
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
package org.thingsboard.server.service.ai.resource; |
||||
|
|
||||
|
import com.fasterxml.jackson.databind.JsonNode; |
||||
|
import org.springframework.web.multipart.MultipartFile; |
||||
|
import org.thingsboard.server.common.data.exception.ThingsboardException; |
||||
|
import org.thingsboard.server.service.security.model.SecurityUser; |
||||
|
|
||||
|
import java.util.UUID; |
||||
|
|
||||
|
public interface AiResourceService { |
||||
|
|
||||
|
JsonNode getConfig(SecurityUser user); |
||||
|
|
||||
|
JsonNode upload(MultipartFile file, SecurityUser user) throws ThingsboardException; |
||||
|
|
||||
|
AiResourceContent download(UUID resourceId, SecurityUser user); |
||||
|
|
||||
|
void delete(UUID resourceId, SecurityUser user); |
||||
|
|
||||
|
record AiResourceContent(String name, String mediaType, byte[] data) {} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,84 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
||||
|
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
package org.thingsboard.server.service.ai.resource; |
||||
|
|
||||
|
import com.fasterxml.jackson.databind.JsonNode; |
||||
|
import lombok.RequiredArgsConstructor; |
||||
|
import org.springframework.stereotype.Service; |
||||
|
import org.springframework.web.multipart.MultipartFile; |
||||
|
import org.thingsboard.ai.common.channel.ChannelProtocol; |
||||
|
import org.thingsboard.ai.common.channel.ResourceOperationRequest; |
||||
|
import org.thingsboard.ai.common.channel.ResourceUploadRequest; |
||||
|
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; |
||||
|
import org.thingsboard.server.common.data.exception.ThingsboardException; |
||||
|
import org.thingsboard.server.queue.util.TbCoreComponent; |
||||
|
import org.thingsboard.server.service.ai.TbAiService; |
||||
|
import org.thingsboard.server.service.ai.transport.TbAiOperation; |
||||
|
import org.thingsboard.server.service.ai.transport.TbAiOperations; |
||||
|
import org.thingsboard.server.service.security.model.SecurityUser; |
||||
|
|
||||
|
import java.io.ByteArrayOutputStream; |
||||
|
import java.io.IOException; |
||||
|
import java.io.InputStream; |
||||
|
import java.io.OutputStream; |
||||
|
import java.nio.charset.StandardCharsets; |
||||
|
import java.util.Base64; |
||||
|
import java.util.UUID; |
||||
|
|
||||
|
@Service |
||||
|
@TbCoreComponent |
||||
|
@RequiredArgsConstructor |
||||
|
class DefaultAiResourceService implements AiResourceService { |
||||
|
|
||||
|
private final TbAiService tbAiService; |
||||
|
private final TbAiOperations operations; |
||||
|
|
||||
|
@Override |
||||
|
public JsonNode getConfig(SecurityUser user) { |
||||
|
return tbAiService.process(tokenProvider -> operations.execute( |
||||
|
new TbAiOperation(ChannelProtocol.RESOURCE_CONFIG, null), user, tokenProvider), user, false); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public JsonNode upload(MultipartFile file, SecurityUser user) throws ThingsboardException { |
||||
|
if (file == null || file.isEmpty()) { |
||||
|
throw new ThingsboardException("The file is empty", ThingsboardErrorCode.BAD_REQUEST_PARAMS); |
||||
|
} |
||||
|
long maxSize = getConfig(user).path("maxSize").asLong(0); |
||||
|
if (maxSize > 0 && file.getSize() > maxSize) { |
||||
|
throw new ThingsboardException("The file is too large: " + file.getOriginalFilename(), ThingsboardErrorCode.BAD_REQUEST_PARAMS); |
||||
|
} |
||||
|
String data; |
||||
|
try { |
||||
|
data = base64(file); |
||||
|
} catch (IOException e) { |
||||
|
throw new ThingsboardException("Failed to read the file", e, ThingsboardErrorCode.GENERAL); |
||||
|
} |
||||
|
var request = new ResourceUploadRequest(file.getOriginalFilename(), file.getContentType(), data); |
||||
|
return tbAiService.process(tokenProvider -> operations.execute( |
||||
|
new TbAiOperation(ChannelProtocol.RESOURCE_UPLOAD, request), user, tokenProvider), user, false); |
||||
|
} |
||||
|
|
||||
|
private static String base64(MultipartFile file) throws IOException { |
||||
|
var encoded = new ByteArrayOutputStream((int) Math.min(Integer.MAX_VALUE - 8, (file.getSize() + 2) / 3 * 4)); |
||||
|
try (InputStream in = file.getInputStream(); OutputStream encoder = Base64.getEncoder().wrap(encoded)) { |
||||
|
in.transferTo(encoder); |
||||
|
} |
||||
|
return encoded.toString(StandardCharsets.ISO_8859_1); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public AiResourceContent download(UUID resourceId, SecurityUser user) { |
||||
|
JsonNode content = tbAiService.process(tokenProvider -> operations.execute( |
||||
|
new TbAiOperation(ChannelProtocol.RESOURCE_GET, new ResourceOperationRequest(resourceId)), user, tokenProvider), user, false); |
||||
|
return new AiResourceContent(content.path("name").asText(), content.path("mediaType").asText(), |
||||
|
Base64.getDecoder().decode(content.path("data").asText())); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void delete(UUID resourceId, SecurityUser user) { |
||||
|
tbAiService.process(tokenProvider -> operations.execute( |
||||
|
new TbAiOperation(ChannelProtocol.RESOURCE_DELETE, new ResourceOperationRequest(resourceId)), user, tokenProvider), user, false); |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,224 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
||||
|
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
package org.thingsboard.server.controller; |
||||
|
|
||||
|
import com.fasterxml.jackson.databind.JsonNode; |
||||
|
import com.fasterxml.jackson.databind.node.ObjectNode; |
||||
|
import org.junit.Test; |
||||
|
import org.springframework.http.HttpHeaders; |
||||
|
import org.springframework.http.HttpMethod; |
||||
|
import org.springframework.http.MediaType; |
||||
|
import org.springframework.mock.web.MockMultipartFile; |
||||
|
import org.springframework.test.web.servlet.MvcResult; |
||||
|
import org.springframework.test.web.servlet.ResultActions; |
||||
|
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; |
||||
|
import org.thingsboard.ai.common.channel.ChannelProtocol; |
||||
|
import org.thingsboard.ai.common.channel.ResourceOperationRequest; |
||||
|
import org.thingsboard.ai.common.channel.ResourceUploadRequest; |
||||
|
import org.thingsboard.ai.common.channel.SolutionChatRequest; |
||||
|
import org.thingsboard.ai.common.data.solution.SolutionStep; |
||||
|
import org.thingsboard.common.util.JacksonUtil; |
||||
|
import org.thingsboard.server.dao.service.DaoSqlTest; |
||||
|
import org.thingsboard.server.service.ai.transport.TbAiTurnContext; |
||||
|
|
||||
|
import java.nio.charset.StandardCharsets; |
||||
|
import java.util.Base64; |
||||
|
import java.util.List; |
||||
|
import java.util.UUID; |
||||
|
|
||||
|
import static org.assertj.core.api.Assertions.assertThat; |
||||
|
import static org.hamcrest.Matchers.equalTo; |
||||
|
import static org.mockito.ArgumentMatchers.any; |
||||
|
import static org.mockito.ArgumentMatchers.argThat; |
||||
|
import static org.mockito.Mockito.never; |
||||
|
import static org.mockito.Mockito.verify; |
||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; |
||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; |
||||
|
|
||||
|
@DaoSqlTest |
||||
|
public class AiResourceControllerTest extends AbstractAiControllerTest { |
||||
|
|
||||
|
private static final byte[] PNG = Base64.getDecoder().decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="); |
||||
|
|
||||
|
@Test |
||||
|
public void shouldForwardTheFileBase64Encoded_whenUploadingAResource() throws Exception { |
||||
|
// GIVEN
|
||||
|
loginTenantAdmin(); |
||||
|
UUID resourceId = UUID.randomUUID(); |
||||
|
ObjectNode info = resourceInfo(resourceId, "chart.png", "image/png", PNG.length); |
||||
|
var request = new ResourceUploadRequest("chart.png", "image/png", Base64.getEncoder().encodeToString(PNG)); |
||||
|
givenOperation(ChannelProtocol.RESOURCE_CONFIG, null, success(limits(5 * 1024 * 1024))); |
||||
|
givenOperation(ChannelProtocol.RESOURCE_UPLOAD, request, success(info)); |
||||
|
|
||||
|
// WHEN
|
||||
|
JsonNode result = readResponse(upload("chart.png", "image/png", PNG).andExpect(status().isCreated()), JsonNode.class); |
||||
|
|
||||
|
// THEN
|
||||
|
assertThat(result).isEqualTo(info); |
||||
|
TbAiTurnContext context = verifyOperation(ChannelProtocol.RESOURCE_UPLOAD, request); |
||||
|
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider()); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void shouldRejectAFileOverTheAiServiceLimit_withoutUploadingIt() throws Exception { |
||||
|
// GIVEN
|
||||
|
loginTenantAdmin(); |
||||
|
givenOperation(ChannelProtocol.RESOURCE_CONFIG, null, success(limits(1024))); |
||||
|
|
||||
|
// WHEN
|
||||
|
upload("huge.png", "image/png", new byte[1025]) |
||||
|
.andExpect(status().isBadRequest()) |
||||
|
.andExpect(statusReason(equalTo("The file is too large: huge.png"))); |
||||
|
|
||||
|
// THEN
|
||||
|
verify(tbAiOperations, never()).execute(argThat(operation -> operation != null && ChannelProtocol.RESOURCE_UPLOAD.equals(operation.type())), |
||||
|
any(TbAiTurnContext.class)); |
||||
|
} |
||||
|
|
||||
|
static JsonNode limits(long maxSize) { |
||||
|
return JacksonUtil.newObjectNode().put("maxSize", maxSize).put("maxPerMessage", 5); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void shouldServeTheFileWithItsTypeAndName_whenDownloadingAResource() throws Exception { |
||||
|
// GIVEN
|
||||
|
loginTenantAdmin(); |
||||
|
UUID resourceId = UUID.randomUUID(); |
||||
|
ObjectNode content = JacksonUtil.newObjectNode() |
||||
|
.put("name", "chart.png") |
||||
|
.put("mediaType", "image/png") |
||||
|
.put("data", Base64.getEncoder().encodeToString(PNG)); |
||||
|
givenOperation(ChannelProtocol.RESOURCE_GET, new ResourceOperationRequest(resourceId), success(content)); |
||||
|
|
||||
|
// WHEN
|
||||
|
MvcResult result = doGet("/api/ai/resources/" + resourceId).andExpect(status().isOk()).andReturn(); |
||||
|
|
||||
|
// THEN
|
||||
|
assertThat(result.getResponse().getContentAsByteArray()).isEqualTo(PNG); |
||||
|
assertThat(result.getResponse().getContentType()).isEqualTo("image/png"); |
||||
|
assertThat(result.getResponse().getHeader(HttpHeaders.CONTENT_DISPOSITION)).isEqualTo("attachment; filename=\"chart.png\""); |
||||
|
assertThat(result.getResponse().getHeader("X-Content-Type-Options")).isEqualTo("nosniff"); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void shouldDeleteAnUnsentResource() throws Exception { |
||||
|
// GIVEN
|
||||
|
loginTenantAdmin(); |
||||
|
UUID resourceId = UUID.randomUUID(); |
||||
|
givenOperation(ChannelProtocol.RESOURCE_DELETE, new ResourceOperationRequest(resourceId), success()); |
||||
|
|
||||
|
// WHEN
|
||||
|
doDelete("/api/ai/resources/" + resourceId).andExpect(status().isNoContent()); |
||||
|
|
||||
|
// THEN
|
||||
|
verifyOperation(ChannelProtocol.RESOURCE_DELETE, new ResourceOperationRequest(resourceId)); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void shouldKeepTheAiServiceStatus_whenAResourceIsMissingOrInvalid() throws Exception { |
||||
|
// GIVEN
|
||||
|
loginTenantAdmin(); |
||||
|
UUID resourceId = UUID.randomUUID(); |
||||
|
givenOperation(ChannelProtocol.RESOURCE_GET, new ResourceOperationRequest(resourceId), failure(404, "Resource not found")); |
||||
|
givenOperation(ChannelProtocol.RESOURCE_DELETE, new ResourceOperationRequest(resourceId), failure(404, "Resource not found or already sent")); |
||||
|
|
||||
|
// WHEN
|
||||
|
MvcResult download = doGet("/api/ai/resources/" + resourceId).andReturn(); |
||||
|
MvcResult delete = doDelete("/api/ai/resources/" + resourceId).andReturn(); |
||||
|
|
||||
|
// THEN
|
||||
|
assertThat(download.getResponse().getStatus()).isEqualTo(404); |
||||
|
assertThat(delete.getResponse().getStatus()).isEqualTo(404); |
||||
|
assertThat(delete.getResponse().getContentAsString()).contains("Resource not found or already sent"); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void shouldReturnTheAcceptedFiles_whenGettingTheConfig() throws Exception { |
||||
|
// GIVEN
|
||||
|
loginTenantAdmin(); |
||||
|
JsonNode limits = JacksonUtil.toJsonNode(""" |
||||
|
{"maxSize": 5242880, "maxPerMessage": 5, "mediaTypes": ["image/png"], "extensions": [".png"]} |
||||
|
"""); |
||||
|
givenOperation(ChannelProtocol.RESOURCE_CONFIG, null, success(limits)); |
||||
|
|
||||
|
// WHEN
|
||||
|
JsonNode result = doGet("/api/ai/resources/config", JsonNode.class); |
||||
|
|
||||
|
// THEN
|
||||
|
assertThat(result).isEqualTo(limits); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void shouldSendTheAttachedResources_whenSendingASolutionMessage() throws Exception { |
||||
|
// GIVEN
|
||||
|
loginTenantAdmin(); |
||||
|
UUID solutionId = UUID.randomUUID(); |
||||
|
UUID resourceId = UUID.randomUUID(); |
||||
|
var request = new SolutionChatRequest(solutionId, SolutionStep.DASHBOARDS_CONFIGURATION, "Like this", List.of(resourceId)); |
||||
|
ObjectNode solution = JacksonUtil.newObjectNode().put("id", solutionId.toString()); |
||||
|
givenOperation(ChannelProtocol.SOLUTION_CHAT, request, success(solution)); |
||||
|
|
||||
|
// WHEN
|
||||
|
JsonNode result = readResponse(solutionMessage(solutionId, SolutionStep.DASHBOARDS_CONFIGURATION, """ |
||||
|
{"message": "Like this", "resources": ["%s"]} |
||||
|
""".formatted(resourceId)).andExpect(status().isOk()), JsonNode.class); |
||||
|
|
||||
|
// THEN
|
||||
|
assertThat(result).isEqualTo(solution); |
||||
|
verifyOperation(ChannelProtocol.SOLUTION_CHAT, request); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void shouldRejectASolutionMessage_whenItHasNeitherTextNorFiles() throws Exception { |
||||
|
// GIVEN
|
||||
|
loginTenantAdmin(); |
||||
|
|
||||
|
// WHEN
|
||||
|
solutionMessage(UUID.randomUUID(), SolutionStep.INITIAL_CONFIGURATION, """ |
||||
|
{"message": " ", "resources": []} |
||||
|
""") |
||||
|
.andExpect(status().isBadRequest()) |
||||
|
.andExpect(statusReason(equalTo("Message cannot be blank"))); |
||||
|
|
||||
|
// THEN
|
||||
|
verifyNoAiCalls(); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void shouldReturnForbiddenAndNotCallClient_whenCustomerUserUploads() throws Exception { |
||||
|
// GIVEN
|
||||
|
loginCustomerUser(); |
||||
|
|
||||
|
// WHEN
|
||||
|
upload("chart.png", "image/png", PNG) |
||||
|
.andExpect(status().isForbidden()) |
||||
|
.andExpect(statusReason(equalTo(msgErrorPermission))); |
||||
|
|
||||
|
// THEN
|
||||
|
verifyNoAiCalls(); |
||||
|
} |
||||
|
|
||||
|
private ResultActions upload(String name, String mediaType, byte[] content) throws Exception { |
||||
|
var request = MockMvcRequestBuilders.multipart(HttpMethod.POST, "/api/ai/resources") |
||||
|
.file(new MockMultipartFile("file", name, mediaType, content)); |
||||
|
setJwtToken(request); |
||||
|
return mockMvc.perform(request); |
||||
|
} |
||||
|
|
||||
|
private ResultActions solutionMessage(UUID solutionId, SolutionStep step, String body) throws Exception { |
||||
|
var request = post("/api/ai/solution/" + solutionId + "/" + step + "/messages") |
||||
|
.contentType(MediaType.APPLICATION_JSON) |
||||
|
.content(body.getBytes(StandardCharsets.UTF_8)); |
||||
|
setJwtToken(request); |
||||
|
return mockMvc.perform(request); |
||||
|
} |
||||
|
|
||||
|
private static ObjectNode resourceInfo(UUID id, String name, String mediaType, int size) { |
||||
|
return JacksonUtil.newObjectNode() |
||||
|
.put("id", id.toString()) |
||||
|
.put("name", name) |
||||
|
.put("mediaType", mediaType) |
||||
|
.put("size", size); |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,218 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
||||
|
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
import { Injectable } from '@angular/core'; |
||||
|
import { HttpClient, HttpErrorResponse, HttpEvent, HttpEventType } from '@angular/common/http'; |
||||
|
import { defaultHttpOptions, defaultHttpUploadOptions } from '@core/http/http-utils'; |
||||
|
import { from, Observable, of, Subscription, throwError } from 'rxjs'; |
||||
|
import { catchError, filter, finalize, map, shareReplay, switchMap } from 'rxjs/operators'; |
||||
|
import { AiResourceConfig, AiResourceInfo } from '@shared/models/ai-chat.models'; |
||||
|
|
||||
|
export type AiResourceUploadEvent = |
||||
|
{ type: 'progress'; progress: number } | |
||||
|
{ type: 'done'; resource: AiResourceInfo }; |
||||
|
|
||||
|
interface CachedUrl { |
||||
|
url$: Observable<string>; |
||||
|
url?: string; |
||||
|
size: number; |
||||
|
dropped?: boolean; |
||||
|
} |
||||
|
|
||||
|
const MAX_CONCURRENT_FETCHES = 3; |
||||
|
const MAX_CACHED_URLS = 40; |
||||
|
const MAX_CACHED_BYTES = 64 * 1024 * 1024; |
||||
|
|
||||
|
@Injectable({ |
||||
|
providedIn: 'root' |
||||
|
}) |
||||
|
export class AiResourceService { |
||||
|
|
||||
|
private config$: Observable<AiResourceConfig | null>; |
||||
|
|
||||
|
private readonly urls = new Map<string, CachedUrl>(); |
||||
|
|
||||
|
private readonly waitingFetches: Array<() => void> = []; |
||||
|
|
||||
|
private activeFetches = 0; |
||||
|
|
||||
|
constructor(private http: HttpClient) { |
||||
|
} |
||||
|
|
||||
|
getConfig(): Observable<AiResourceConfig | null> { |
||||
|
if (!this.config$) { |
||||
|
this.config$ = this.http.get<AiResourceConfig>('/api/ai/resources/config', defaultHttpOptions(true, true)).pipe( |
||||
|
catchError(() => { |
||||
|
this.config$ = null; |
||||
|
return of(null); |
||||
|
}), |
||||
|
shareReplay(1) |
||||
|
); |
||||
|
} |
||||
|
return this.config$; |
||||
|
} |
||||
|
|
||||
|
upload(file: File): Observable<AiResourceUploadEvent> { |
||||
|
const formData = new FormData(); |
||||
|
formData.append('file', file, file.name); |
||||
|
return this.http.post<AiResourceInfo>('/api/ai/resources', formData, { |
||||
|
...defaultHttpUploadOptions(true, true), |
||||
|
observe: 'events', |
||||
|
reportProgress: true |
||||
|
}).pipe( |
||||
|
filter((event: HttpEvent<AiResourceInfo>) => event.type === HttpEventType.UploadProgress || event.type === HttpEventType.Response), |
||||
|
map((event: HttpEvent<AiResourceInfo>): AiResourceUploadEvent => { |
||||
|
if (event.type === HttpEventType.UploadProgress) { |
||||
|
return {type: 'progress', progress: event.total ? Math.round(100 * event.loaded / event.total) : 0}; |
||||
|
} |
||||
|
return {type: 'done', resource: (event as any).body as AiResourceInfo}; |
||||
|
}) |
||||
|
); |
||||
|
} |
||||
|
|
||||
|
delete(resourceId: string): Observable<void> { |
||||
|
this.forget(resourceId); |
||||
|
return this.http.delete<void>(`/api/ai/resources/${resourceId}`, defaultHttpOptions(true, true)); |
||||
|
} |
||||
|
|
||||
|
rememberUrl(resourceId: string, url: string, size: number): void { |
||||
|
this.forget(resourceId); |
||||
|
this.urls.set(resourceId, {url$: of(url), url, size}); |
||||
|
this.evict(resourceId); |
||||
|
} |
||||
|
|
||||
|
getUrl(resourceId: string): Observable<string> { |
||||
|
const cached = this.urls.get(resourceId); |
||||
|
if (cached) { |
||||
|
this.urls.delete(resourceId); |
||||
|
this.urls.set(resourceId, cached); |
||||
|
return cached.url$; |
||||
|
} |
||||
|
const entry: CachedUrl = {url$: null, size: 0}; |
||||
|
entry.url$ = this.fetch(resourceId).pipe( |
||||
|
map(blob => { |
||||
|
const url = URL.createObjectURL(blob); |
||||
|
if (entry.dropped) { |
||||
|
setTimeout(() => URL.revokeObjectURL(url)); |
||||
|
} else { |
||||
|
entry.url = url; |
||||
|
entry.size = blob.size; |
||||
|
this.evict(resourceId); |
||||
|
} |
||||
|
return url; |
||||
|
}), |
||||
|
catchError(error => { |
||||
|
if (this.urls.get(resourceId) === entry) { |
||||
|
this.urls.delete(resourceId); |
||||
|
} |
||||
|
throw error; |
||||
|
}), |
||||
|
shareReplay(1) |
||||
|
); |
||||
|
this.urls.set(resourceId, entry); |
||||
|
return entry.url$; |
||||
|
} |
||||
|
|
||||
|
download(resource: AiResourceInfo): Observable<void> { |
||||
|
const cachedUrl = this.urls.get(resource.id)?.url; |
||||
|
if (cachedUrl) { |
||||
|
this.save(cachedUrl, resource.name); |
||||
|
return of(undefined); |
||||
|
} |
||||
|
return this.fetch(resource.id).pipe( |
||||
|
map(blob => { |
||||
|
const url = URL.createObjectURL(blob); |
||||
|
this.save(url, resource.name); |
||||
|
setTimeout(() => URL.revokeObjectURL(url)); |
||||
|
}) |
||||
|
); |
||||
|
} |
||||
|
|
||||
|
private save(url: string, name: string): void { |
||||
|
const link = document.createElement('a'); |
||||
|
link.href = url; |
||||
|
link.download = name; |
||||
|
document.body.appendChild(link); |
||||
|
link.click(); |
||||
|
link.remove(); |
||||
|
} |
||||
|
|
||||
|
private fetch(resourceId: string): Observable<Blob> { |
||||
|
const request$ = this.http.get(`/api/ai/resources/${resourceId}`, {...defaultHttpOptions(true, true), responseType: 'blob'}).pipe( |
||||
|
catchError(error => this.readErrorBody(error)) |
||||
|
); |
||||
|
return new Observable<Blob>(subscriber => { |
||||
|
let subscription: Subscription; |
||||
|
let finished = false; |
||||
|
const finish = () => { |
||||
|
if (!finished) { |
||||
|
finished = true; |
||||
|
this.activeFetches--; |
||||
|
this.waitingFetches.shift()?.(); |
||||
|
} |
||||
|
}; |
||||
|
const start = () => { |
||||
|
this.activeFetches++; |
||||
|
subscription = request$.pipe(finalize(finish)).subscribe(subscriber); |
||||
|
}; |
||||
|
if (this.activeFetches < MAX_CONCURRENT_FETCHES) { |
||||
|
start(); |
||||
|
} else { |
||||
|
this.waitingFetches.push(start); |
||||
|
} |
||||
|
return () => { |
||||
|
const index = this.waitingFetches.indexOf(start); |
||||
|
if (index >= 0) { |
||||
|
this.waitingFetches.splice(index, 1); |
||||
|
} |
||||
|
subscription?.unsubscribe(); |
||||
|
}; |
||||
|
}); |
||||
|
} |
||||
|
|
||||
|
private readErrorBody(error: any): Observable<never> { |
||||
|
if (!(error instanceof HttpErrorResponse) || !(error.error instanceof Blob)) { |
||||
|
return throwError(() => error); |
||||
|
} |
||||
|
return from(error.error.text()).pipe( |
||||
|
catchError(() => of('')), |
||||
|
switchMap(text => throwError(() => new HttpErrorResponse({ |
||||
|
error: text || null, |
||||
|
headers: error.headers, |
||||
|
status: error.status, |
||||
|
statusText: error.statusText, |
||||
|
url: error.url ?? undefined |
||||
|
}))) |
||||
|
); |
||||
|
} |
||||
|
|
||||
|
private forget(resourceId: string): void { |
||||
|
const entry = this.urls.get(resourceId); |
||||
|
if (entry) { |
||||
|
this.urls.delete(resourceId); |
||||
|
this.release(entry); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private release(entry: CachedUrl): void { |
||||
|
entry.dropped = true; |
||||
|
if (entry.url) { |
||||
|
URL.revokeObjectURL(entry.url); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private evict(keep: string): void { |
||||
|
let bytes = 0; |
||||
|
this.urls.forEach(entry => bytes += entry.size); |
||||
|
for (const [resourceId, entry] of this.urls) { |
||||
|
if (this.urls.size <= MAX_CACHED_URLS && bytes <= MAX_CACHED_BYTES) { |
||||
|
break; |
||||
|
} |
||||
|
if (resourceId !== keep && entry.url) { |
||||
|
this.urls.delete(resourceId); |
||||
|
bytes -= entry.size; |
||||
|
this.release(entry); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,32 @@ |
|||||
|
<!-- |
||||
|
|
||||
|
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
||||
|
SPDX-License-Identifier: BUSL-1.1 |
||||
|
|
||||
|
--> |
||||
|
<mat-toolbar class="flex items-center gap-2"> |
||||
|
<h2 class="preview-title">{{ data.resource.name }}</h2> |
||||
|
<span class="flex-1"></span> |
||||
|
<button mat-icon-button type="button" (click)="download()" |
||||
|
[matTooltip]="'action.download' | translate" matTooltipPosition="above"> |
||||
|
<mat-icon>download</mat-icon> |
||||
|
</button> |
||||
|
<button mat-icon-button type="button" (click)="close()" |
||||
|
[matTooltip]="'action.close' | translate" matTooltipPosition="above"> |
||||
|
<mat-icon>close</mat-icon> |
||||
|
</button> |
||||
|
</mat-toolbar> |
||||
|
<div mat-dialog-content class="preview-content" tb-toast toastTarget="aiAttachmentPreview"> |
||||
|
@if (preview$ | async; as preview) { |
||||
|
@if (preview.url) { |
||||
|
<img [src]="preview.url" [alt]="data.resource.name"> |
||||
|
} @else { |
||||
|
<div class="preview-error"> |
||||
|
<mat-icon>broken_image</mat-icon> |
||||
|
<span>{{ preview.error }}</span> |
||||
|
</div> |
||||
|
} |
||||
|
} @else { |
||||
|
<mat-progress-spinner diameter="40" mode="indeterminate"></mat-progress-spinner> |
||||
|
} |
||||
|
</div> |
||||
@ -0,0 +1,50 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
||||
|
// SPDX-License-Identifier: BUSL-1.1 |
||||
|
:host { |
||||
|
display: flex; |
||||
|
flex-direction: column; |
||||
|
min-width: min(360px, 90vw); |
||||
|
max-height: 90vh; |
||||
|
|
||||
|
.preview-title { |
||||
|
margin: 0; |
||||
|
font-size: 16px; |
||||
|
overflow: hidden; |
||||
|
white-space: nowrap; |
||||
|
text-overflow: ellipsis; |
||||
|
} |
||||
|
|
||||
|
.preview-content { |
||||
|
display: flex; |
||||
|
align-items: center; |
||||
|
justify-content: center; |
||||
|
padding: 0 16px 16px; |
||||
|
max-height: calc(90vh - 64px); |
||||
|
overflow: auto; |
||||
|
|
||||
|
img { |
||||
|
max-width: 100%; |
||||
|
max-height: calc(90vh - 96px); |
||||
|
object-fit: contain; |
||||
|
border-radius: 8px; |
||||
|
} |
||||
|
|
||||
|
.preview-error { |
||||
|
display: flex; |
||||
|
flex-direction: column; |
||||
|
align-items: center; |
||||
|
gap: 8px; |
||||
|
padding: 32px 16px; |
||||
|
max-width: 360px; |
||||
|
color: rgba(0, 0, 0, 0.54); |
||||
|
text-align: center; |
||||
|
|
||||
|
mat-icon { |
||||
|
width: 40px; |
||||
|
height: 40px; |
||||
|
font-size: 40px; |
||||
|
color: rgba(0, 0, 0, 0.38); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,74 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
||||
|
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
import { Component, Inject, SecurityContext } from '@angular/core'; |
||||
|
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; |
||||
|
import { Router } from '@angular/router'; |
||||
|
import { Store } from '@ngrx/store'; |
||||
|
import { TranslateService } from '@ngx-translate/core'; |
||||
|
import { DomSanitizer } from '@angular/platform-browser'; |
||||
|
import { Observable, of } from 'rxjs'; |
||||
|
import { catchError, map } from 'rxjs/operators'; |
||||
|
import { AppState } from '@core/core.state'; |
||||
|
import { DialogComponent } from '@shared/components/dialog.component'; |
||||
|
import { ActionNotificationShow } from '@core/notification/notification.actions'; |
||||
|
|
||||
|
import { aiServerMessage } from '@home/components/ai/ai-attachment.models'; |
||||
|
import { AiResourceService } from '@core/http/ai-resource.service'; |
||||
|
import { AiResourceInfo } from '@shared/models/ai-chat.models'; |
||||
|
|
||||
|
export interface AiAttachmentPreviewDialogData { |
||||
|
resource: AiResourceInfo; |
||||
|
} |
||||
|
|
||||
|
interface AiAttachmentPreview { |
||||
|
url?: string; |
||||
|
error?: string; |
||||
|
} |
||||
|
|
||||
|
@Component({ |
||||
|
selector: 'tb-ai-attachment-preview-dialog', |
||||
|
templateUrl: './ai-attachment-preview-dialog.component.html', |
||||
|
styleUrls: ['./ai-attachment-preview-dialog.component.scss'], |
||||
|
standalone: false |
||||
|
}) |
||||
|
export class AiAttachmentPreviewDialogComponent extends DialogComponent<AiAttachmentPreviewDialogComponent> { |
||||
|
|
||||
|
readonly preview$: Observable<AiAttachmentPreview>; |
||||
|
|
||||
|
constructor(protected store: Store<AppState>, |
||||
|
protected router: Router, |
||||
|
public dialogRef: MatDialogRef<AiAttachmentPreviewDialogComponent>, |
||||
|
@Inject(MAT_DIALOG_DATA) public data: AiAttachmentPreviewDialogData, |
||||
|
private aiResourceService: AiResourceService, |
||||
|
private translate: TranslateService, |
||||
|
private sanitizer: DomSanitizer) { |
||||
|
super(store, router, dialogRef); |
||||
|
this.preview$ = this.aiResourceService.getUrl(data.resource.id).pipe( |
||||
|
map(url => ({url})), |
||||
|
catchError(error => of({error: this.errorMessage(error)})) |
||||
|
); |
||||
|
} |
||||
|
|
||||
|
download(): void { |
||||
|
this.aiResourceService.download(this.data.resource).subscribe({ |
||||
|
error: error => this.store.dispatch(new ActionNotificationShow({ |
||||
|
message: this.errorMessage(error), |
||||
|
target: 'aiAttachmentPreview', |
||||
|
modern: true, |
||||
|
type: 'error', |
||||
|
verticalPosition: 'bottom', |
||||
|
horizontalPosition: 'center' |
||||
|
})) |
||||
|
}); |
||||
|
} |
||||
|
|
||||
|
close(): void { |
||||
|
this.dialogRef.close(); |
||||
|
} |
||||
|
|
||||
|
private errorMessage(error: unknown): string { |
||||
|
const message = aiServerMessage(error); |
||||
|
return message ? this.sanitizer.sanitize(SecurityContext.HTML, message) ?? message : this.translate.instant('ai-assistant.attachment-load-failed'); |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,189 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
||||
|
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
import { HttpErrorResponse } from '@angular/common/http'; |
||||
|
import { AI_IMAGE_MEDIA_TYPES } from '@shared/models/ai-chat.models'; |
||||
|
|
||||
|
const MAX_IMAGE_SIDE = 2560; |
||||
|
const MIN_SVG_SIDE = 1024; |
||||
|
const SVG_MEDIA_TYPE = 'image/svg+xml'; |
||||
|
const SVG_UNITS: Record<string, number> = {'': 1, px: 1, pt: 4 / 3, pc: 16, in: 96, cm: 96 / 2.54, mm: 96 / 25.4}; |
||||
|
|
||||
|
export const AI_SVG_EXTENSION = '.svg'; |
||||
|
|
||||
|
export interface AiAttachmentKind { |
||||
|
icon: string; |
||||
|
label: string; |
||||
|
} |
||||
|
|
||||
|
export const aiAttachmentKind = (mediaType: string, name: string): AiAttachmentKind => { |
||||
|
const extension = name.split('.').pop()?.toLowerCase(); |
||||
|
if (mediaType?.startsWith('image/')) { |
||||
|
return {icon: 'image', label: 'ai-assistant.file-kind.image'}; |
||||
|
} |
||||
|
if (mediaType === 'application/pdf' || extension === 'pdf') { |
||||
|
return {icon: 'picture_as_pdf', label: 'ai-assistant.file-kind.pdf'}; |
||||
|
} |
||||
|
if (extension === 'xlsx' || extension === 'csv') { |
||||
|
return {icon: 'table_chart', label: 'ai-assistant.file-kind.table'}; |
||||
|
} |
||||
|
if (extension === 'docx') { |
||||
|
return {icon: 'description', label: 'ai-assistant.file-kind.document'}; |
||||
|
} |
||||
|
if (extension === 'pptx') { |
||||
|
return {icon: 'slideshow', label: 'ai-assistant.file-kind.slides'}; |
||||
|
} |
||||
|
if (extension === 'json') { |
||||
|
return {icon: 'data_object', label: 'ai-assistant.file-kind.json'}; |
||||
|
} |
||||
|
if (['txt', 'log', 'md', 'xml', 'yaml', 'yml', 'html', 'htm'].includes(extension)) { |
||||
|
return {icon: 'description', label: 'ai-assistant.file-kind.text'}; |
||||
|
} |
||||
|
return {icon: 'attach_file', label: 'ai-assistant.file-kind.file'}; |
||||
|
}; |
||||
|
|
||||
|
export const formatAiFileSize = (bytes: number): string => bytes >= 1048576 |
||||
|
? (bytes / 1048576).toFixed(1).replace(/\.0$/, '') + ' MB' |
||||
|
: Math.max(1, Math.round(bytes / 1024)) + ' KB'; |
||||
|
|
||||
|
export const aiAttachmentExtension = (name: string): string => { |
||||
|
const dot = name.lastIndexOf('.'); |
||||
|
return dot > 0 ? name.substring(dot + 1).toUpperCase() : ''; |
||||
|
}; |
||||
|
|
||||
|
export const isAiSvg = (file: File): boolean => file.type === SVG_MEDIA_TYPE || file.name.toLowerCase().endsWith(AI_SVG_EXTENSION); |
||||
|
|
||||
|
export const isAiAttachmentAccepted = (file: File, extensions: string[]): boolean => { |
||||
|
const name = file.name.toLowerCase(); |
||||
|
return isAiSvg(file) || extensions.some(extension => name.endsWith(extension.toLowerCase())); |
||||
|
}; |
||||
|
|
||||
|
export const namePastedImage = (file: File): File => { |
||||
|
if (!AI_IMAGE_MEDIA_TYPES.includes(file.type) || (file.name && file.name !== 'image.png')) { |
||||
|
return file; |
||||
|
} |
||||
|
const stamp = new Date().toISOString().replace(/[-:]/g, '').replace('T', '-').substring(0, 15); |
||||
|
const extension = file.type === 'image/jpeg' ? 'jpg' : file.type.split('/')[1]; |
||||
|
return new File([file], `screenshot-${stamp}.${extension}`, {type: file.type, lastModified: file.lastModified}); |
||||
|
}; |
||||
|
|
||||
|
const loadImage = (file: File): Promise<HTMLImageElement> => new Promise((resolve, reject) => { |
||||
|
const url = URL.createObjectURL(file); |
||||
|
const image = new Image(); |
||||
|
image.onload = () => { |
||||
|
URL.revokeObjectURL(url); |
||||
|
resolve(image); |
||||
|
}; |
||||
|
image.onerror = () => { |
||||
|
URL.revokeObjectURL(url); |
||||
|
reject(new Error('Image could not be decoded')); |
||||
|
}; |
||||
|
image.src = url; |
||||
|
}); |
||||
|
|
||||
|
const encode = (canvas: HTMLCanvasElement, type: string, quality?: number): Promise<Blob> => new Promise((resolve, reject) => |
||||
|
canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error('Image could not be encoded')), type, quality)); |
||||
|
|
||||
|
export const fitAiImage = async (file: File, maxSize: number): Promise<File> => { |
||||
|
if (!AI_IMAGE_MEDIA_TYPES.includes(file.type)) { |
||||
|
return file; |
||||
|
} |
||||
|
let image: HTMLImageElement; |
||||
|
try { |
||||
|
image = await loadImage(file); |
||||
|
} catch { |
||||
|
return file; |
||||
|
} |
||||
|
const scale = Math.min(1, MAX_IMAGE_SIDE / Math.max(image.naturalWidth, image.naturalHeight)); |
||||
|
if (scale === 1 && file.size <= maxSize) { |
||||
|
return file; |
||||
|
} |
||||
|
const canvas = document.createElement('canvas'); |
||||
|
canvas.width = Math.max(1, Math.round(image.naturalWidth * scale)); |
||||
|
canvas.height = Math.max(1, Math.round(image.naturalHeight * scale)); |
||||
|
const context = canvas.getContext('2d'); |
||||
|
if (file.type === 'image/jpeg') { |
||||
|
context.fillStyle = '#fff'; |
||||
|
context.fillRect(0, 0, canvas.width, canvas.height); |
||||
|
} |
||||
|
context.drawImage(image, 0, 0, canvas.width, canvas.height); |
||||
|
let blob = await encode(canvas, file.type, 0.92); |
||||
|
let type = file.type; |
||||
|
if (blob.size > maxSize) { |
||||
|
context.globalCompositeOperation = 'destination-over'; |
||||
|
context.fillStyle = '#fff'; |
||||
|
context.fillRect(0, 0, canvas.width, canvas.height); |
||||
|
blob = await encode(canvas, 'image/jpeg', 0.85); |
||||
|
type = 'image/jpeg'; |
||||
|
} |
||||
|
if (blob.size >= file.size && scale === 1) { |
||||
|
return file; |
||||
|
} |
||||
|
const base = file.name.replace(/\.[^.]+$/, ''); |
||||
|
const name = type === file.type ? file.name : `${base}.jpg`; |
||||
|
return new File([blob], name, {type, lastModified: file.lastModified}); |
||||
|
}; |
||||
|
|
||||
|
const svgLength = (value: string | null): number | null => { |
||||
|
const match = value?.trim().match(/^([0-9]*\.?[0-9]+(?:e[-+]?[0-9]+)?)\s*(px|pt|pc|in|cm|mm)?$/i); |
||||
|
const length = match ? parseFloat(match[1]) * SVG_UNITS[(match[2] ?? '').toLowerCase()] : NaN; |
||||
|
return length > 0 ? length : null; |
||||
|
}; |
||||
|
|
||||
|
export const svgToAiImage = async (file: File, maxSize: number): Promise<File> => { |
||||
|
const document = new DOMParser().parseFromString(await file.text(), SVG_MEDIA_TYPE); |
||||
|
const svg = document.documentElement; |
||||
|
if (svg.localName !== 'svg' || document.getElementsByTagName('parsererror').length) { |
||||
|
throw new Error('Not an SVG image'); |
||||
|
} |
||||
|
Array.from(document.getElementsByTagNameNS('*', 'foreignObject')).forEach(node => node.remove()); |
||||
|
const viewBox = (svg.getAttribute('viewBox') ?? '').trim().split(/[\s,]+/).map(Number); |
||||
|
const hasViewBox = viewBox.length === 4 && viewBox[2] > 0 && viewBox[3] > 0; |
||||
|
let width = svgLength(svg.getAttribute('width')) ?? (hasViewBox ? viewBox[2] : null); |
||||
|
let height = svgLength(svg.getAttribute('height')) ?? (hasViewBox ? viewBox[3] : null); |
||||
|
if (!width || !height) { |
||||
|
width = width ?? height ?? MIN_SVG_SIDE; |
||||
|
height = height ?? width; |
||||
|
} |
||||
|
if (!hasViewBox) { |
||||
|
svg.setAttribute('viewBox', `0 0 ${width} ${height}`); |
||||
|
} |
||||
|
const scale = Math.min(MAX_IMAGE_SIDE / Math.max(width, height), Math.max(1, MIN_SVG_SIDE / Math.max(width, height))); |
||||
|
const canvas = window.document.createElement('canvas'); |
||||
|
canvas.width = Math.max(1, Math.round(width * scale)); |
||||
|
canvas.height = Math.max(1, Math.round(height * scale)); |
||||
|
svg.setAttribute('width', String(canvas.width)); |
||||
|
svg.setAttribute('height', String(canvas.height)); |
||||
|
const image = await loadImage(new File([new XMLSerializer().serializeToString(document)], file.name, {type: SVG_MEDIA_TYPE})); |
||||
|
const context = canvas.getContext('2d'); |
||||
|
context.fillStyle = '#fff'; |
||||
|
context.fillRect(0, 0, canvas.width, canvas.height); |
||||
|
context.drawImage(image, 0, 0, canvas.width, canvas.height); |
||||
|
let blob = await encode(canvas, 'image/png'); |
||||
|
let type = 'image/png'; |
||||
|
if (blob.size > maxSize) { |
||||
|
blob = await encode(canvas, 'image/jpeg', 0.85); |
||||
|
type = 'image/jpeg'; |
||||
|
} |
||||
|
const base = file.name.replace(/\.[^.]+$/, ''); |
||||
|
return new File([blob], `${base}.${type === 'image/png' ? 'png' : 'jpg'}`, {type, lastModified: file.lastModified}); |
||||
|
}; |
||||
|
|
||||
|
export function aiServerMessage(error: unknown): string | undefined { |
||||
|
if (!(error instanceof HttpErrorResponse)) { |
||||
|
return undefined; |
||||
|
} |
||||
|
let body: unknown = error.error; |
||||
|
if (typeof body === 'string') { |
||||
|
const text = body.trim(); |
||||
|
if (!text || text.startsWith('<')) { |
||||
|
return undefined; |
||||
|
} |
||||
|
try { |
||||
|
body = JSON.parse(text); |
||||
|
} catch { |
||||
|
return text; |
||||
|
} |
||||
|
} |
||||
|
const message = body && typeof body === 'object' ? (body as {message?: unknown}).message : undefined; |
||||
|
return typeof message === 'string' && message.trim() ? message.trim() : undefined; |
||||
|
} |
||||
@ -0,0 +1,30 @@ |
|||||
|
<!-- |
||||
|
|
||||
|
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
||||
|
SPDX-License-Identifier: BUSL-1.1 |
||||
|
|
||||
|
--> |
||||
|
<div class="attachments"> |
||||
|
@for (item of shown; track item.resource.id) { |
||||
|
<div class="attachment" |
||||
|
[class.image]="item.image" |
||||
|
[class.file]="!item.image" |
||||
|
[matTooltip]="item.resource.name" |
||||
|
matTooltipPosition="above" |
||||
|
(click)="open(item)"> |
||||
|
@if (item.image) { |
||||
|
@if (item.url$ | async; as url) { |
||||
|
<img [src]="url" [alt]="item.resource.name"> |
||||
|
} @else { |
||||
|
<mat-icon class="placeholder">image</mat-icon> |
||||
|
} |
||||
|
} @else { |
||||
|
<div class="file-icon"><mat-icon>{{ item.icon }}</mat-icon></div> |
||||
|
<div class="file-meta"> |
||||
|
<span class="file-name">{{ item.resource.name }}</span> |
||||
|
<span class="file-info">{{ item.extension }}@if (item.extension) { · }{{ item.resource.size | fileSize }}</span> |
||||
|
</div> |
||||
|
} |
||||
|
</div> |
||||
|
} |
||||
|
</div> |
||||
@ -0,0 +1,101 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
||||
|
// SPDX-License-Identifier: BUSL-1.1 |
||||
|
:host { |
||||
|
display: block; |
||||
|
max-width: 100%; |
||||
|
|
||||
|
.attachments { |
||||
|
display: flex; |
||||
|
flex-wrap: wrap; |
||||
|
gap: 8px; |
||||
|
justify-content: inherit; |
||||
|
} |
||||
|
|
||||
|
.attachment { |
||||
|
position: relative; |
||||
|
display: flex; |
||||
|
align-items: center; |
||||
|
border-radius: 10px; |
||||
|
border: 1px solid rgba(0, 0, 0, 0.12); |
||||
|
background: #fff; |
||||
|
overflow: hidden; |
||||
|
flex: none; |
||||
|
cursor: pointer; |
||||
|
|
||||
|
&:hover { |
||||
|
border-color: var(--tb-primary-500); |
||||
|
} |
||||
|
|
||||
|
&.image { |
||||
|
width: 64px; |
||||
|
height: 64px; |
||||
|
justify-content: center; |
||||
|
background: rgba(0, 0, 0, 0.04); |
||||
|
|
||||
|
img { |
||||
|
width: 100%; |
||||
|
height: 100%; |
||||
|
object-fit: cover; |
||||
|
} |
||||
|
|
||||
|
.placeholder { |
||||
|
color: rgba(0, 0, 0, 0.38); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
&.file { |
||||
|
gap: 8px; |
||||
|
height: 48px; |
||||
|
max-width: 220px; |
||||
|
padding: 0 12px 0 8px; |
||||
|
|
||||
|
.file-icon { |
||||
|
display: flex; |
||||
|
align-items: center; |
||||
|
justify-content: center; |
||||
|
flex: none; |
||||
|
width: 32px; |
||||
|
height: 32px; |
||||
|
border-radius: 8px; |
||||
|
color: var(--tb-primary-500); |
||||
|
position: relative; |
||||
|
|
||||
|
&:before { |
||||
|
content: ""; |
||||
|
position: absolute; |
||||
|
inset: 0; |
||||
|
border-radius: inherit; |
||||
|
background: var(--tb-primary-500); |
||||
|
opacity: 0.1; |
||||
|
} |
||||
|
|
||||
|
mat-icon { |
||||
|
font-size: 20px; |
||||
|
width: 20px; |
||||
|
height: 20px; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
.file-meta { |
||||
|
display: flex; |
||||
|
flex-direction: column; |
||||
|
min-width: 0; |
||||
|
line-height: 16px; |
||||
|
|
||||
|
.file-name { |
||||
|
font-size: 13px; |
||||
|
color: rgba(0, 0, 0, 0.87); |
||||
|
white-space: nowrap; |
||||
|
overflow: hidden; |
||||
|
text-overflow: ellipsis; |
||||
|
} |
||||
|
|
||||
|
.file-info { |
||||
|
font-size: 11px; |
||||
|
color: rgba(0, 0, 0, 0.54); |
||||
|
white-space: nowrap; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,70 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
||||
|
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
import { Component, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core'; |
||||
|
import { MatDialog } from '@angular/material/dialog'; |
||||
|
import { Observable } from 'rxjs'; |
||||
|
import { catchError } from 'rxjs/operators'; |
||||
|
import { AiResourceInfo, isAiImageResource } from '@shared/models/ai-chat.models'; |
||||
|
import { AiResourceService } from '@core/http/ai-resource.service'; |
||||
|
import { aiAttachmentExtension, aiAttachmentKind } from '@home/components/ai/ai-attachment.models'; |
||||
|
import { |
||||
|
AiAttachmentPreviewDialogComponent, |
||||
|
AiAttachmentPreviewDialogData |
||||
|
} from '@home/components/ai/ai-attachment-preview-dialog.component'; |
||||
|
|
||||
|
interface AiAttachmentItem { |
||||
|
resource: AiResourceInfo; |
||||
|
image: boolean; |
||||
|
icon: string; |
||||
|
extension: string; |
||||
|
url$?: Observable<string | null>; |
||||
|
} |
||||
|
|
||||
|
@Component({ |
||||
|
selector: 'tb-ai-attachments', |
||||
|
templateUrl: './ai-attachments.component.html', |
||||
|
styleUrls: ['./ai-attachments.component.scss'], |
||||
|
standalone: false |
||||
|
}) |
||||
|
export class AiAttachmentsComponent implements OnChanges { |
||||
|
|
||||
|
@Input() resources: AiResourceInfo[]; |
||||
|
|
||||
|
@Output() resourceError = new EventEmitter<any>(); |
||||
|
|
||||
|
shown: AiAttachmentItem[] = []; |
||||
|
|
||||
|
constructor(private aiResourceService: AiResourceService, |
||||
|
private dialog: MatDialog) { |
||||
|
} |
||||
|
|
||||
|
ngOnChanges(changes: SimpleChanges): void { |
||||
|
if (changes.resources) { |
||||
|
this.shown = (this.resources ?? []).map(resource => { |
||||
|
const image = isAiImageResource(resource); |
||||
|
return { |
||||
|
resource, |
||||
|
image, |
||||
|
icon: aiAttachmentKind(resource.mediaType, resource.name).icon, |
||||
|
extension: aiAttachmentExtension(resource.name), |
||||
|
url$: image ? this.aiResourceService.getUrl(resource.id).pipe(catchError(() => [null])) : undefined |
||||
|
}; |
||||
|
}); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
open(item: AiAttachmentItem): void { |
||||
|
if (item.image) { |
||||
|
this.dialog.open<AiAttachmentPreviewDialogComponent, AiAttachmentPreviewDialogData>(AiAttachmentPreviewDialogComponent, { |
||||
|
panelClass: ['tb-dialog', 'tb-ai-attachment-preview-dialog'], |
||||
|
maxWidth: '92vw', |
||||
|
data: {resource: item.resource} |
||||
|
}); |
||||
|
} else { |
||||
|
this.aiResourceService.download(item.resource).subscribe({ |
||||
|
error: error => this.resourceError.emit(error) |
||||
|
}); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -1,30 +1,454 @@ |
|||||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
||||
// SPDX-License-Identifier: BUSL-1.1 |
// SPDX-License-Identifier: BUSL-1.1 |
||||
|
$ai-teal-300: #4db6ac; |
||||
|
$ai-teal-400: #26a69a; |
||||
|
$ai-action: #00695c; |
||||
|
$ai-action-hover: #004d40; |
||||
|
$ai-focus: #00695c; |
||||
|
$ai-teal-700: #00796b; |
||||
|
$ink: rgba(0, 0, 0, 0.87); |
||||
|
$ink-54: rgba(0, 0, 0, 0.54); |
||||
|
$ink-38: rgba(0, 0, 0, 0.38); |
||||
|
$faint: rgba(0, 0, 0, 0.56); |
||||
|
$line: rgba(0, 0, 0, 0.12); |
||||
|
$line-soft: rgba(0, 0, 0, 0.05); |
||||
|
$crit: #d12730; |
||||
|
$font: Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif; |
||||
|
$chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2.75' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M9 5l7 7-7 7'/%3E%3C/svg%3E"; |
||||
|
|
||||
:host { |
:host { |
||||
|
display: block; |
||||
|
width: 100%; |
||||
|
} |
||||
|
|
||||
|
.tb-ai-composer { |
||||
width: 100%; |
width: 100%; |
||||
|
font-family: $font; |
||||
|
letter-spacing: 0.25px; |
||||
|
text-align: left; |
||||
|
|
||||
.prompt-input { |
.composer-field { |
||||
border-radius: 12px; |
|
||||
border: 1px solid rgba(0, 0, 0, 0.2); |
|
||||
background-color: #fff; |
|
||||
position: relative; |
position: relative; |
||||
|
display: flow-root; |
||||
|
background: #fff; |
||||
|
border: 1px solid transparent; |
||||
|
border-radius: 14px; |
||||
|
box-shadow: 0 0 0 1px rgba(16, 24, 40, 0.04), 0 1px 2px rgba(16, 24, 40, 0.06), 0 8px 24px rgba(16, 24, 40, 0.08); |
||||
|
transition: border-color .18s ease, box-shadow .18s ease; |
||||
|
|
||||
|
&:focus-within { |
||||
|
border-color: $ai-focus; |
||||
|
box-shadow: 0 0 0 1px $ai-focus, 0 8px 24px rgba(0, 105, 92, 0.12); |
||||
|
|
||||
|
.composer-chevron { |
||||
|
color: $ai-focus; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
&.drop .composer-field { |
||||
|
box-shadow: inset 0 0 0 2px $ai-teal-300; |
||||
|
background: color-mix(in srgb, $ai-action 4%, #fff); |
||||
|
} |
||||
|
|
||||
|
.composer-files { |
||||
display: flex; |
display: flex; |
||||
flex: 1; |
flex-wrap: wrap; |
||||
--mat-form-field-outlined-outline-width: 0px; |
gap: 6px; |
||||
--mat-form-field-outlined-focus-outline-width: 0px; |
margin: 10px 12px 0 16px; |
||||
|
} |
||||
|
|
||||
|
.composer-file { |
||||
|
position: relative; |
||||
|
display: inline-flex; |
||||
|
align-items: center; |
||||
|
gap: 10px; |
||||
|
max-width: 100%; |
||||
|
overflow: hidden; |
||||
|
padding: 6px 10px 6px 8px; |
||||
|
border: 1px solid $line; |
||||
|
border-radius: 8px; |
||||
|
background: #fff; |
||||
|
font-size: 13.5px; |
||||
|
line-height: 20px; |
||||
|
animation: composer-file-in .12s ease-out; |
||||
|
|
||||
.send-button { |
.mat-icon { |
||||
|
flex: none; |
||||
|
color: $ink-54; |
||||
|
} |
||||
|
|
||||
|
.file-pic { |
||||
|
flex: none; |
||||
|
width: 32px; |
||||
|
height: 32px; |
||||
|
border-radius: 6px; |
||||
|
background: linear-gradient(135deg, #cfd8dc, #90a4ae) center / cover no-repeat; |
||||
|
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.06); |
||||
|
} |
||||
|
|
||||
|
.file-text { |
||||
|
display: flex; |
||||
|
flex-direction: column; |
||||
|
min-width: 0; |
||||
|
overflow-wrap: anywhere; |
||||
|
|
||||
|
b { |
||||
|
max-width: 240px; |
||||
|
overflow: hidden; |
||||
|
font-size: 13.5px; |
||||
|
font-weight: 500; |
||||
|
line-height: 18px; |
||||
|
color: $ink; |
||||
|
text-overflow: ellipsis; |
||||
|
white-space: nowrap; |
||||
|
} |
||||
|
|
||||
|
small { |
||||
|
font-size: 12px; |
||||
|
line-height: 16px; |
||||
|
color: $faint; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
.file-bar { |
||||
position: absolute; |
position: absolute; |
||||
right: 10px; |
left: 0; |
||||
bottom: 10px; |
bottom: 0; |
||||
|
height: 2px; |
||||
|
background: $ai-action; |
||||
|
transition: width .15s linear; |
||||
|
} |
||||
|
|
||||
|
.file-remove { |
||||
|
flex: none; |
||||
|
display: inline-flex; |
||||
|
align-items: center; |
||||
|
justify-content: center; |
||||
|
width: 24px; |
||||
|
height: 24px; |
||||
|
margin-right: -4px; |
||||
|
padding: 0; |
||||
|
border: 0; |
||||
|
border-radius: 50%; |
||||
|
background: none; |
||||
|
color: $ink-54; |
||||
|
cursor: pointer; |
||||
|
|
||||
|
&:hover { |
||||
|
background: rgba(0, 0, 0, 0.06); |
||||
|
color: $ink; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
&.up small { |
||||
|
color: $ai-teal-700; |
||||
|
} |
||||
|
|
||||
|
&.bad { |
||||
|
border-color: color-mix(in srgb, $crit 40%, transparent); |
||||
|
background: color-mix(in srgb, $crit 4%, #fff); |
||||
|
|
||||
|
.mat-icon, small { |
||||
|
color: $crit; |
||||
|
} |
||||
} |
} |
||||
} |
} |
||||
|
|
||||
|
.composer-row { |
||||
|
position: relative; |
||||
|
display: flex; |
||||
|
align-items: flex-start; |
||||
|
gap: 10px; |
||||
|
padding: 8px 0 8px 16px; |
||||
|
} |
||||
|
|
||||
|
.composer-chevron { |
||||
|
--chevron: 18px; |
||||
|
display: flex; |
||||
|
flex: none; |
||||
|
align-items: center; |
||||
|
height: 24px; |
||||
|
margin: 4px 0 0 -2px; |
||||
|
color: $ai-action; |
||||
|
transition: color .18s ease; |
||||
|
|
||||
|
&::before { |
||||
|
content: ''; |
||||
|
width: var(--chevron); |
||||
|
height: var(--chevron); |
||||
|
background: currentColor; |
||||
|
mask: url($chevron) center / contain no-repeat; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
textarea { |
||||
|
flex: 1; |
||||
|
min-width: 0; |
||||
|
min-height: 72px; |
||||
|
max-height: 240px; |
||||
|
margin: 4px 0 0; |
||||
|
padding: 0 58px 0 0; |
||||
|
border: 0; |
||||
|
outline: 0; |
||||
|
resize: none; |
||||
|
background: transparent; |
||||
|
font-family: $font; |
||||
|
font-size: 16px; |
||||
|
line-height: 24px; |
||||
|
letter-spacing: normal; |
||||
|
color: $ink; |
||||
|
caret-color: $ai-action; |
||||
|
tab-size: 2; |
||||
|
transition: height .12s ease; |
||||
|
|
||||
|
&::placeholder { |
||||
|
color: $faint; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
.composer-send-slot { |
||||
|
position: absolute; |
||||
|
right: 12px; |
||||
|
bottom: 12px; |
||||
|
display: inline-flex; |
||||
|
} |
||||
|
|
||||
|
.composer-send { |
||||
|
position: relative; |
||||
|
display: inline-flex; |
||||
|
flex: none; |
||||
|
align-items: center; |
||||
|
justify-content: center; |
||||
|
width: 36px; |
||||
|
height: 36px; |
||||
|
padding: 0; |
||||
|
border: 0; |
||||
|
border-radius: 10px; |
||||
|
background: $ai-action; |
||||
|
color: #fff; |
||||
|
cursor: pointer; |
||||
|
transition: background-color .2s ease, color .2s ease, box-shadow .2s ease, transform .16s cubic-bezier(.2, 0, 0, 1); |
||||
|
|
||||
|
&:hover:not(:disabled) { |
||||
|
background: $ai-action-hover; |
||||
|
|
||||
|
.return-glyph polyline { |
||||
|
transform: scale(1.12); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
&:active:not(:disabled) { |
||||
|
transform: scale(.92); |
||||
|
} |
||||
|
|
||||
|
&:focus-visible { |
||||
|
outline: 2px solid $ai-focus; |
||||
|
outline-offset: 2px; |
||||
|
} |
||||
|
|
||||
|
&:disabled { |
||||
|
background: rgba(0, 0, 0, 0.06); |
||||
|
color: $ink-38; |
||||
|
cursor: default; |
||||
|
} |
||||
|
|
||||
|
&.fly .return-glyph polyline { |
||||
|
animation: composer-grow .32s cubic-bezier(.2, 0, 0, 1); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
.return-glyph { |
||||
|
display: inline-flex; |
||||
|
width: 20px; |
||||
|
height: 20px; |
||||
|
|
||||
|
svg { |
||||
|
width: 100%; |
||||
|
height: 100%; |
||||
|
overflow: visible; |
||||
|
fill: none; |
||||
|
stroke: currentColor; |
||||
|
stroke-width: 2.2; |
||||
|
stroke-linecap: round; |
||||
|
stroke-linejoin: round; |
||||
|
} |
||||
|
|
||||
|
polyline { |
||||
|
transform-box: fill-box; |
||||
|
transform-origin: 0 50%; |
||||
|
transition: transform .16s ease-out; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
.composer-foot { |
||||
|
display: flex; |
||||
|
flex-wrap: wrap; |
||||
|
align-items: center; |
||||
|
gap: 2px; |
||||
|
padding: 2px 8px 6px 16px; |
||||
|
border-top: 1px solid $line-soft; |
||||
|
border-radius: 0 0 14px 14px; |
||||
|
font-size: 13px; |
||||
|
line-height: 18px; |
||||
|
color: rgba(0, 0, 0, 0.6); |
||||
|
} |
||||
|
|
||||
|
.composer-spacer { |
||||
|
flex: 1; |
||||
|
} |
||||
|
|
||||
|
.composer-tool { |
||||
|
display: inline-flex; |
||||
|
align-items: center; |
||||
|
justify-content: center; |
||||
|
width: 32px; |
||||
|
height: 32px; |
||||
|
margin: 0; |
||||
|
padding: 0; |
||||
|
border: 0; |
||||
|
border-radius: 8px; |
||||
|
background: none; |
||||
|
color: $ink-54; |
||||
|
cursor: pointer; |
||||
|
transition: background-color .12s ease, color .12s ease; |
||||
|
|
||||
|
&:hover, &[aria-describedby] { |
||||
|
background: $line-soft; |
||||
|
color: $ink; |
||||
|
} |
||||
|
|
||||
|
&:focus-visible { |
||||
|
outline: 2px solid $ai-focus; |
||||
|
outline-offset: 1px; |
||||
|
color: $ink; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
.composer-foot > .composer-add:first-child { |
||||
|
margin-left: -9px; |
||||
|
} |
||||
|
|
||||
|
&.docked { |
||||
|
border-top: 1px solid $line; |
||||
|
background: #fff; |
||||
|
font-size: 14px; |
||||
|
line-height: 20px; |
||||
|
transition: border-top-color .18s ease; |
||||
|
|
||||
|
&:focus-within { |
||||
|
border-top-color: $ai-focus; |
||||
|
} |
||||
|
|
||||
|
.composer-field { |
||||
|
border: 0; |
||||
|
border-radius: 0; |
||||
|
box-shadow: none; |
||||
|
transition: box-shadow .18s ease; |
||||
|
|
||||
|
&:focus-within { |
||||
|
box-shadow: inset 0 1px 0 $ai-focus; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
&.drop .composer-field { |
||||
|
box-shadow: inset 0 0 0 2px $ai-teal-300; |
||||
|
} |
||||
|
|
||||
|
.composer-files { |
||||
|
margin: 8px 8px 0 12px; |
||||
|
} |
||||
|
|
||||
|
.composer-row { |
||||
|
gap: 6px; |
||||
|
padding: 6px 0 6px 12px; |
||||
|
} |
||||
|
|
||||
|
.composer-chevron { |
||||
|
--chevron: 17px; |
||||
|
height: 22px; |
||||
|
} |
||||
|
|
||||
|
textarea { |
||||
|
min-height: 44px; |
||||
|
max-height: 160px; |
||||
|
padding-right: 44px; |
||||
|
font-size: 14px; |
||||
|
line-height: 20px; |
||||
|
} |
||||
|
|
||||
|
.composer-send-slot { |
||||
|
right: 8px; |
||||
|
bottom: 8px; |
||||
|
} |
||||
|
|
||||
|
.composer-send { |
||||
|
width: 28px; |
||||
|
height: 28px; |
||||
|
border-radius: 8px; |
||||
|
} |
||||
|
|
||||
|
.return-glyph { |
||||
|
width: 17px; |
||||
|
height: 17px; |
||||
|
|
||||
|
svg { |
||||
|
stroke-width: 2.4; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
.composer-foot { |
||||
|
flex-wrap: nowrap; |
||||
|
gap: 6px 8px; |
||||
|
padding: 2px 8px 6px 12px; |
||||
|
border-radius: 0; |
||||
|
font-size: 12px; |
||||
|
} |
||||
|
|
||||
|
.composer-tool { |
||||
|
width: 28px; |
||||
|
height: 28px; |
||||
|
} |
||||
|
|
||||
|
.composer-foot > .composer-add:first-child { |
||||
|
margin-left: -7.5px; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@keyframes composer-grow { |
||||
|
0% { |
||||
|
transform: none; |
||||
|
} |
||||
|
40% { |
||||
|
transform: scale(1.2); |
||||
|
} |
||||
|
100% { |
||||
|
transform: none; |
||||
|
} |
||||
} |
} |
||||
|
|
||||
:host::ng-deep { |
@keyframes composer-file-in { |
||||
.prompt-input { |
from { |
||||
.mdc-text-field--outlined { |
opacity: 0; |
||||
padding-right: 8px; |
transform: translateY(2px); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@media (prefers-reduced-motion: reduce) { |
||||
|
.tb-ai-composer { |
||||
|
.composer-file { |
||||
|
animation: none; |
||||
|
} |
||||
|
|
||||
|
.composer-send .return-glyph polyline { |
||||
|
animation: none; |
||||
|
transition: none; |
||||
|
transform: none !important; |
||||
|
} |
||||
|
|
||||
|
&.docked, .file-bar { |
||||
|
transition: none; |
||||
} |
} |
||||
} |
} |
||||
} |
} |
||||
|
|||||
@ -0,0 +1,118 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
||||
|
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
import { Directive, ElementRef, HostListener, inject, Input, OnDestroy, OnInit, Renderer2, TemplateRef } from '@angular/core'; |
||||
|
import { Subscription } from 'rxjs'; |
||||
|
import { TbPopoverDirective } from '@shared/components/popover.component'; |
||||
|
|
||||
|
const SHOW_DELAY = 0.35; |
||||
|
const HIDE_DELAY = 0.08; |
||||
|
const TIP_ID = 'tb-ai-tip'; |
||||
|
|
||||
|
const openTip: { current: AiTipDirective | null } = {current: null}; |
||||
|
|
||||
|
@Directive({ |
||||
|
selector: '[tbAiTip]', |
||||
|
standalone: false |
||||
|
}) |
||||
|
export class AiTipDirective implements OnInit, OnDestroy { |
||||
|
|
||||
|
private popover = inject(TbPopoverDirective, {self: true}); |
||||
|
private elementRef = inject<ElementRef<HTMLElement>>(ElementRef); |
||||
|
private renderer = inject(Renderer2); |
||||
|
|
||||
|
@Input('tbAiTip') template: TemplateRef<void>; |
||||
|
|
||||
|
@Input() tipToggle = false; |
||||
|
|
||||
|
private pointerType: string; |
||||
|
private visibleSubscription: Subscription; |
||||
|
private unlistenKeydown: () => void; |
||||
|
|
||||
|
private get trigger(): HTMLElement { |
||||
|
return this.elementRef.nativeElement; |
||||
|
} |
||||
|
|
||||
|
ngOnInit(): void { |
||||
|
this.popover.content = this.template; |
||||
|
this.popover.trigger = 'hover'; |
||||
|
this.popover.placement = ['top', 'topRight', 'topLeft', 'bottom', 'bottomRight', 'bottomLeft']; |
||||
|
this.popover.showCloseButton = false; |
||||
|
this.popover.mouseEnterDelay = SHOW_DELAY; |
||||
|
this.popover.mouseLeaveDelay = HIDE_DELAY; |
||||
|
this.popover.overlayClassName = 'tb-ai-tip'; |
||||
|
this.visibleSubscription = this.popover.visibleChange.subscribe(visible => visible ? this.onShown() : this.onHidden()); |
||||
|
} |
||||
|
|
||||
|
ngOnDestroy(): void { |
||||
|
this.visibleSubscription?.unsubscribe(); |
||||
|
this.onHidden(); |
||||
|
} |
||||
|
|
||||
|
@HostListener('pointerenter', ['$event']) |
||||
|
onPointerEnter(event: PointerEvent): void { |
||||
|
this.pointerType = event.pointerType; |
||||
|
const other = openTip.current !== this ? openTip.current : null; |
||||
|
this.popover.mouseEnterDelay = other ? 0 : SHOW_DELAY; |
||||
|
other?.popover.hide(); |
||||
|
} |
||||
|
|
||||
|
@HostListener('mouseenter', ['$event']) |
||||
|
onMouseEnter(event: MouseEvent): void { |
||||
|
if (this.pointerType === 'touch') { |
||||
|
event.stopImmediatePropagation(); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@HostListener('focus') |
||||
|
onFocus(): void { |
||||
|
if (this.trigger.matches(':focus-visible')) { |
||||
|
this.popover.show(); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@HostListener('blur') |
||||
|
onBlur(): void { |
||||
|
this.popover.hide(); |
||||
|
} |
||||
|
|
||||
|
@HostListener('click', ['$event']) |
||||
|
onClick(event: MouseEvent): void { |
||||
|
if (!this.tipToggle || this.popover.component?.visible) { |
||||
|
this.popover.hide(); |
||||
|
return; |
||||
|
} |
||||
|
event.preventDefault(); |
||||
|
this.popover.show(); |
||||
|
} |
||||
|
|
||||
|
private onShown(): void { |
||||
|
if (openTip.current !== this) { |
||||
|
openTip.current?.popover.hide(); |
||||
|
} |
||||
|
openTip.current = this; |
||||
|
this.unlistenKeydown?.(); |
||||
|
this.unlistenKeydown = this.renderer.listen('document', 'keydown', (event: KeyboardEvent) => { |
||||
|
if (event.key === 'Escape') { |
||||
|
this.popover.hide(); |
||||
|
} |
||||
|
}); |
||||
|
Promise.resolve().then(() => { |
||||
|
const pane = this.popover.component?.overlay?.overlayRef?.overlayElement; |
||||
|
const tip = pane?.querySelector('.tb-popover-inner'); |
||||
|
if (openTip.current === this && tip) { |
||||
|
this.renderer.setStyle(pane, 'pointer-events', 'none'); |
||||
|
tip.id = TIP_ID; |
||||
|
this.trigger.setAttribute('aria-describedby', TIP_ID); |
||||
|
} |
||||
|
}); |
||||
|
} |
||||
|
|
||||
|
private onHidden(): void { |
||||
|
if (openTip.current === this) { |
||||
|
openTip.current = null; |
||||
|
} |
||||
|
this.unlistenKeydown?.(); |
||||
|
this.unlistenKeydown = null; |
||||
|
this.trigger.removeAttribute('aria-describedby'); |
||||
|
} |
||||
|
} |
||||
File diff suppressed because it is too large
File diff suppressed because it is too large
File diff suppressed because it is too large
File diff suppressed because it is too large
Loading…
Reference in new issue