Browse Source

UI: Implement gallery image input component.

pull/9542/head
Igor Kulikov 3 years ago
parent
commit
bda319c3e8
  1. 8
      ui-ngx/src/app/core/http/image.service.ts
  2. 7
      ui-ngx/src/app/modules/home/components/home-components.module.ts
  3. 93
      ui-ngx/src/app/modules/home/components/image/gallery-image-input.component.html
  4. 180
      ui-ngx/src/app/modules/home/components/image/gallery-image-input.component.scss
  5. 224
      ui-ngx/src/app/modules/home/components/image/gallery-image-input.component.ts
  6. 27
      ui-ngx/src/app/modules/home/components/image/image-gallery.component.html
  7. 33
      ui-ngx/src/app/modules/home/components/image/image-gallery.component.scss
  8. 60
      ui-ngx/src/app/modules/home/components/image/image-gallery.component.ts
  9. 4
      ui-ngx/src/app/modules/home/components/image/images-in-use-dialog.component.html
  10. 14
      ui-ngx/src/app/modules/home/components/image/images-in-use-dialog.component.ts
  11. 8
      ui-ngx/src/app/modules/home/pages/widget/widgets-bundle.component.html
  12. 4
      ui-ngx/src/app/shared/components/popover.component.ts
  13. 12
      ui-ngx/src/app/shared/models/resource.models.ts
  14. 16
      ui-ngx/src/app/shared/pipe/image.pipe.ts
  15. 10
      ui-ngx/src/assets/locale/locale.constant-en_US.json

8
ui-ngx/src/app/core/http/image.service.ts

@ -80,7 +80,7 @@ export class ImageService {
defaultHttpOptionsFromConfig(config)); defaultHttpOptionsFromConfig(config));
} }
public getImageDataUrl(imageUrl: string, preview = false, asString = false): Observable<SafeUrl | string> { public getImageDataUrl(imageUrl: string, preview = false, asString = false, emptyUrl = NO_IMAGE_DATA_URI): Observable<SafeUrl | string> {
const parts = imageUrl.split('/'); const parts = imageUrl.split('/');
const key = parts[parts.length - 1]; const key = parts[parts.length - 1];
parts[parts.length - 1] = encodeURIComponent(key); parts[parts.length - 1] = encodeURIComponent(key);
@ -92,13 +92,13 @@ export class ImageService {
switchMap(val => blobToBase64(val).pipe( switchMap(val => blobToBase64(val).pipe(
map((dataUrl) => asString ? dataUrl : this.sanitizer.bypassSecurityTrustUrl(dataUrl)) map((dataUrl) => asString ? dataUrl : this.sanitizer.bypassSecurityTrustUrl(dataUrl))
)), )),
catchError(() => of(asString ? NO_IMAGE_DATA_URI : this.sanitizer.bypassSecurityTrustUrl(NO_IMAGE_DATA_URI))) catchError(() => of(asString ? emptyUrl : this.sanitizer.bypassSecurityTrustUrl(emptyUrl)))
); );
} }
public resolveImageUrl(imageUrl: string, preview = false, asString = false): Observable<SafeUrl | string> { public resolveImageUrl(imageUrl: string, preview = false, asString = false, emptyUrl = NO_IMAGE_DATA_URI): Observable<SafeUrl | string> {
if (isImageResourceUrl(imageUrl)) { if (isImageResourceUrl(imageUrl)) {
return this.getImageDataUrl(imageUrl, preview, asString); return this.getImageDataUrl(imageUrl, preview, asString, emptyUrl);
} else { } else {
return of(asString ? imageUrl : this.sanitizer.bypassSecurityTrustUrl(imageUrl)); return of(asString ? imageUrl : this.sanitizer.bypassSecurityTrustUrl(imageUrl));
} }

7
ui-ngx/src/app/modules/home/components/home-components.module.ts

@ -187,6 +187,7 @@ import { UploadImageDialogComponent } from '@home/components/image/upload-image-
import { ImageDialogComponent } from '@home/components/image/image-dialog.component'; import { ImageDialogComponent } from '@home/components/image/image-dialog.component';
import { ImagesInUseDialogComponent } from '@home/components/image/images-in-use-dialog.component'; import { ImagesInUseDialogComponent } from '@home/components/image/images-in-use-dialog.component';
import { ImageReferencesComponent } from '@home/components/image/image-references.component'; import { ImageReferencesComponent } from '@home/components/image/image-references.component';
import { GalleryImageInputComponent } from '@home/components/image/gallery-image-input.component';
@NgModule({ @NgModule({
declarations: declarations:
@ -337,7 +338,8 @@ import { ImageReferencesComponent } from '@home/components/image/image-reference
UploadImageDialogComponent, UploadImageDialogComponent,
ImageDialogComponent, ImageDialogComponent,
ImageReferencesComponent, ImageReferencesComponent,
ImagesInUseDialogComponent ImagesInUseDialogComponent,
GalleryImageInputComponent
], ],
imports: [ imports: [
CommonModule, CommonModule,
@ -481,7 +483,8 @@ import { ImageReferencesComponent } from '@home/components/image/image-reference
UploadImageDialogComponent, UploadImageDialogComponent,
ImageDialogComponent, ImageDialogComponent,
ImageReferencesComponent, ImageReferencesComponent,
ImagesInUseDialogComponent ImagesInUseDialogComponent,
GalleryImageInputComponent
], ],
providers: [ providers: [
WidgetComponentService, WidgetComponentService,

93
ui-ngx/src/app/modules/home/components/image/gallery-image-input.component.html

@ -0,0 +1,93 @@
<!--
Copyright © 2016-2023 The Thingsboard Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<div class="tb-container">
<label class="tb-title" *ngIf="label" [class]="{'tb-error': !disabled && (required && linkType === ImageLinkType.none), 'tb-required': !disabled && required}">{{label}}</label>
<div class="tb-image-select-container" [class]="{disabled: disabled && (linkType === ImageLinkType.none || linkType === ImageLinkType.base64)}">
<div class="tb-image-container">
<img *ngIf="linkType !== ImageLinkType.none && imageUrl; else noImage" class="tb-image-preview" [src]="imageUrl | image: {preview: true} | async">
</div>
<div *ngIf="linkType !== ImageLinkType.none && (linkType !== ImageLinkType.base64 || !disabled)" class="tb-image-info-container">
<div *ngIf="linkType === ImageLinkType.base64" class="tb-base64-image-container">
</div>
<div *ngIf="linkType === ImageLinkType.resource" class="tb-resource-image-container" [class]="{loading: loadingImageResource}">
<ng-container *ngIf="!loadingImageResource; else loading">
<div class="tb-resource-image-name">
{{ imageResource.title }}
</div>
<div class="tb-resource-image-details">
<div>{{ imageResource.descriptor.width }}x{{ imageResource.descriptor.height }}</div>
<mat-divider vertical></mat-divider>
<div>{{ imageResource.descriptor.size | fileSize }}</div>
</div>
</ng-container>
</div>
<div *ngIf="linkType === ImageLinkType.external" class="tb-external-image-container">
<div class="tb-external-link-label">
{{ 'image.image-link' | translate }}
</div>
<div class="tb-external-link-input-container">
<mat-form-field class="tb-inline-field" appearance="outline" subscriptSizing="dynamic">
<input matInput [formControl]="externalLinkControl" placeholder="{{ 'widget-config.set' | translate }}">
</mat-form-field>
<button *ngIf="!disabled"
class="tb-image-clear-btn"
type="button"
mat-icon-button
matTooltip="{{ 'image.clear-image' | translate }}"
matTooltipPosition="above"
(click)="clearImage()">
<mat-icon>close</mat-icon>
</button>
</div>
</div>
<button *ngIf="!disabled && linkType !== ImageLinkType.external"
class="tb-image-clear-btn"
type="button"
mat-icon-button
matTooltip="{{ 'image.clear-image' | translate }}"
matTooltipPosition="above"
(click)="clearImage()">
<mat-icon>close</mat-icon>
</button>
</div>
<div *ngIf="linkType === ImageLinkType.none && !disabled" class="tb-image-select-buttons-container">
<button #browseGalleryButton
mat-stroked-button
color="primary"
class="tb-image-select-button"
(click)="toggleGallery($event, browseGalleryButton)">
<tb-icon matButtonIcon>filter</tb-icon>
<span translate>image.browse-from-gallery</span>
</button>
<button mat-stroked-button
color="primary"
class="tb-image-select-button"
(click)="setLink($event)">
<tb-icon matButtonIcon>link</tb-icon>
<span translate>image.set-link</span>
</button>
</div>
</div>
</div>
<ng-template #noImage>
<div class="tb-no-image">{{ (disabled ? 'image.no-image' : 'image.no-image-selected') | translate }}</div>
</ng-template>
<ng-template #loading>
<mat-spinner [diameter]="80" strokeWidth="4"></mat-spinner>
</ng-template>

180
ui-ngx/src/app/modules/home/components/image/gallery-image-input.component.scss

@ -0,0 +1,180 @@
/**
* Copyright © 2016-2023 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
$containerHeight: 96px !default;
:host {
.tb-container {
margin-top: 0;
padding: 0 0 16px;
display: flex;
flex-direction: column;
gap: 8px;
label.tb-title {
display: block;
padding-bottom: 0;
}
}
.tb-image-select-container {
width: 100%;
height: $containerHeight;
border-radius: 4px;
border: 1px solid rgba(0, 0, 0, 0.12);
display: flex;
align-items: center;
&.disabled {
width: $containerHeight;
.tb-image-container {
width: $containerHeight - 2px;
border-right: none;
}
}
}
.tb-image-container {
width: $containerHeight - 1px;
height: $containerHeight - 2px;
display: flex;
justify-content: center;
align-items: center;
border-radius: 4px;
border-right: 1px solid rgba(0, 0, 0, 0.12);
background: #fff;
overflow: hidden;
}
.tb-image-preview {
width: auto;
max-width: $containerHeight - 2px;
height: auto;
max-height: $containerHeight - 2px;
}
.tb-no-image {
text-align: center;
color: rgba(0, 0, 0, 0.38);
font-size: 12px;
font-style: normal;
font-weight: 400;
line-height: 16px;
letter-spacing: 0.4px;
}
.tb-image-info-container {
display: flex;
flex: 1;
align-self: stretch;
padding: 0 8px;
justify-content: flex-end;
align-items: center;
gap: 4px;
.tb-base64-image-container, .tb-resource-image-container, .tb-external-image-container {
display: flex;
flex: 1;
align-self: stretch;
}
.tb-resource-image-container {
padding: 8px;
justify-content: center;
align-items: flex-start;
flex-direction: column;
gap: 4px;
.tb-resource-image-name {
color: rgba(0, 0, 0, 0.54);
font-size: 12px;
font-style: normal;
font-weight: 500;
line-height: 16px;
letter-spacing: 0.25px;
}
.tb-resource-image-details {
display: flex;
align-items: center;
gap: 8px;
color: rgba(0, 0, 0, 0.38);
font-size: 11px;
font-style: normal;
font-weight: 400;
line-height: 16px;
letter-spacing: 0.017px;
.mat-divider.mat-divider-vertical {
height: 16px;
}
}
&.loading {
align-items: center;
}
}
.tb-external-image-container {
padding: 16px 8px 0 16px;
flex-direction: column;
align-items: flex-start;
gap: 4px;
.tb-external-link-label {
color: rgba(0, 0, 0, 0.54);
font-size: 12px;
font-style: normal;
font-weight: 400;
line-height: 16px;
letter-spacing: 0.4px;
}
.tb-external-link-input-container {
display: flex;
justify-content: flex-end;
align-items: center;
gap: 4px;
align-self: stretch;
.tb-inline-field {
width: 100%;
}
}
}
.tb-image-clear-btn {
color: rgba(0,0,0,0.38);
}
}
.tb-image-select-buttons-container {
display: flex;
flex: 1;
align-self: stretch;
padding: 8px;
gap: 8px;
justify-content: center;
align-items: flex-start;
.tb-image-select-button {
width: 100%;
height: 100%;
align-self: stretch;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 4px;
padding: 16px;
line-height: normal;
font-size: 12px;
.mat-icon {
width: 24px;
height: 24px;
font-size: 24px;
margin: 0;
}
}
}
}

224
ui-ngx/src/app/modules/home/components/image/gallery-image-input.component.ts

@ -0,0 +1,224 @@
///
/// Copyright © 2016-2023 The Thingsboard Authors
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
import {
ChangeDetectorRef,
Component,
forwardRef,
Input,
OnDestroy,
OnInit,
Renderer2,
ViewContainerRef
} from '@angular/core';
import { PageComponent } from '@shared/components/page.component';
import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state';
import { ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR, } from '@angular/forms';
import { coerceBoolean } from '@shared/decorators/coercion';
import {
extractParamsFromImageResourceUrl,
ImageResourceInfo,
isBase64DataImageUrl,
isImageResourceUrl
} from '@shared/models/resource.models';
import { ImageService } from '@core/http/image.service';
import { MatButton } from '@angular/material/button';
import { TbPopoverService } from '@shared/components/popover.service';
import { ImageGalleryComponent } from '@home/components/image/image-gallery.component';
enum ImageLinkType {
none = 'none',
base64 = 'base64',
external = 'external',
resource = 'resource'
}
@Component({
selector: 'tb-gallery-image-input',
templateUrl: './gallery-image-input.component.html',
styleUrls: ['./gallery-image-input.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => GalleryImageInputComponent),
multi: true
}
]
})
export class GalleryImageInputComponent extends PageComponent implements OnInit, OnDestroy, ControlValueAccessor {
@Input()
label: string;
@Input()
@coerceBoolean()
required = false;
@Input()
disabled: boolean;
imageUrl: string;
imageResource: ImageResourceInfo;
loadingImageResource = false;
ImageLinkType = ImageLinkType;
linkType: ImageLinkType = ImageLinkType.none;
externalLinkControl = new FormControl(null);
private propagateChange = null;
constructor(protected store: Store<AppState>,
private imageService: ImageService,
private cd: ChangeDetectorRef,
private renderer: Renderer2,
private viewContainerRef: ViewContainerRef,
private popoverService: TbPopoverService) {
super(store);
}
ngOnInit() {
this.externalLinkControl.valueChanges.subscribe((value) => {
if (this.linkType === ImageLinkType.external) {
this.imageUrl = value;
this.updateModel();
}
});
}
ngOnDestroy() {
}
registerOnChange(fn: any): void {
this.propagateChange = fn;
}
registerOnTouched(fn: any): void {
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
if (this.disabled) {
this.detectLinkType();
this.externalLinkControl.disable({emitEvent: false});
} else {
this.externalLinkControl.enable({emitEvent: false});
}
}
writeValue(value: string): void {
if (this.imageUrl !== value) {
this.reset();
this.imageUrl = value;
this.detectLinkType();
if (this.linkType === ImageLinkType.resource) {
const params = extractParamsFromImageResourceUrl(value);
this.loadingImageResource = true;
this.imageService.getImageInfo(params.type, params.key, {ignoreLoading: true, ignoreErrors: true}).subscribe(
{
next: (res) => {
this.imageResource = res;
this.loadingImageResource = false;
this.cd.markForCheck();
},
error: () => {
this.reset();
this.loadingImageResource = false;
this.cd.markForCheck();
}
}
);
} else if (this.linkType === ImageLinkType.base64) {
this.cd.markForCheck();
} else if (this.linkType === ImageLinkType.external) {
this.externalLinkControl.setValue(this.imageUrl, {emitEvent: false});
this.cd.markForCheck();
}
}
}
private detectLinkType() {
if (this.imageUrl) {
if (isImageResourceUrl(this.imageUrl)) {
this.linkType = ImageLinkType.resource;
} else if (isBase64DataImageUrl(this.imageUrl)) {
this.linkType = ImageLinkType.base64;
} else {
this.linkType = ImageLinkType.external;
}
} else {
this.linkType = ImageLinkType.none;
}
}
private updateModel() {
this.cd.markForCheck();
this.propagateChange(this.imageUrl);
}
private reset() {
this.linkType = ImageLinkType.none;
this.imageUrl = null;
this.imageResource = null;
this.externalLinkControl.setValue(null, {emitEvent: false});
}
clearImage() {
this.reset();
this.updateModel();
}
setLink($event: Event) {
if ($event) {
$event.stopPropagation();
}
this.linkType = ImageLinkType.external;
}
toggleGallery($event: Event, browseGalleryButton: MatButton) {
if ($event) {
$event.stopPropagation();
}
const trigger = browseGalleryButton._elementRef.nativeElement;
if (this.popoverService.hasPopover(trigger)) {
this.popoverService.hidePopover(trigger);
} else {
const ctx: any = {
pageMode: false,
popoverMode: true,
mode: 'grid',
selectionMode: true
};
const imageGalleryPopover = this.popoverService.displayPopover(trigger, this.renderer,
this.viewContainerRef, ImageGalleryComponent, 'top', true, null,
ctx,
{},
{}, {}, true);
imageGalleryPopover.tbComponentRef.instance.imageSelected.subscribe((image) => {
imageGalleryPopover.hide();
this.linkType = ImageLinkType.resource;
this.imageUrl = image.link;
this.imageResource = image;
this.updateModel();
});
}
}
}

27
ui-ngx/src/app/modules/home/components/image/image-gallery.component.html

@ -15,11 +15,11 @@
limitations under the License. limitations under the License.
--> -->
<div class="mat-padding tb-images tb-absolute-fill" [ngClass]="{'mat-padding': pageMode}"> <div class="tb-images tb-absolute-fill" [ngClass]="{'tb-popover-mode': popoverMode, 'mat-padding': !popoverMode}">
<div fxFlex fxLayout="column" class="tb-images-content" [ngClass]="{'tb-outlined-border': pageMode}"> <div fxFlex fxLayout="column" class="tb-images-content" [ngClass]="{'tb-outlined-border': pageMode}">
<mat-toolbar class="mat-mdc-table-toolbar" <mat-toolbar class="mat-mdc-table-toolbar"
fxLayout.lt-md="column" fxLayoutAlign.lt-md="start stretch" fxLayout.lt-md="column" fxLayoutAlign.lt-md="start stretch"
[fxShow]="!textSearchMode && dataSource.selection.isEmpty()" [ngClass.lt-md]="{'multi-row': !isSysAdmin}"> [fxShow]="!textSearchMode && (mode === 'grid' || dataSource?.selection.isEmpty())" [ngClass.lt-md]="{'multi-row': !isSysAdmin}">
<div fxFlex fxLayout="row" fxLayoutAlign="start center"> <div fxFlex fxLayout="row" fxLayoutAlign="start center">
<div class="mat-toolbar-tools"> <div class="mat-toolbar-tools">
<span fxHide fxShow.gt-sm class="tb-images-title" translate>image.gallery</span> <span fxHide fxShow.gt-sm class="tb-images-title" translate>image.gallery</span>
@ -93,7 +93,7 @@
<mat-slide-toggle *ngIf="!isSysAdmin" fxHide fxShow.lt-md <mat-slide-toggle *ngIf="!isSysAdmin" fxHide fxShow.lt-md
[formControl]="includeSystemImages">{{ 'image.include-system-images' | translate }}</mat-slide-toggle> [formControl]="includeSystemImages">{{ 'image.include-system-images' | translate }}</mat-slide-toggle>
</mat-toolbar> </mat-toolbar>
<mat-toolbar class="mat-mdc-table-toolbar" [fxShow]="textSearchMode && dataSource.selection.isEmpty()"> <mat-toolbar class="mat-mdc-table-toolbar" [fxShow]="textSearchMode && (mode === 'grid' || dataSource?.selection.isEmpty())">
<div class="mat-toolbar-tools"> <div class="mat-toolbar-tools">
<button mat-icon-button <button mat-icon-button
matTooltip="{{ 'image.search' | translate }}" matTooltip="{{ 'image.search' | translate }}"
@ -113,10 +113,10 @@
</button> </button>
</div> </div>
</mat-toolbar> </mat-toolbar>
<mat-toolbar class="mat-mdc-table-toolbar" color="primary" [fxShow]="!dataSource.selection.isEmpty()"> <mat-toolbar class="mat-mdc-table-toolbar" color="primary" [fxShow]="mode === 'list' && !dataSource?.selection.isEmpty()">
<div class="mat-toolbar-tools"> <div class="mat-toolbar-tools">
<span> <span>
{{ translate.get('image.selected-images', {count: dataSource.selection.selected.length}) | async }} {{ translate.get('image.selected-images', {count: dataSource?.selection.selected.length}) | async }}
</span> </span>
<span fxFlex></span> <span fxFlex></span>
<button mat-icon-button [disabled]="isLoading$ | async" <button mat-icon-button [disabled]="isLoading$ | async"
@ -248,6 +248,14 @@
</div> </div>
</mat-cell> </mat-cell>
</ng-container> </ng-container>
<ng-container matColumnDef="imageSelect" stickyEnd>
<mat-header-cell *matHeaderCellDef></mat-header-cell>
<mat-cell *matCellDef="let image">
<button mat-stroked-button
color="primary"
(click)="selectImage($event, image)">{{ 'action.select' | translate }}</button>
</mat-cell>
</ng-container>
<mat-header-row [ngClass]="{'mat-row-select': true}" *matHeaderRowDef="displayedColumns; sticky: true"></mat-header-row> <mat-header-row [ngClass]="{'mat-row-select': true}" *matHeaderRowDef="displayedColumns; sticky: true"></mat-header-row>
<mat-row [ngClass]="{'mat-row-select': true, <mat-row [ngClass]="{'mat-row-select': true,
'mat-selected': dataSource.selection.isSelected(image)}" 'mat-selected': dataSource.selection.isSelected(image)}"
@ -323,13 +331,20 @@
</div> </div>
</div> </div>
<div class="tb-image-preview-container"> <div class="tb-image-preview-container">
<div class="tb-image-preview-overlay"> <div class="tb-image-preview-overlay" (click)="selectionMode && selectImage($event, item)">
<button <button
*ngIf="!selectionMode"
mat-flat-button mat-flat-button
color="primary" color="primary"
(click)="editImage($event, item, itemIndex)"> (click)="editImage($event, item, itemIndex)">
{{ (readonly(item) ? 'image.image-details' : 'image.edit-image') | translate }} {{ (readonly(item) ? 'image.image-details' : 'image.edit-image') | translate }}
</button> </button>
<button
*ngIf="selectionMode"
mat-flat-button
color="primary"
(click)="selectImage($event, item)">{{ 'action.select' | translate }}
</button>
</div> </div>
<div class="tb-image-preview-spacer"></div> <div class="tb-image-preview-spacer"></div>
<img class="tb-image-preview" [src]="item.link | image: {preview: true} | async" alt="{{ item.title }}"> <img class="tb-image-preview" [src]="item.link | image: {preview: true} | async" alt="{{ item.title }}">

33
ui-ngx/src/app/modules/home/components/image/image-gallery.component.scss

@ -13,9 +13,42 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
@import "../../../../../scss/constants";
$tb-button-selected-color: rgb(255, 110, 64) !default; $tb-button-selected-color: rgb(255, 110, 64) !default;
.tb-images { .tb-images {
&.tb-popover-mode {
padding-top: 8px;
position: relative;
width: 300px;
height: 500px;
max-width: calc(100vw - 50px);
max-height: calc(100vh - 100px);
@media #{$mat-gt-xs} {
width: 400px;
height: 600px;
}
@media #{$mat-gt-sm} {
width: 500px;
height: 600px;
}
@media #{$mat-gt-md} {
width: 700px;
height: 700px;
}
@media #{$mat-gt-xmd} {
width: 900px;
height: 700px;
}
@media #{$mat-gt-xl} {
width: 1200px;
height: 800px;
}
}
.tb-images-content { .tb-images-content {
width: 100%; width: 100%;
height: 100%; height: 100%;

60
ui-ngx/src/app/modules/home/components/image/image-gallery.component.ts

@ -29,10 +29,10 @@ import {
AfterViewInit, AfterViewInit,
ChangeDetectorRef, ChangeDetectorRef,
Component, Component,
ElementRef, ElementRef, EventEmitter,
Input, Input,
OnDestroy, OnDestroy,
OnInit, OnInit, Output,
ViewChild, ViewChild,
ViewEncapsulation ViewEncapsulation
} from '@angular/core'; } from '@angular/core';
@ -74,6 +74,28 @@ interface GridImagesFilter {
includeSystemImages: boolean; includeSystemImages: boolean;
} }
const pageGridColumns: ScrollGridColumns = {
columns: 2,
breakpoints: {
'screen and (min-width: 2320px)': 10,
'screen and (min-width: 2000px)': 8,
'gt-lg': 7,
'screen and (min-width: 1600px)': 6,
'gt-md': 5,
'screen and (min-width: 1120px)': 4,
'gt-xs': 3
}
};
const popoverGridColumns: ScrollGridColumns = {
columns: 2,
breakpoints: {
'gt-lg': 5,
'screen and (min-width: 1600px)': 4,
'gt-md': 3
}
};
@Component({ @Component({
selector: 'tb-image-gallery', selector: 'tb-image-gallery',
templateUrl: './image-gallery.component.html', templateUrl: './image-gallery.component.html',
@ -86,9 +108,19 @@ export class ImageGalleryComponent extends PageComponent implements OnInit, OnDe
@coerceBoolean() @coerceBoolean()
pageMode = true; pageMode = true;
@Input()
@coerceBoolean()
popoverMode = false;
@Input() @Input()
mode: 'list' | 'grid' = 'list'; mode: 'list' | 'grid' = 'list';
@Input()
selectionMode = false;
@Output()
imageSelected = new EventEmitter<ImageResourceInfo>();
@ViewChild('searchInput') searchInputField: ElementRef; @ViewChild('searchInput') searchInputField: ElementRef;
@ViewChild(MatPaginator) paginator: MatPaginator; @ViewChild(MatPaginator) paginator: MatPaginator;
@ -111,18 +143,7 @@ export class ImageGalleryComponent extends PageComponent implements OnInit, OnDe
textSearch = this.fb.control('', {nonNullable: true}); textSearch = this.fb.control('', {nonNullable: true});
includeSystemImages = this.fb.control(false); includeSystemImages = this.fb.control(false);
gridColumns: ScrollGridColumns = { gridColumns: ScrollGridColumns;
columns: 2,
breakpoints: {
'screen and (min-width: 2320px)': 10,
'screen and (min-width: 2000px)': 8,
'gt-lg': 7,
'screen and (min-width: 1600px)': 6,
'gt-md': 5,
'screen and (min-width: 1120px)': 4,
'gt-xs': 3
}
};
gridImagesFetchFunction: GridEntitiesFetchFunction<ImageResourceInfo, GridImagesFilter>; gridImagesFetchFunction: GridEntitiesFetchFunction<ImageResourceInfo, GridImagesFilter>;
gridImagesFilter: GridImagesFilter = { gridImagesFilter: GridImagesFilter = {
@ -166,6 +187,7 @@ export class ImageGalleryComponent extends PageComponent implements OnInit, OnDe
} }
ngOnInit(): void { ngOnInit(): void {
this.gridColumns = this.popoverMode ? popoverGridColumns : pageGridColumns;
this.displayedColumns = this.computeDisplayedColumns(); this.displayedColumns = this.computeDisplayedColumns();
let sortOrder: SortOrder = this.defaultSortOrder; let sortOrder: SortOrder = this.defaultSortOrder;
this.pageSizeOptions = [this.defaultPageSize, this.defaultPageSize * 2, this.defaultPageSize * 3]; this.pageSizeOptions = [this.defaultPageSize, this.defaultPageSize * 2, this.defaultPageSize * 3];
@ -285,6 +307,9 @@ export class ImageGalleryComponent extends PageComponent implements OnInit, OnDe
} }
private computeDisplayedColumns(): string[] { private computeDisplayedColumns(): string[] {
if (this.selectionMode) {
return ['preview', 'title', 'imageSelect'];
}
const columns = ['select', 'preview', 'title', 'createdTime', 'resolution', 'size']; const columns = ['select', 'preview', 'title', 'createdTime', 'resolution', 'size'];
if (!this.isSysAdmin && this.includeSystemImages.value) { if (!this.isSysAdmin && this.includeSystemImages.value) {
columns.push('system'); columns.push('system');
@ -567,6 +592,13 @@ export class ImageGalleryComponent extends PageComponent implements OnInit, OnDe
}); });
} }
selectImage($event, image: ImageResourceInfo) {
if ($event) {
$event.stopPropagation();
}
this.imageSelected.next(image);
}
uploadImage(): void { uploadImage(): void {
this.dialog.open<UploadImageDialogComponent, UploadImageDialogData, this.dialog.open<UploadImageDialogComponent, UploadImageDialogData,
ImageResourceInfo>(UploadImageDialogComponent, { ImageResourceInfo>(UploadImageDialogComponent, {

4
ui-ngx/src/app/modules/home/components/image/images-in-use-dialog.component.html

@ -15,9 +15,9 @@
limitations under the License. limitations under the License.
--> -->
<h2 mat-dialog-title>{{title | translate}}</h2> <h2 mat-dialog-title>{{title}}</h2>
<div mat-dialog-content class="tb-images-in-use-content" [class]="{multiple: data.multiple}"> <div mat-dialog-content class="tb-images-in-use-content" [class]="{multiple: data.multiple}">
<div [innerHTML]="message | translate | safe: 'html'"></div> <div [innerHTML]="message | safe: 'html'"></div>
<ng-container *ngIf="data.multiple; else singleImageReferences"> <ng-container *ngIf="data.multiple; else singleImageReferences">
<div class="table-container"> <div class="table-container">
<table mat-table [dataSource]="dataSource"> <table mat-table [dataSource]="dataSource">

14
ui-ngx/src/app/modules/home/components/image/images-in-use-dialog.component.ts

@ -60,12 +60,12 @@ export class ImagesInUseDialogComponent extends
ngOnInit(): void { ngOnInit(): void {
if (this.data.multiple) { if (this.data.multiple) {
this.title = 'image.images-are-in-use'; this.title = this.translate.instant('image.images-are-in-use');
this.message = 'image.images-are-in-use-text'; this.message = this.translate.instant('image.images-are-in-use-text');
this.dataSource = new ImagesDatasource(null, this.data.images, entity => true); this.dataSource = new ImagesDatasource(null, this.data.images, entity => true);
} else { } else {
this.title = 'image.image-is-in-use'; this.title = this.translate.instant('image.image-is-in-use');
this.message = 'image.image-is-in-use-text'; this.message = this.translate.instant('image.image-is-in-use-text', {title: this.data.images[0].title});
this.references = this.data.images[0].references; this.references = this.data.images[0].references;
} }
} }
@ -97,8 +97,10 @@ export class ImagesInUseDialogComponent extends
}, {}, {}, {}, }, {}, {}, {},
false, false,
visible => { visible => {
const addClasses = visible ? 'mdc-button--unelevated mat-mdc-unelevated-button' : 'mdc-button--outlined mat-mdc-outlined-button'; const addClasses =
const removeClasses = visible ? 'mdc-button--outlined mat-mdc-outlined-button' : 'mdc-button--unelevated mat-mdc-unelevated-button'; visible ? 'mdc-button--unelevated mat-mdc-unelevated-button' : 'mdc-button--outlined mat-mdc-outlined-button';
const removeClasses =
visible ? 'mdc-button--outlined mat-mdc-outlined-button' : 'mdc-button--unelevated mat-mdc-unelevated-button';
addClasses.split(' ').forEach(clazz => { addClasses.split(' ').forEach(clazz => {
this.renderer.addClass(trigger, clazz); this.renderer.addClass(trigger, clazz);
}); });

8
ui-ngx/src/app/modules/home/pages/widget/widgets-bundle.component.html

@ -54,11 +54,15 @@
{{ 'widgets-bundle.title-max-length' | translate }} {{ 'widgets-bundle.title-max-length' | translate }}
</mat-error> </mat-error>
</mat-form-field> </mat-form-field>
<tb-image-input fxFlex <tb-gallery-image-input fxFlex
label="{{'widgets-bundle.image-preview' | translate}}"
formControlName="image">
</tb-gallery-image-input>
<!--tb-image-input fxFlex
label="{{'widgets-bundle.image-preview' | translate}}" label="{{'widgets-bundle.image-preview' | translate}}"
maxSizeByte="524288" maxSizeByte="524288"
formControlName="image"> formControlName="image">
</tb-image-input> </tb-image-input-->
<mat-form-field class="mat-block"> <mat-form-field class="mat-block">
<mat-label translate>widgets-bundle.description</mat-label> <mat-label translate>widgets-bundle.description</mat-label>
<textarea matInput formControlName="description" rows="2" maxlength="1024" #descriptionInput></textarea> <textarea matInput formControlName="description" rows="2" maxlength="1024" #descriptionInput></textarea>

4
ui-ngx/src/app/shared/components/popover.component.ts

@ -44,7 +44,7 @@ import {
CdkConnectedOverlay, CdkConnectedOverlay,
CdkOverlayOrigin, CdkOverlayOrigin,
ConnectedOverlayPositionChange, ConnectedOverlayPositionChange,
ConnectionPositionPair ConnectionPositionPair, NoopScrollStrategy
} from '@angular/cdk/overlay'; } from '@angular/cdk/overlay';
import { Subject, Subscription } from 'rxjs'; import { Subject, Subscription } from 'rxjs';
import { import {
@ -311,6 +311,7 @@ export class TbPopoverDirective implements OnChanges, OnDestroy, AfterViewInit {
[cdkConnectedOverlayHasBackdrop]="hasBackdrop" [cdkConnectedOverlayHasBackdrop]="hasBackdrop"
[cdkConnectedOverlayOrigin]="origin" [cdkConnectedOverlayOrigin]="origin"
[cdkConnectedOverlayPositions]="positions" [cdkConnectedOverlayPositions]="positions"
[cdkConnectedOverlayScrollStrategy]="scrollStrategy"
[cdkConnectedOverlayOpen]="visible" [cdkConnectedOverlayOpen]="visible"
[cdkConnectedOverlayPush]="true" [cdkConnectedOverlayPush]="true"
(overlayOutsideClick)="onClickOutside($event)" (overlayOutsideClick)="onClickOutside($event)"
@ -451,6 +452,7 @@ export class TbPopoverComponent<T = any> implements OnDestroy, OnInit {
public dir: Direction = 'ltr'; public dir: Direction = 'ltr';
classMap: { [klass: string]: any } = {}; classMap: { [klass: string]: any } = {};
positions: ConnectionPositionPair[] = [...DEFAULT_POPOVER_POSITIONS]; positions: ConnectionPositionPair[] = [...DEFAULT_POPOVER_POSITIONS];
scrollStrategy = new NoopScrollStrategy();
private parentScrollSubscription: Subscription = null; private parentScrollSubscription: Subscription = null;
private intersectionObserver = new IntersectionObserver((entries) => { private intersectionObserver = new IntersectionObserver((entries) => {
if (this.lastIsIntersecting !== entries[0].isIntersecting) { if (this.lastIsIntersecting !== entries[0].isIntersecting) {

12
ui-ngx/src/app/shared/models/resource.models.ts

@ -127,8 +127,18 @@ export const toImageDeleteResult = (image: ImageResourceInfo, e?: any): ImageDel
export const imageResourceType = (imageInfo: ImageResourceInfo): ImageResourceType => export const imageResourceType = (imageInfo: ImageResourceInfo): ImageResourceType =>
(!imageInfo.tenantId || imageInfo.tenantId?.id === NULL_UUID) ? 'system' : 'tenant'; (!imageInfo.tenantId || imageInfo.tenantId?.id === NULL_UUID) ? 'system' : 'tenant';
export const IMAGES_URL_REGEXP = /\/api\/images\/(tenant|system)\/(.*)/;
export const IMAGES_URL_PREFIX = '/api/images'; export const IMAGES_URL_PREFIX = '/api/images';
export const isImageResourceUrl = (url: string): boolean => url && url.startsWith(IMAGES_URL_PREFIX); export const IMAGE_BASE64_URL_PREFIX = 'data:image/';
export const isImageResourceUrl = (url: string): boolean => url && IMAGES_URL_REGEXP.test(url);
export const extractParamsFromImageResourceUrl = (url: string): {type: ImageResourceType; key: string} => {
const res = url.match(IMAGES_URL_REGEXP);
return {type: res[1] as ImageResourceType, key: res[2]};
};
export const isBase64DataImageUrl = (url: string): boolean => url && url.startsWith(IMAGE_BASE64_URL_PREFIX);
export const NO_IMAGE_DATA_URI = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='; export const NO_IMAGE_DATA_URI = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';

16
ui-ngx/src/app/shared/pipe/image.pipe.ts

@ -40,18 +40,22 @@ export class ImagePipe implements PipeTransform {
transform(urlData: string | UrlHolder, args?: any): Observable<SafeUrl | string> { transform(urlData: string | UrlHolder, args?: any): Observable<SafeUrl | string> {
const ignoreLoadingImage = !!args?.ignoreLoadingImage; const ignoreLoadingImage = !!args?.ignoreLoadingImage;
const asString = !!args?.asString; const asString = !!args?.asString;
const emptyUrl = args?.emptyUrl || NO_IMAGE_DATA_URI;
const image$ = ignoreLoadingImage ? new Subject<SafeUrl | string>() : new BehaviorSubject<SafeUrl | string>(LOADING_IMAGE_DATA_URI); const image$ = ignoreLoadingImage ? new Subject<SafeUrl | string>() : new BehaviorSubject<SafeUrl | string>(LOADING_IMAGE_DATA_URI);
const url = (typeof urlData === 'string') ? urlData : urlData?.url; const url = (typeof urlData === 'string') ? urlData : urlData?.url;
if (isDefinedAndNotNull(url)) { if (isDefinedAndNotNull(url)) {
const preview = !!args?.preview; const preview = !!args?.preview;
this.imageService.resolveImageUrl(url, preview, asString).subscribe((imageUrl) => { this.imageService.resolveImageUrl(url, preview, asString, emptyUrl).subscribe((imageUrl) => {
image$.next(imageUrl); Promise.resolve().then(() => {
image$.complete(); image$.next(imageUrl);
image$.complete();
});
}); });
} else { } else {
const emptyUrl = args?.emptyUrl || NO_IMAGE_DATA_URI; Promise.resolve().then(() => {
image$.next(asString ? emptyUrl : this.sanitizer.bypassSecurityTrustUrl(emptyUrl)); image$.next(asString ? emptyUrl : this.sanitizer.bypassSecurityTrustUrl(emptyUrl));
image$.complete(); image$.complete();
});
} }
return image$.asObservable(); return image$.asObservable();
} }

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

@ -2976,13 +2976,19 @@
"invalid-image-json-file-error": "Unable to import image from JSON: Invalid image JSON data structure.", "invalid-image-json-file-error": "Unable to import image from JSON: Invalid image JSON data structure.",
"image-is-in-use": "Image is used by other entities", "image-is-in-use": "Image is used by other entities",
"images-are-in-use": "Images are used by other entities", "images-are-in-use": "Images are used by other entities",
"image-is-in-use-text": "The image was not deleted because it is used by the following entities:", "image-is-in-use-text": "The image <b>'{{title}}'</b> was not deleted because it is used by the following entities:",
"images-are-in-use-text": "Not all images have been deleted because they are used by other entities.</br>You can view referenced entities by clicking the <b>References</b> button in the corresponding image row.</br>If you still want to delete these images, select them in the table below and click the <b>Delete selected</b> button.", "images-are-in-use-text": "Not all images have been deleted because they are used by other entities.</br>You can view referenced entities by clicking the <b>References</b> button in the corresponding image row.</br>If you still want to delete these images, select them in the table below and click the <b>Delete selected</b> button.",
"delete-image-in-use-text": "If you still want to delete the image, click the <b>Delete anyway</b> button.", "delete-image-in-use-text": "If you still want to delete the image, click the <b>Delete anyway</b> button.",
"system-entities": "System entities:", "system-entities": "System entities:",
"entities": "entities:", "entities": "entities:",
"references": "References", "references": "References",
"include-system-images": "Include system images" "include-system-images": "Include system images",
"clear-image": "Clear image",
"no-image": "No image",
"no-image-selected": "No image selected",
"browse-from-gallery": "Browse from gallery",
"set-link": "Set link",
"image-link": "Image link"
}, },
"image-input": { "image-input": {
"drop-images-or": "Drag and drop an images or", "drop-images-or": "Drag and drop an images or",

Loading…
Cancel
Save