All files / file-uploader si-file-uploader.component.ts

95.02% Statements 172/181
73.43% Branches 47/64
100% Functions 43/43
94.73% Lines 162/171

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616                                                                                                                                                                                                            1x                 28x 28x                   28x                 28x 28x                   28x 28x                   28x 28x                   28x                 28x                 28x                 28x                 28x                 28x 28x                   28x 28x             28x                 28x 28x                   28x     28x                                 28x                     28x           28x               28x           28x           28x           28x           28x                       28x         28x           28x         28x   28x           28x 28x 28x 28x 28x   28x 28x 28x     30x 30x         30x       30x   30x       30x 30x 41x 41x   5x 5x   5x     36x 36x 36x 1x 1x 35x 30x   35x     30x   30x   30x     30x   30x   1x 1x         4x 4x 4x 4x 4x         1x 1x 1x 1x   1x 1x 1x 1x   1x 1x                   1x 1x             3x 1x 1x 1x 1x 1x               10x     10x 10x       11x 11x     11x 11x   11x       21x 21x 21x 11x 11x             11x 11x 10x   10x 1x 2x       10x     11x   11x           11x 11x 11x     11x 11x 11x       11x     22x 2x 8x           41x 18x 5x     36x       22x 8x 14x             2x 2x 2x 2x     2x       8x 8x 8x 8x 8x 1x   8x       10x 10x 10x 10x 10x       1x 1x 1x 1x 1x 1x   1x         76x     42x 76x           31x      
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { NgClass } from '@angular/common';
import {
  HttpClient,
  HttpErrorResponse,
  HttpEvent,
  HttpEventType,
  HttpHeaders,
  HttpRequest,
  HttpResponse
} from '@angular/common/http';
import {
  booleanAttribute,
  ChangeDetectorRef,
  Component,
  inject,
  input,
  numberAttribute,
  OnChanges,
  output,
  SimpleChanges,
  viewChild
} from '@angular/core';
import {
  addIcons,
  elementCancel,
  elementDelete,
  elementDocument,
  elementRedo,
  SiIconComponent,
  SiStatusIconComponent
} from '@siemens/element-ng/icon';
import { SiInlineNotificationComponent } from '@siemens/element-ng/inline-notification';
import { SiProgressbarComponent } from '@siemens/element-ng/progressbar';
import { SiTranslatePipe, t } from '@siemens/element-translate-ng/translate';
import { Observable, Subscription } from 'rxjs';
import { retry } from 'rxjs/operators';
 
import { SiFileDropzoneComponent } from './si-file-dropzone.component';
import { UploadFile } from './si-file-uploader.model';
 
/**
 * The FileUploadResult is emitted at completion of the file uploading
 * via the `uploadCompleted` emitter. On success the Http `response` from
 * the backend is provided and on failure, the `error` object is available.
 */
export interface FileUploadResult {
  file: string;
  response?: HttpResponse<unknown>;
  error?: Error;
}
 
export interface FileUploadConfig {
  headers: HttpHeaders | string | Record<string, string | number | (string | number)[]> | Headers;
  method: 'POST' | 'PUT' | 'PATCH';
  url: string;
  /** Form field name for the uploaded file. */
  fieldName: string;
  /**
   * Additional form fields added in the HTTP request.
   *
   * @example
   * ```json
   * { upload_user: 'Reiner Zufall', expiry_date: ' 21.12.2012' }
   * ```
   */
  additionalFields?: Record<string, string>;
  /** Specify the server response type */
  responseType?: 'arraybuffer' | 'blob' | 'json' | 'text';
  /** A function to modify the HTTP request sent on the consumer side. */
  handler?: (req: HttpRequest<unknown>) => Observable<HttpEvent<unknown>>;
  /**
   * When `true`, the file will be sent directly w/o the use of `FormData`.
   * You will also need to set the `Content-Type` header when sending binary. See: {@link headers}
   */
  sendBinary?: boolean;
}
 
interface ExtUploadFile extends UploadFile {
  httpErrorText?: string;
  subscription?: Subscription;
  successResponse?: HttpResponse<unknown>;
  fadeOut?: boolean;
}
 
@Component({
  selector: 'si-file-uploader',
  imports: [
    NgClass,
    SiStatusIconComponent,
    SiFileDropzoneComponent,
    SiIconComponent,
    SiInlineNotificationComponent,
    SiProgressbarComponent,
    SiTranslatePipe
  ],
  templateUrl: './si-file-uploader.component.html',
  styleUrl: './si-file-uploader.component.scss'
})
export class SiFileUploaderComponent implements OnChanges {
  /**
   * Text of the link to open the file select dialog (follows `uploadDropText`).
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_FILE_UPLOADER.FILE_SELECT:click to upload`)
   * ```
   */
  readonly uploadTextFileSelect = input(
    t(() => $localize`:@@SI_FILE_UPLOADER.FILE_SELECT:click to upload`)
  );
  /**
   * Text instructing a user to drop the files inside the dropzone.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_FILE_UPLOADER.DROP:Drop files here or`)
   * ```
   */
  readonly uploadDropText = input(t(() => $localize`:@@SI_FILE_UPLOADER.DROP:Drop files here or`));
  /**
   * Text to describe the maximum file size.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_FILE_UPLOADER.MAX_SIZE:Maximum upload size`)
   * ```
   */
  readonly maxFileSizeText = input(
    t(() => $localize`:@@SI_FILE_UPLOADER.MAX_SIZE:Maximum upload size`)
  );
  /**
   * Error message shown when the maximum number of files are reached.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_FILE_UPLOADER.MAX_FILE_REACHED:Maximum number of files reached`)
   * ```
   */
  readonly maxFilesReachedText = input(
    t(() => $localize`:@@SI_FILE_UPLOADER.MAX_FILE_REACHED:Maximum number of files reached`)
  );
  /**
   * Text for the accepted file types.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_FILE_UPLOADER.ACCEPTED_FILE_TYPES:Accepted file types`)
   * ```
   */
  readonly acceptText = input(
    t(() => $localize`:@@SI_FILE_UPLOADER.ACCEPTED_FILE_TYPES:Accepted file types`)
  );
  /**
   * Text used inside the upload button.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_FILE_UPLOADER.UPLOAD:Upload`)
   * ```
   */
  readonly uploadButtonText = input(t(() => $localize`:@@SI_FILE_UPLOADER.UPLOAD:Upload`));
  /**
   * Text used inside the clear button.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_FILE_UPLOADER.CLEAR:Clear`)
   * ```
   */
  readonly clearButtonText = input(t(() => $localize`:@@SI_FILE_UPLOADER.CLEAR:Clear`));
  /**
   * Text shown during the file upload.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_FILE_UPLOADER.UPLOADING:Uploading`)
   * ```
   */
  readonly uploadingText = input(t(() => $localize`:@@SI_FILE_UPLOADER.UPLOADING:Uploading`));
  /**
   * Text shown to remove a file from the file list. Required for a11y.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_FILE_UPLOADER.REMOVE:Remove`)
   * ```
   */
  readonly removeButtonText = input(t(() => $localize`:@@SI_FILE_UPLOADER.REMOVE:Remove`));
  /**
   * Text of cancel button. Shown during upload. Required for a11y.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_FILE_UPLOADER.CANCEL:Cancel`)
   * ```
   */
  readonly cancelButtonText = input(t(() => $localize`:@@SI_FILE_UPLOADER.CANCEL:Cancel`));
  /**
   * Text shown if the upload was successful.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_FILE_UPLOADER.UPLOAD_COMPLETED:Upload completed`)
   * ```
   */
  readonly successTextTitle = input(
    t(() => $localize`:@@SI_FILE_UPLOADER.UPLOAD_COMPLETED:Upload completed`)
  );
  /**
   * Text shown if the upload failed.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_FILE_UPLOADER.UPLOAD_FAILED:Upload failed`)
   * ```
   */
  readonly errorUploadFailed = input(
    t(() => $localize`:@@SI_FILE_UPLOADER.UPLOAD_FAILED:Upload failed`)
  );
  /**
   * On failed upload, show the error received from the server.
   *
   * @defaultValue false
   */
  readonly showHttpError = input(false, { transform: booleanAttribute });
  /**
   * Text shown to indicate that an incorrect file type was added to file list.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_FILE_UPLOADER.ERROR_FILE_TYPE:Incorrect file type selected`)
   * ```
   */
  readonly errorTextFileType = input(
    t(() => $localize`:@@SI_FILE_UPLOADER.ERROR_FILE_TYPE:Incorrect file type selected`)
  );
  /**
   * Message or translation key if file exceeds the maximum file size limit.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_FILE_UPLOADER.ERROR_FILE_SIZE_EXCEEDED:File exceeds allowed maximum size`)
   * ```
   */
  readonly errorTextFileMaxSize = input(
    t(
      () =>
        $localize`:@@SI_FILE_UPLOADER.ERROR_FILE_SIZE_EXCEEDED:File exceeds allowed maximum size`
    )
  );
  /**
   * Config for HTTP request to upload file.
   *
   * @defaultValue
   * ```
   * {
   *     headers: new HttpHeaders({ 'Accept': 'application/json' }),
   *     method: 'POST',
   *     url: '',
   *     fieldName: 'upload_file',
   *     responseType: 'json'
   *   }
   * ```
   */
  readonly uploadConfig = input<FileUploadConfig>({
    headers: new HttpHeaders({ 'Accept': 'application/json' }),
    method: 'POST',
    url: '',
    fieldName: 'upload_file',
    responseType: 'json'
  });
  /**
   * Define which file types are suggested in file browser.
   * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#attr-accept
   */
  readonly accept = input<string>();
  /**
   * Define maximal allowed file size in bytes.
   *
   * @defaultValue undefined
   */
  readonly maxFileSize = input<number | undefined, unknown>(undefined, {
    transform: numberAttribute
  });
  /**
   * Define maximal allowed number of files.
   * When {@link directoryUpload} is enabled, this will have no effect.
   * @defaultValue 10
   */
  readonly maxFiles = input(10, { transform: numberAttribute });
  /**
   * Maximum number of concurrent uploads.
   *
   * @defaultValue 3
   */
  readonly maxConcurrentUploads = input(3, { transform: numberAttribute });
  /**
   * Numbers of retries for failed uploads.
   *
   * @defaultValue 0
   */
  readonly retries = input(0, { transform: numberAttribute });
  /**
   * Auto-upload mode - automatically start upload once files are added.
   *
   * @defaultValue false
   */
  readonly autoUpload = input(false, { transform: booleanAttribute });
  /**
   * Disable the upload button.
   *
   * @defaultValue false
   */
  readonly disableUpload = input(false, { transform: booleanAttribute });
 
  /**
   * Enable directory upload mode.
   * When enabled, the file input will accept directories and upload all files within as a flat list.
   * The hierarchy of the directory will not be preserved.
   * The `maxFiles` property will have no effect when `directoryUpload` is enabled.
   *
   * **Note:** This feature is not yet available for safari (iOS)
   *
   * @defaultValue false
   */
  readonly directoryUpload = input(false, { transform: booleanAttribute });
 
  /**
   * Emits when a user press cancel during upload. The event provides the file details.
   */
  readonly uploadCanceled = output<UploadFile>();
 
  /**
   * Output callback event will provide you if upload is finished. If an error
   * occurred it will be emitted.
   */
  readonly uploadCompleted = output<FileUploadResult>();
 
  /**
   * Output which fires whenever new files are added to or removed from the uploader.
   */
  readonly filesChanges = output<UploadFile[]>();
 
  protected readonly icons = addIcons({
    elementCancel,
    elementDelete,
    elementDocument,
    elementRedo
  });
  protected files: ExtUploadFile[] = [];
  protected pending = 0;
  protected uploading = 0;
  protected uploadEnabled = false;
  protected maxFilesReached = false;
 
  private readonly dropZone = viewChild.required<SiFileDropzoneComponent>('dropZone');
  private cdRef = inject(ChangeDetectorRef);
  private http? = inject(HttpClient, { optional: true });
 
  ngOnChanges(changes: SimpleChanges): void {
    if (changes.maxFiles || changes.disableUpload) {
      this.updateStates();
    }
  }
 
  protected handleFiles(files: UploadFile[]): void {
    Iif (!files?.length) {
      return;
    }
 
    const maxFiles = this.maxFiles();
    // for single-file case, replace exiting file if any
    Iif (maxFiles === 1 && this.files.length) {
      this.reset(false);
    }
 
    let numValid = this.countValid();
    for (const file of files) {
      const duplicate = this.isDuplicate(file);
      if (duplicate) {
        // in case this is duplicated: reset if already uploaded or not handled yet
        if (duplicate.status !== 'uploading' && duplicate.status !== 'queued') {
          Object.assign(duplicate, file);
        }
        continue;
      }
 
      const canAdd = numValid + 1 <= maxFiles;
      const valid = file.status === 'added';
      if (valid && !canAdd) {
        this.maxFilesReached = true;
        break;
      } else if (valid) {
        numValid++;
      }
      this.files.push(file);
    }
 
    this.files.sort((a, b) => a.fileName.localeCompare(b.fileName));
 
    this.filesChanges.emit(this.files.slice());
 
    this.updateStates();
 
    // needed for drag drop of directory
    this.cdRef.markForCheck();
 
    if (this.autoUpload()) {
      // allow concurrent uploads for auto upload mode.
      this.uploadEnabled = true;
      this.fileUpload(false);
    }
  }
 
  protected removeFile(index: number): void {
    if (index >= 0) {
      this.files.splice(index, 1);
      this.filesChanges.emit(this.files.slice());
      this.dropZone().reset();
      this.updateStates();
    }
  }
 
  protected cancelUpload(file: ExtUploadFile): void {
    if (file.subscription) {
      file.subscription.unsubscribe();
      file.subscription = undefined;
      this.uploading--;
    }
    this.pending--;
    file.status = 'added';
    file.progress = 0;
    this.updateStates();
 
    const { status, fileName, size, progress } = file;
    this.uploadCanceled.emit({
      status,
      fileName,
      size,
      progress,
      file: file.file
    });
  }
 
  protected retryUpload(file: UploadFile): void {
    file.status = 'added';
    this.doUpload([file], true);
  }
 
  /**
   * Reset the state.
   */
  reset(emit = true): void {
    this.files.forEach(f => f.subscription?.unsubscribe());
    this.files = [];
    this.dropZone().reset();
    this.updateStates();
    if (emit) {
      this.filesChanges.emit([]);
    }
  }
 
  /**
   * Uploads the file
   */
  fileUpload(doRetry = true): void {
    Iif (!this.uploadEnabled) {
      return;
    }
    this.uploadEnabled = false;
    this.doUpload(this.files, doRetry);
  }
 
  private doUpload(files: UploadFile[], doRetry: boolean): void {
    for (const file of files) {
      Iif (file.status !== 'added' && (!doRetry || file.status !== 'error')) {
        continue;
      }
      this.pending++;
      file.status = 'queued';
    }
    this.processQueue();
  }
 
  private processQueue(): void {
    for (let i = 0; i < this.files.length && this.uploading < this.maxConcurrentUploads(); i++) {
      const file = this.files[i];
      if (file.status === 'queued') {
        this.uploading++;
        this.uploadOneFile(file);
      }
    }
  }
 
  private uploadOneFile(file: ExtUploadFile): void {
    let formData: FormData | undefined;
    const config = this.uploadConfig();
    if (!config.sendBinary) {
      formData = new FormData();
 
      if (config.additionalFields) {
        Object.keys(config.additionalFields).forEach(key => {
          formData!.append(key, config.additionalFields![key]);
        });
      }
      // this needs to be last for AWS
      formData.append(config.fieldName, file.file, file.fileName);
    }
    const headers =
      config.headers instanceof HttpHeaders ? config.headers : new HttpHeaders(config.headers);
 
    const req = new HttpRequest(config.method, config.url, formData ?? file.file, {
      headers,
      responseType: config.responseType,
      reportProgress: true
    });
 
    file.status = 'uploading';
    file.errorText = undefined;
    file.httpErrorText = undefined;
 
    const requestHandler =
      config.handler ??
      (this.http ? (r: HttpRequest<unknown>) => this.http!.request(r) : undefined);
    Iif (!requestHandler) {
      return;
    }
 
    file.subscription = requestHandler(req)
      .pipe(retry(this.retries()))
      .subscribe({
        next: event => this.handleUploadEvent(file, event),
        error: (error: HttpErrorResponse) => this.handleUploadError(file, error),
        complete: () => this.handleUploadComplete(file)
      });
  }
 
  // this is a light check for duplicate file - name and size only, not content!
  private isDuplicate(file: UploadFile): UploadFile | null {
    for (const uploadFile of this.files) {
      if (uploadFile.file.name === file.file.name && uploadFile.file.size === file.file.size) {
        return uploadFile;
      }
    }
    return null;
  }
 
  private handleUploadEvent(file: ExtUploadFile, httpEvent: HttpEvent<unknown>): void {
    if (httpEvent instanceof HttpResponse) {
      file.successResponse = httpEvent as HttpResponse<unknown>;
    } else Iif (httpEvent.type === HttpEventType.UploadProgress && httpEvent.total) {
      file.progress = Math.floor((100 * httpEvent.loaded) / httpEvent.total);
      this.cdRef.markForCheck();
    }
  }
 
  private handleUploadError(file: ExtUploadFile, error: HttpErrorResponse): void {
    this.uploadCompleted.emit({ file: file.fileName, error });
    file.status = 'error';
    file.errorText = this.errorUploadFailed();
    Iif (this.showHttpError() && error.status && error.statusText) {
      file.httpErrorText = `${error.status}: ${error.statusText}`;
    }
    this.oneUploadDone(file);
  }
 
  private handleUploadComplete(file: ExtUploadFile): void {
    this.uploadCompleted.emit({ file: file.fileName, response: file.successResponse });
    file.status = 'success';
    file.progress = 100;
    file.successResponse = undefined;
    if (this.autoUpload()) {
      this.fadeOut(file);
    }
    this.oneUploadDone(file);
  }
 
  private oneUploadDone(file: ExtUploadFile): void {
    file.subscription = undefined;
    this.pending--;
    this.uploading--;
    this.updateStates();
    this.processQueue();
  }
 
  private fadeOut(file: ExtUploadFile): void {
    setTimeout(() => {
      file.fadeOut = true;
      this.cdRef.markForCheck();
      setTimeout(() => {
        this.removeFile(this.files.indexOf(file));
        this.cdRef.markForCheck();
      }, 500);
      this.cdRef.markForCheck();
    }, 3500);
  }
 
  private updateStates(): void {
    this.uploadEnabled =
      !this.disableUpload() &&
      !this.pending &&
      this.files.some(f => f.status === 'added' || f.status === 'error');
    Iif (this.maxFilesReached && this.countValid() < this.maxFiles()) {
      this.maxFilesReached = false;
    }
  }
 
  private countValid(): number {
    return this.files.reduce<number>((acc, f) => acc + (f.status !== 'invalid' ? 1 : 0), 0);
  }
}