• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

atinc / ngx-tethys / 3b40a702-4b4d-4ddb-81a7-a96baae6d682

08 Nov 2024 05:40AM UTC coverage: 90.395% (-0.04%) from 90.431%
3b40a702-4b4d-4ddb-81a7-a96baae6d682

push

circleci

why520crazy
Merge branch 'master' into feat-theme

5503 of 6730 branches covered (81.77%)

Branch coverage included in aggregate %.

424 of 431 new or added lines in 171 files covered. (98.38%)

344 existing lines in 81 files now uncovered.

13150 of 13905 relevant lines covered (94.57%)

999.86 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

81.29
/src/image/preview/image-preview.component.ts
1
import { CdkDrag } from '@angular/cdk/drag-drop';
2

3
import {
4
    ChangeDetectionStrategy,
5
    ChangeDetectorRef,
6
    Component,
7
    DestroyRef,
8
    ElementRef,
9
    EventEmitter,
10
    NgZone,
11
    OnInit,
12
    Output,
13
    ViewChild,
14
    ViewEncapsulation,
15
    inject
16
} from '@angular/core';
17
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
18
import { DomSanitizer } from '@angular/platform-browser';
19
import { ThyAction, ThyActions } from 'ngx-tethys/action';
1✔
20
import { ThyCopyDirective, ThyCopyEvent } from 'ngx-tethys/copy';
21
import { ThyDialog } from 'ngx-tethys/dialog';
22
import { ThyDivider } from 'ngx-tethys/divider';
23
import { ThyFullscreen } from 'ngx-tethys/fullscreen';
1✔
24
import { ThyIcon } from 'ngx-tethys/icon';
1✔
25
import { ThyLoading } from 'ngx-tethys/loading';
1✔
26
import { ThyNotifyService } from 'ngx-tethys/notify';
1✔
27
import { ThyTooltipDirective } from 'ngx-tethys/tooltip';
28
import { getClientSize, getFitContentPosition, getOffset, helpers, humanizeBytes, isNumber, isUndefinedOrNull } from 'ngx-tethys/util';
29
import { Observable, fromEvent } from 'rxjs';
30
import { InternalImageInfo, ThyImageInfo, ThyImagePreviewMode, ThyImagePreviewOperation, ThyImagePreviewOptions } from '../image.class';
31
import { fetchImageBlob } from '../utils';
32

1✔
33
const initialPosition = {
34
    x: 0,
18✔
35
    y: 0
18✔
36
};
18✔
37
const IMAGE_MAX_ZOOM = 3;
18✔
38
const IMAGE_MIN_ZOOM = 0.1;
18✔
39
const HORIZONTAL_SPACE = 100 * 2; // left: 100px; right: 100px
18✔
40
const VERTICAL_SPACE = 96 + 106; // top: 96px; bottom: 106px
18✔
41

18✔
42
/**
18✔
43
 * 图片预览组件
18✔
44
 * @name thy-image-preview
18✔
45
 * @order 20
18✔
46
 */
18✔
47
@Component({
18✔
48
    selector: 'thy-image-preview',
18✔
49
    exportAs: 'thyImagePreview',
18✔
50
    templateUrl: './image-preview.component.html',
18✔
51
    changeDetection: ChangeDetectionStrategy.OnPush,
18✔
52
    encapsulation: ViewEncapsulation.None,
18✔
53
    host: {
18✔
54
        class: 'thy-image-preview-wrap',
18✔
55
        '[class.thy-image-preview-moving]': 'isDragging'
18✔
56
    },
57
    standalone: true,
58
    imports: [ThyTooltipDirective, ThyAction, CdkDrag, ThyLoading, ThyIcon, ThyActions, ThyDivider, ThyCopyDirective]
59
})
60
export class ThyImagePreview implements OnInit {
2✔
61
    thyDialog = inject(ThyDialog);
62
    thyFullscreen = inject(ThyFullscreen);
63
    private cdr = inject(ChangeDetectorRef);
64
    private ngZone = inject(NgZone);
65
    private notifyService = inject(ThyNotifyService);
66
    private host = inject<ElementRef<HTMLElement>>(ElementRef);
67
    private sanitizer = inject(DomSanitizer);
68

2✔
69
    @Output() downloadClicked: EventEmitter<ThyImageInfo> = new EventEmitter();
70

71
    private readonly destroyRef = inject(DestroyRef);
72

73
    images: InternalImageInfo[] = [];
74
    previewIndex: number = 0;
75
    previewConfig: ThyImagePreviewOptions;
76
    previewImageTransform = '';
1✔
77
    previewImageWrapperTransform = '';
78
    zoomDisabled = false;
79
    zoom: number = 1;
80
    position = { ...initialPosition };
81
    isDragging = false;
82
    isLoadingDone = false;
83
    isFullScreen = false;
84
    isInsideScreen = true;
1✔
85
    currentImageMode: ThyImagePreviewMode = 'original-scale';
86
    previewOperations: ThyImagePreviewOperation[];
87
    defaultPreviewOperations: ThyImagePreviewOperation[] = [
88
        {
89
            icon: 'zoom-out',
90
            name: '缩小',
91
            action: (image: ThyImageInfo) => {
92
                this.zoomOut();
1✔
93
            },
94
            type: 'zoom-out'
95
        },
96
        {
97
            icon: 'zoom-in',
98
            name: '放大',
99
            action: (image: ThyImageInfo) => {
100
                this.zoomIn();
1✔
101
            },
102
            type: 'zoom-in'
103
        },
104
        {
105
            icon: 'one-to-one',
106
            name: '原始比例',
107
            action: (image: ThyImageInfo) => {
108
                this.setOriginalSize();
2✔
109
            },
110
            type: 'original-scale'
111
        },
112
        {
113
            icon: 'max-view',
114
            name: '适应屏幕',
115
            action: () => {
116
                this.setFitScreen();
1✔
117
            },
118
            type: 'fit-screen'
119
        },
120
        {
121
            icon: 'expand-arrows',
122
            name: '全屏显示',
123
            action: () => {
124
                this.fullScreen();
125
            },
126
            type: 'full-screen'
127
        },
128
        {
503✔
129
            icon: 'rotate-right',
503✔
130
            name: '旋转',
487!
131
            action: (image: ThyImageInfo) => {
132
                this.rotateRight();
503✔
133
            },
134
            type: 'rotate-right'
135
        },
38✔
136
        {
38!
UNCOV
137
            icon: 'download',
×
138
            name: '下载',
139
            action: (image: ThyImageInfo) => {
38✔
140
                this.download(image);
141
            },
142
            type: 'download'
26✔
143
        },
10!
144
        {
145
            icon: 'preview',
10!
146
            name: '查看原图',
147
            action: () => {
148
                this.viewOriginal();
149
            },
150
            type: 'view-original'
151
        },
18✔
152
        {
18✔
153
            icon: 'link-insert',
18✔
154
            name: '复制链接',
155
            type: 'copyLink'
156
        }
17✔
157
    ];
158

159
    private rotate: number;
2✔
160

161
    get previewImage(): InternalImageInfo {
162
        const image = this.images[this.previewIndex];
18✔
163
        if (image.size) {
164
            image.size = isNumber(image.size) ? humanizeBytes(image.size) : image.size;
UNCOV
165
        }
×
166
        return image;
167
    }
168

169
    get previewImageOriginSrc() {
170
        let imageSrc = this.previewImage.origin?.src || this.previewImage.src;
1✔
171
        if (imageSrc.startsWith('./')) {
1✔
172
            return window.location.host + '/' + imageSrc.split('./')[1];
1✔
173
        }
1✔
174
        return imageSrc;
1✔
175
    }
1✔
176

1✔
177
    get defaultZoom(): number {
178
        if (this.previewConfig?.zoom && this.previewConfig?.zoom > 0) {
179
            return this.previewConfig.zoom >= IMAGE_MAX_ZOOM
1✔
180
                ? IMAGE_MAX_ZOOM
1✔
181
                : this.previewConfig.zoom <= IMAGE_MIN_ZOOM
1✔
182
                  ? IMAGE_MIN_ZOOM
183
                  : this.previewConfig.zoom;
184
        }
5✔
185
    }
5✔
186

5✔
187
    @ViewChild('imgRef', { static: false }) imageRef!: ElementRef<HTMLImageElement>;
5!
188
    @ViewChild('imagePreviewWrapper', { static: true }) imagePreviewWrapper!: ElementRef<HTMLElement>;
5✔
189

190
    ngOnInit(): void {
5✔
191
        this.initPreview();
192
        this.ngZone.runOutsideAngular(() => {
193
            fromEvent(this.host.nativeElement, 'click')
16✔
194
                .pipe(takeUntilDestroyed(this.destroyRef))
16✔
195
                .subscribe(event => {
16✔
196
                    if (
6✔
197
                        (event.target === event.currentTarget ||
6✔
198
                            (this.isInsideScreen && this.imagePreviewWrapper.nativeElement.contains(event.target as HTMLElement))) &&
6✔
199
                        !this.previewConfig?.disableClose
6✔
200
                    ) {
6✔
201
                        this.ngZone.run(() => !this.isFullScreen && this.thyDialog.close());
6✔
202
                    }
6✔
203
                });
6!
204

6✔
205
            fromEvent(this.imagePreviewWrapper.nativeElement, 'mousedown')
206
                .pipe(takeUntilDestroyed(this.destroyRef))
UNCOV
207
                .subscribe(() => {
×
208
                    this.isDragging = !this.isInsideScreen && true;
209
                });
6✔
210
        });
6✔
211
    }
6!
UNCOV
212

×
213
    setOriginalSize() {
214
        this.reset();
6✔
215
        this.currentImageMode = 'fit-screen';
216
        this.zoom = 1;
217
        this.updatePreviewImageTransform();
218
        this.calculateInsideScreen();
21✔
219
        this.isLoadingDone = true;
21!
220
        this.cdr.detectChanges();
UNCOV
221
    }
×
UNCOV
222

×
223
    setFitScreen() {
224
        this.reset();
225
        this.isInsideScreen = true;
21!
UNCOV
226
        this.updatePreviewImage();
×
227
    }
228

21✔
229
    useDefaultZoomUpdate(isUpdateImageWrapper: boolean) {
5✔
230
        this.zoom = this.defaultZoom;
231
        this.isLoadingDone = true;
232
        this.updatePreviewImageTransform();
16✔
233
        if (isUpdateImageWrapper) {
234
            this.updatePreviewImageWrapperTransform();
235
        }
236
        this.cdr.detectChanges();
237
    }
21✔
238

21✔
239
    useCalculateZoomUpdate(isUpdateImageWrapper?: boolean) {
1✔
240
        let img = new Image();
1✔
241
        img.src = this.previewImage.src;
1✔
242
        img.onload = () => {
1✔
243
            const { width: offsetWidth, height: offsetHeight } = getClientSize();
244
            const innerWidth = offsetWidth - HORIZONTAL_SPACE;
20✔
245
            const innerHeight = offsetHeight - VERTICAL_SPACE;
19✔
246
            const { naturalWidth, naturalHeight } = img;
19✔
247
            const xRatio = innerWidth / naturalWidth;
248
            const yRatio = innerHeight / naturalHeight;
249
            const zoom = Math.min(xRatio, yRatio);
1✔
250
            if (zoom > 1) {
1!
251
                this.zoom = 1;
1✔
252
            } else {
1✔
253
                this.zoom = zoom;
1✔
254
            }
1✔
255
            this.isLoadingDone = true;
1✔
256
            this.updatePreviewImageTransform();
UNCOV
257
            if (isUpdateImageWrapper) {
×
UNCOV
258
                this.updatePreviewImageWrapperTransform();
×
259
            }
260
            this.cdr.detectChanges();
261
        };
262
    }
263

264
    updatePreviewImage() {
18✔
265
        this.resolvePreviewImage().subscribe(result => {
1✔
266
            if (!result) {
1✔
267
                // error
5✔
268
                this.isLoadingDone = true;
4✔
269
                return;
270
            }
271
            // image size
1✔
272
            if (!this.previewImage.size && this.previewImage.blob) {
273
                this.previewImage.size = humanizeBytes(this.previewImage.blob.size);
274
            }
275
            if (this.defaultZoom) {
276
                this.useDefaultZoomUpdate(true);
17✔
277
            } else {
278
                this.useCalculateZoomUpdate();
18✔
279
            }
18✔
280
        });
281
    }
282

2✔
283
    resolvePreviewImage() {
2!
284
        return new Observable<Boolean>(subscriber => {
2✔
285
            if (this.previewImage.src.startsWith('blob:')) {
286
                this.previewImage.objectURL = this.sanitizer.bypassSecurityTrustUrl(this.previewImage.src);
287
                subscriber.next(true);
1!
288
                subscriber.complete();
1✔
289
                return;
1✔
290
            }
1!
291
            if (this.previewImage.objectURL || !this.previewConfig.resolveSize) {
1✔
292
                subscriber.next(true);
1✔
293
                subscriber.complete();
294
            } else {
295
                fetchImageBlob(this.previewImage.src).subscribe(
296
                    blob => {
2✔
297
                        const urlCreator = window.URL || window.webkitURL;
1✔
298
                        const objectURL = urlCreator.createObjectURL(blob);
1✔
299
                        this.previewImage.objectURL = this.sanitizer.bypassSecurityTrustUrl(objectURL);
1✔
300
                        this.previewImage.blob = blob;
1✔
301
                        subscriber.next(true);
302
                        subscriber.complete();
303
                    },
304
                    error => {
2✔
305
                        subscriber.next(false);
1✔
306
                        subscriber.complete();
1✔
307
                    }
1✔
308
                );
1✔
309
            }
310
        });
311
    }
312

3✔
313
    initPreview() {
3✔
314
        if (Array.isArray(this.previewConfig?.operations) && this.previewConfig?.operations.length) {
3✔
315
            const defaultOperationsMap = helpers.keyBy(this.defaultPreviewOperations, 'type');
3!
UNCOV
316
            this.previewOperations = this.previewConfig?.operations.map(operation => {
×
317
                if (helpers.isString(operation) && defaultOperationsMap[operation]) {
318
                    return defaultOperationsMap[operation];
319
                } else {
3✔
320
                    return operation as ThyImagePreviewOperation;
321
                }
322
            });
323
        } else {
1!
324
            this.previewOperations = this.defaultPreviewOperations;
325
        }
326
        this.rotate = this.previewConfig?.rotate ?? 0;
1✔
327
        this.updatePreviewImage();
1✔
328
    }
329

330
    download(image: ThyImageInfo) {
1✔
331
        this.downloadClicked.emit(image);
1✔
332
        const src = image.origin?.src || image.src;
1✔
333
        fetchImageBlob(src)
334
            .pipe(takeUntilDestroyed(this.destroyRef))
335
            .subscribe(blob => {
1✔
UNCOV
336
                const urlCreator = window.URL || window.webkitURL;
×
UNCOV
337
                const objectURL = urlCreator.createObjectURL(blob);
×
338
                let a = document.createElement('a');
339
                a.download = image.name || 'default.png';
340
                a.href = objectURL;
UNCOV
341
                a.click();
×
UNCOV
342
            });
×
343
    }
344

UNCOV
345
    zoomIn(): void {
×
346
        if (this.zoom < IMAGE_MAX_ZOOM) {
347
            this.zoom = Math.min(this.zoom + 0.1, IMAGE_MAX_ZOOM);
348
            this.calculateInsideScreen();
349
            this.updatePreviewImageTransform();
2✔
350
            this.position = { ...initialPosition };
1✔
351
        }
1✔
352
    }
1✔
353

1✔
354
    zoomOut(): void {
355
        if (this.zoom > IMAGE_MIN_ZOOM) {
356
            this.zoom = Math.max(this.zoom - 0.1, IMAGE_MIN_ZOOM);
357
            this.calculateInsideScreen();
2✔
358
            this.updatePreviewImageTransform();
1✔
359
            this.position = { ...initialPosition };
1✔
360
        }
1✔
361
    }
1✔
362

363
    calculateInsideScreen() {
364
        const width = this.imageRef.nativeElement.offsetWidth * this.zoom;
365
        const height = this.imageRef.nativeElement.offsetHeight * this.zoom;
×
366
        const { width: clientWidth, height: clientHeight } = getClientSize();
×
367
        if (width >= clientWidth || height >= clientHeight) {
×
368
            this.isInsideScreen = false;
×
369
        } else {
×
UNCOV
370
            this.isInsideScreen = true;
×
UNCOV
371
        }
×
372
    }
×
373

×
374
    viewOriginal() {
375
        window.open(this.previewImage?.origin?.src || this.previewImage.src, '_blank');
376
    }
377

378
    rotateRight(): void {
379
        this.rotate += 90;
×
UNCOV
380
        this.updatePreviewImageTransform();
×
UNCOV
381
    }
×
382

383
    fullScreen(): void {
384
        const targetElement = this.host.nativeElement.querySelector('.thy-image-preview');
385
        this.isFullScreen = true;
4✔
386
        const fullscreenRef = this.thyFullscreen.launch({
4✔
387
            target: targetElement
4✔
388
        });
4✔
389
        fullscreenRef.afterExited().subscribe(() => {
390
            this.isFullScreen = false;
391
            this.cdr.markForCheck();
15✔
392
        });
393
    }
394

5✔
395
    copyLink(event: ThyCopyEvent) {
396
        if (event.isSuccess) {
1✔
397
            this.notifyService.success('复制图片地址成功');
398
        } else {
399
            this.notifyService.error('复制图片地址失败');
400
        }
401
    }
402

1✔
403
    prev() {
404
        if (this.previewIndex > 0) {
405
            this.previewIndex--;
406
            this.isLoadingDone = false;
407
            this.reset();
408
            this.updatePreviewImage();
409
        }
410
    }
411

412
    next() {
413
        if (this.previewIndex < this.images.length - 1) {
414
            this.previewIndex++;
415
            this.isLoadingDone = false;
416
            this.reset();
417
            this.updatePreviewImage();
418
        }
419
    }
420

421
    dragReleased() {
422
        this.isDragging = false;
423
        const width = this.imageRef.nativeElement.offsetWidth * this.zoom;
424
        const height = this.imageRef.nativeElement.offsetHeight * this.zoom;
425
        const { left, top } = getOffset(this.imageRef.nativeElement, window);
426
        const { width: clientWidth, height: clientHeight } = getClientSize();
427
        const isRotate = this.rotate % 180 !== 0;
428
        const fitContentParams = {
429
            width: isRotate ? height : width,
430
            height: isRotate ? width : height,
431
            left,
432
            top,
433
            clientWidth,
434
            clientHeight
435
        };
436
        const fitContentPos = getFitContentPosition(fitContentParams);
437
        if (!isUndefinedOrNull(fitContentPos.x) || !isUndefinedOrNull(fitContentPos.y)) {
438
            this.position = { ...this.position, ...fitContentPos };
439
        }
440
    }
441

442
    private reset(): void {
443
        this.currentImageMode = 'original-scale';
444
        this.rotate = this.previewConfig?.rotate ?? 0;
445
        this.position = { ...initialPosition };
446
        this.cdr.detectChanges();
447
    }
448

449
    private updatePreviewImageTransform(): void {
450
        this.previewImageTransform = `scale3d(${this.zoom}, ${this.zoom}, 1) rotate(${this.rotate}deg)`;
451
    }
452

453
    private updatePreviewImageWrapperTransform(): void {
454
        this.previewImageWrapperTransform = `translate3d(${this.position.x}px, ${this.position.y}px, 0)`;
455
    }
456
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc