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 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 | import { Optional, Component, Input, OnInit, OnChanges, OnDestroy, forwardRef } from '@angular/core'; import { Output, EventEmitter } from '@angular/core'; import { ViewChild, ElementRef } from '@angular/core'; import { ModalController } from '@ionic/angular'; import { ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core'; import { DomSanitizer, SafeUrl } from '@angular/platform-browser'; import { AbstractControl, FormGroup, FormGroupDirective } from '@angular/forms'; import { ControlContainer, ControlValueAccessor } from "@angular/forms"; import { NG_VALUE_ACCESSOR } from "@angular/forms"; import { Subscription } from 'rxjs'; import { AppConstants } from '@unpispas/upp-defs'; import { languageSupport, languageService } from '@unpispas/upp-base'; import { httpService } from '@unpispas/upp-base'; import { preloadService } from '@unpispas/upp-base'; import { viewService } from '@unpispas/upp-base'; /** * The `UppModalCropComponent` is a modal component used for cropping images. * It is designed to work within an Ionic modal context and accepts an image and its desired dimensions. * * @remarks * This component extends the `languageSupport` class, providing multi-language support. * It interacts with Ionic's `ModalController` for presenting and dismissing the modal. * * @selector `upp-modal-crop-image` * @templateUrl `./upp-modal.html` * @styleUrls `./upp-modal.scss` * * @example * ```typescript * const modal = await this.modalCtrl.create({ * component: UppModalCropComponent, * componentProps: { * image: imageData, * height: 200, * width: 200 * } * }); * * modal.onDidDismiss().then((result) => { * console.log('Cropped Image:', result.data); * }); * ``` */ @Component({ selector: 'upp-modal-crop-image', templateUrl:'./upp-modal.html', styleUrls: [ './upp-modal.scss' ] }) export class UppModalCropComponent extends languageSupport implements OnDestroy { /** The image to be cropped. */ @Input() image: any = null; /** The desired height of the cropped image. */ @Input() height = 0; /** The desired width of the cropped image. */ @Input() width = 0; /** * Indicates if the component has fully loaded. * @defaultValue `false` */ public _loaded = false; /** * Constructs the `UppModalCropComponent` and injects necessary dependencies. * @param lang Language service for multi-language support. * @param modalCtrl Controller for managing the modal. * @param params Service for accessing modal parameters. * @param view View service for UI-related functionalities. */ constructor(private lang: languageService, private modalCtrl: ModalController, public view: viewService) { super(lang, null); } /** * Cleans up resources when the modal is destroyed. */ ngOnDestroy(){ super.OnDestroy(); } /** * Dismisses the modal with the cropped image data. * @param data The cropped image data. */ async OnCrop(data: any){ (document.activeElement as HTMLElement)?.blur(); await this.modalCtrl.dismiss(data); } /** * Closes the modal without returning any data. */ async CloseModal() { (document.activeElement as HTMLElement)?.blur(); await this.modalCtrl.dismiss(null); } } /** * The `UppImageComponent` is a versatile image component with cropping capabilities, lazy loading, * and base64 image transformation. It is compatible with Angular's reactive forms as a `ControlValueAccessor`. * * @remarks * This component supports both readonly and editable modes. * It uses a modal-based cropping interface (`UppModalCropComponent`) to allow users to crop images before upload. * * @selector `upp-image` * @templateUrl `./upp-image.html` * @styleUrls `./upp-image.scss` * @providers `NG_VALUE_ACCESSOR` * @changeDetection `ChangeDetectionStrategy.OnPush` * * @example * ```html * <upp-image * [readonly]="false" * [src]="imageSource" * [crheight]="200" * [crwidth]="200" * (Changed)="onImageChange($event)"> * </upp-image> * ``` */ @Component({ selector: 'upp-image', templateUrl:'./upp-image.html', styleUrls: [ './upp-image.scss' ], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => UppImageComponent), multi: true } ], changeDetection: ChangeDetectionStrategy.OnPush }) export class UppImageComponent extends languageSupport implements ControlValueAccessor, OnInit, OnChanges, OnDestroy { /** * Determines if the component is in readonly mode. * @defaultValue `true` */ @Input() readonly = true; /** * The name of the form control this input is bound to. * @defaultValue `''` */ @Input() formControlName = ''; /** * The source of the image. Can be a URL or a base64 string. * @defaultValue `null` */ @Input() src: string | null = null; /** * The height constraint for cropping. * @defaultValue `'0'` */ @Input() crheight = '0'; /** * The width constraint for cropping. * @defaultValue `'0'` */ @Input() crwidth = '0'; /** * Tracks the image loading mode (`lazy` or `eager`). * @defaultValue `'lazy'` */ public _loading = 'lazy'; /** optional FromGroup */ public formGroup: FormGroup | null = null public formControl: AbstractControl | null = null; /* eslint-disable @typescript-eslint/no-unused-vars */ /** Callback to notify Angular Forms when the value changes. */ private _onChangeCallback = (v: any) => { // nothing to do (required by angular) } /** Callback to notify Angular Forms when the input is touched. */ private _onTouchCallback = () => { // nothing to do (required by angular) } /* eslint-enable @typescript-eslint/no-unused-vars */ /** * Image element reference in the template. */ @ViewChild('image', {static: false}) _image: ElementRef | null = null; /** * Determines if the image source requires the `crossorigin` attribute for server images. * * @remarks * The `_cors` getter checks if the `src` is an HTTP URL that is external to the base URL. * This is used to handle cross-origin requests for server-hosted images. * * @returns `true` if the `crossorigin` attribute should be used; otherwise, `false`. */ get _cors(): boolean{ // use crossorigin for server images Iif (this.src){ return !this.src.startsWith('http') || (!!this.src && (this.src.startsWith(AppConstants.baseURL))); } return false; } private b64: string | null = null; /** * Private accessor for the base64-encoded value of the image. * * @remarks * This getter retrieves the stored base64 representation of the image (`b64`). * It is used internally for managing the image's state. * * @returns The base64 string of the image, or `null` if not available. */ private get _value(){ return this.b64; } /** * Private setter for the base64-encoded value of the image. * * @remarks * This setter updates the base64 representation (`b64`) and synchronizes it with * the `src` property. It also triggers change detection to update the UI. * * @param value The new base64 value for the image. */ private set _value(value){ this.b64 = value; this.src = value; this.change.markForCheck(); } private _cachesrc: SafeUrl | null = null; /** * Gets the current source of the image, which may be the base64 value, a cached value, * or the original source URL. * * @returns The effective source of the image (`SafeUrl`, string, or `null`). */ get _source(): SafeUrl | string | null{ return this._value || this._cachesrc || this.src; } /** * Sets the current source of the image and ensures it is sanitized if necessary. * * @remarks * This setter uses Angular's `DomSanitizer` to handle potentially unsafe URLs. * It stores the sanitized or safe value in `_cachesrc` and triggers change detection. * * @param value The new source of the image, which can be a URL, a base64 string, or `SafeUrl`. */ private set _source(value: string | SafeUrl | null){ const _isSafeUrl = (value: string | SafeUrl): value is SafeUrl => { return typeof value === 'object' && value !== null && ('changingThisBreaksApplicationSecurity' in value); } Iif (value){ this._cachesrc = _isSafeUrl(value) ? value : this.sanitizer.bypassSecurityTrustUrl(value); } this.change.markForCheck(); } private c64: any = null; /** * Retrieves the base64-encoded string of the image. * * @remarks * The `Base64` getter uses a `Promise` to asynchronously generate a base64-encoded * string from the image source. If the image is already processed, it returns the cached value (`c64`). * * @returns A `Promise` that resolves to the base64 string of the image, or `null` if processing fails. */ get Base64() { return new Promise((resolve) =>{ if (!this.c64){ const _img = new Image(); _img.onload = () => { const _cnv = document.createElement("canvas"); const _ctx = _cnv.getContext("2d"); Iif (_cnv && _ctx) { _cnv.width = _img.naturalWidth; _cnv.height = _img.naturalHeight; _ctx.drawImage(_img, 0, 0); const _dataurl = _cnv.toDataURL("image/png"); this.c64 = _dataurl.split(',', 2)[1]; resolve(this.c64); } resolve(null); } const _source = this._source as unknown as string; Iif (_source){ _img.crossOrigin = "Anonymous"; _img.src = _source; } } else { resolve(this.c64); } }); } /** * Constructs the `UppImageComponent` and injects necessary dependencies. * * @param lang Language service for multi-language support. * @param change Change detector for triggering view updates. * @param controlContainer Provides access to the form control's parent `FormGroup`, enabling integration with reactive forms. * @param http HTTP service for tracking online status and connectivity. * @param preload Preload service for caching and optimizing image loading. * @param sanitizer Sanitizer for handling and securing image URLs. * @param modalCtrl Controller for managing modal interactions, such as cropping images. * * @remarks * - If the component is used inside a reactive form, it will attempt to retrieve its associated `FormControl` from the `FormGroup`. * - Implements `ControlValueAccessor` to allow two-way binding with Angular forms. * - Supports image preprocessing, caching, and transformations (e.g., EXIF orientation adjustments). */ constructor(private lang: languageService, private change: ChangeDetectorRef, @Optional() private controlContainer: ControlContainer, private http: httpService, private preload: preloadService, private sanitizer: DomSanitizer, private modalCtrl: ModalController){ super(lang, change); } /** * Tracks whether the image has fully loaded. * @defaultValue `false` */ public _loaded = false; /** * Tracks the online status of the application. * @defaultValue `true` */ public _online = true; /** * Checks whether the current image source is cached. * @returns `true` if the image source is cached; otherwise, `false`. */ get IsCached(): boolean{ Iif (this.src){ return !!this.preload.Recover(this.src); } return true; } /** * Determines whether the image is visible. * Combines the `_loaded` state and whether the image is cached. * @returns `true` if the image is either loaded or cached; otherwise, `false`. */ get IsVisible(){ return this._loaded || this.IsCached; } /** * Updates the `_loaded` state when the image finishes loading. * Triggers change detection to update the view. */ OnLoaded(){ this._loaded = true; this.change.markForCheck(); } private _online_subscription: Subscription | null = null; private _form_subscription: Subscription | null = null; /** * Sets the online status and manages the online subscription. * @param value The new online status (`true` for online, `false` for offline). */ set Online(value: boolean){ this._online = value; Iif (this._online && this._online_subscription){ this._online_subscription.unsubscribe(); this._online_subscription = null; } this.change.markForCheck(); } /** * Initializes the component and subscribes to the online status. */ ngOnInit() { this._online = this.http.IsOnline; Iif (!this._online){ this._online_subscription = this.http.OnOnline.subscribe( data => { this.Online = data; }); } Iif (this.controlContainer && this.controlContainer instanceof FormGroupDirective){ this.formGroup = this.controlContainer.form; } this.formControl = (this.formGroup && this.formControlName) ? this.formGroup.get(this.formControlName) : null; Iif (this.formControl){ this.value = this.formControl.value || null; this._form_subscription = this.formControl.valueChanges.subscribe( () => { this.value = this.formControl?.value || null; }); } } /** * Handles changes to the input properties, such as the image source. */ ngOnChanges(){ this.c64 = null; this.b64 = null; if (!this.src){ this._loaded = true; return; // no src for image? } else { this._cachesrc = this.preload.Recover(this.src); Iif (!this._cachesrc){ this.preload.Enqueue(this.src, (safeurl) => { this._loading = 'eager'; Iif (safeurl){ this._source = safeurl; } this.change.markForCheck(); }); } } } /** * Cleans up subscriptions and resources when the component is destroyed. */ ngOnDestroy(){ super.OnDestroy(); Iif (this._online_subscription){ this._online_subscription.unsubscribe(); this._online_subscription = null; } Iif (this._form_subscription){ this._form_subscription.unsubscribe(); this._form_subscription = null; } } /** * Clears this image source */ fileDelete(){ this.value = null; } /** * Opens a modal for cropping the image. * @param _imagesrc The image source to crop. * @returns A promise that resolves to a boolean indicating whether cropping was successful. * @private */ private async _showCropModal(_imagesrc: any): Promise<boolean> { const _image = new Image(); _image.src = _imagesrc; const modal = await this.modalCtrl.create({ component: UppModalCropComponent, componentProps: { image: _image, height: Number(this.crheight), width: Number(this.crwidth), } }); await modal.present(); const { data } = await modal.onDidDismiss(); Iif (data) { this.value = data; } return true; } /** * Emits an event when the image is changed. */ @Output() Changed = new EventEmitter<any>(); /** * Emits the `Changed` event when an image is modified. * @param event The change event from the file input. */ OnChange(event: Event){ return new Promise((resolve) => { const input = event.target as HTMLInputElement; if (input.files && input.files[0]) { this._readImage(input.files[0]) .then((dataURL) => { this._showCropModal(dataURL).then( () => { resolve(true); }); }); input.value = ''; this.Changed.emit(); } else { // no file selected resolve(false); input.value = ''; this.Changed.emit(); } }); } /************************************************/ /* adjust image according to exif information */ /************************************************/ // https://stackoverflow.com/questions/7584794/accessing-jpeg-exif-rotation-data-in-javascript-on-the-client-side/32490603#32490603 /** * Handles the EXIF orientation of an image. * Extracts the orientation value from the image's EXIF data. * @param event The file load event containing the image data. * @returns The orientation value or an error code (`-2` for non-JPEG, `-1` for undefined). * @private */ private _getOrientation(event: any) { const view = new DataView(event.target.result); Iif (view.getUint16(0, false) != 0xFFD8) { return -2; // not a JPEG } const length = view.byteLength; let offset = 2; while (offset < length) { Iif (view.getUint16(offset+2, false) <= 8){ return -1; // not defined } const marker = view.getUint16(offset, false); offset += 2; if (marker == 0xFFE1) { Iif (view.getUint32(offset += 2, false) != 0x45786966) { return -1; // not defined } const little = view.getUint16(offset += 6, false) == 0x4949; offset += view.getUint32(offset + 4, little); const tags = view.getUint16(offset, little); offset += 2; for (let i = 0; i < tags; i++) { Iif (view.getUint16(offset + (i * 12), little) == 0x0112) { return view.getUint16(offset + (i * 12) + 8, little); } } } else if ((marker & 0xFF00) != 0xFF00) { break; } else { offset += view.getUint16(offset, false); } } return -1; // not defined }; // https://github.com/mshibl/Exif-Stripper/blob/master/exif-stripper.js /** * Removes EXIF metadata from the provided image buffer. * Extracts the image data without metadata for security and size efficiency. * @param event The file load event containing the image buffer. * @returns A Blob containing the image data without EXIF metadata, or `null` if failed. * @private */ private _removeExif(event: any){ const imageArrayBuffer = event.target.result; const dv = new DataView(imageArrayBuffer); const pieces = []; let offset = 0, recess = 0, i = 0; Iif (dv.getUint16(offset) == 0xffd8){ offset += 2; let app1 = dv.getUint16(offset); offset += 2; while (offset < dv.byteLength){ if (app1 == 0xffe1){ pieces[i] = {recess:recess,offset:offset-2}; recess = offset + dv.getUint16(offset); i++; } else Iif (app1 == 0xffda){ break; } offset += dv.getUint16(offset); app1 = dv.getUint16(offset); offset += 2; } Iif (pieces.length > 0){ const newPieces = []; pieces.forEach(function(v){ newPieces.push(imageArrayBuffer.slice(v.recess, v.offset)); }, this); newPieces.push(imageArrayBuffer.slice(recess)); return new Blob(newPieces, {type: 'image/jpeg'}); } } return null; } // https://stackoverflow.com/questions/20600800/js-client-side-exif-orientation-rotate-and-mirror-jpeg-images /** * Applies transformations to an image based on EXIF orientation data. * Ensures the image is correctly rotated or flipped according to the metadata. * @param callback A callback to handle the transformed image's data URL. * @param orientation The EXIF orientation value. * @param image The image element to be transformed. * @private */ private _imgTransform(callback: (dataUrl: string) => void, orientation: number, image: HTMLImageElement){ const canvas = document.createElement('canvas'); let w = image.width let h = image.height; const context = canvas.getContext('2d'); Iif (context){ const max = 1024; // max side: 1024 pixels let scale = 1; Iif ((w > h) && (w > max)){ scale = max/w; } Iif ((h >= w) && (h > max)){ scale = max/h; } w = Math.round(w * scale); h = Math.round(h * scale); if ((orientation > 4) && (orientation < 9)) { canvas.width = h; canvas.height = w; } else { canvas.width = w; canvas.height = h; } let tm = [ 1, 0, 0, 1, 0, 0 ]; // transformation matrix switch (orientation) { case 2: tm = [ -1, 0, 0, 0, image.width, 0 ]; break; case 3: tm = [ -1, 0, 0, -1, image.width, image.height ]; break; case 4: tm = [ 1, 0, 0, -1, 0, image.height ]; break; case 5: tm = [ 0, 1, 1, 0, 0, 0 ]; break; case 6: tm = [ 0, 1, -1, 0, image.height, 0 ]; break; case 7: tm = [ 0, -1, -1, 0, image.height, image.width ]; break; case 8: tm = [ 0, -1, 1, 0, 0, image.width ]; break; } context.transform(scale, 0, 0, scale, 0, 0); context.transform(tm[0], tm[1], tm[2], tm[3], tm[4], tm[5]); context.drawImage(image, 0, 0); } callback(canvas.toDataURL()); } /** * Reads an image file and processes it, applying EXIF-based transformations and removing metadata. * @param file The image file to be processed. * @returns A promise that resolves to the processed image's data URL. * @private */ private async _readImage(file: File): Promise<string> { const removeExifAndTransform = async (arrayBuffer: ArrayBuffer, orientation: number): Promise<string> => { const blob = this._removeExif({ target: { result: arrayBuffer } }); const image = new Image(); return new Promise((resolve) => { image.onload = () => { this._imgTransform((dataURL) => resolve(dataURL), orientation, image); URL.revokeObjectURL(image.src); }; image.src = URL.createObjectURL(blob || new Blob([arrayBuffer], { type: "image/jpeg" })); }); }; const getOrientation = (arrayBuffer: ArrayBuffer): number => { return this._getOrientation({ target: { result: arrayBuffer } }); }; const fileArrayBuffer = await file.arrayBuffer(); const orientation = getOrientation(fileArrayBuffer); return removeExifAndTransform(fileArrayBuffer, orientation); } /********************************************/ /* get/set accesors */ /********************************************/ @Input() /** * Gets the current value of the image. * * @remarks * The `value` accessor retrieves the image's base64 data (`_value`) if available. * Otherwise, it falls back to the `src` property, which can be a URL or base64 string. * * @returns The base64 representation or the source URL of the image. */ get value(): string | null { return this._value || this.src; } /** * Sets a new value for the image. * * @remarks * The `value` accessor updates the internal `_value` and `src` properties when the * provided value differs from the current `src`. It also triggers change detection, * invokes the registered `ControlValueAccessor` callbacks, and emits the `Changed` event. * * @param v The new value for the image. This can be a base64 string or a URL. */ set value(v: string | null) { Iif (v !== this.src) { this._value = v; this._onChangeCallback(v); this._onTouchCallback(); this.Changed.emit(); } } /********************************************/ /* ControlValueAccessor */ /********************************************/ /** * Implements `ControlValueAccessor` to handle form binding. */ writeValue(value: string | null) { Iif (value !== this.src) { this.value = value; } } /** * Registers a callback for when the value changes. */ registerOnChange(fn: any) { this._onChangeCallback = fn; } /** * Registers a callback for when the control is touched. */ registerOnTouched(fn: any) { this._onTouchCallback = fn; } }; |