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

atinc / ngx-tethys / 5fa9630c-19a1-4ee7-af3d-6a0c3535952a

08 Oct 2024 08:24AM UTC coverage: 90.438% (+0.007%) from 90.431%
5fa9630c-19a1-4ee7-af3d-6a0c3535952a

push

circleci

minlovehua
refactor: refactor all control-flow directives to new control-flow #TINFR-381

5511 of 6738 branches covered (81.79%)

Branch coverage included in aggregate %.

98 of 104 new or added lines in 58 files covered. (94.23%)

113 existing lines in 17 files now uncovered.

13253 of 14010 relevant lines covered (94.6%)

991.73 hits per line

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

81.36
/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,
503✔
35
    y: 0
503✔
36
};
487!
37
const IMAGE_MAX_ZOOM = 3;
38
const IMAGE_MIN_ZOOM = 0.1;
503✔
39
const HORIZONTAL_SPACE = 100 * 2; // left: 100px; right: 100px
40
const VERTICAL_SPACE = 96 + 106; // top: 96px; bottom: 106px
41

38✔
42
/**
38!
UNCOV
43
 * 图片预览组件
×
44
 * @name thy-image-preview
45
 * @order 20
38✔
46
 */
47
@Component({
48
    selector: 'thy-image-preview',
26✔
49
    exportAs: 'thyImagePreview',
10!
50
    templateUrl: './image-preview.component.html',
51
    changeDetection: ChangeDetectionStrategy.OnPush,
10!
52
    encapsulation: ViewEncapsulation.None,
53
    host: {
54
        class: 'thy-image-preview-wrap',
55
        '[class.thy-image-preview-moving]': 'isDragging'
56
    },
57
    standalone: true,
18✔
58
    imports: [ThyTooltipDirective, ThyAction, CdkDrag, ThyLoading, ThyIcon, ThyActions, ThyDivider, ThyCopyDirective]
18✔
59
})
18✔
60
export class ThyImagePreview implements OnInit {
18✔
61
    @Output() downloadClicked: EventEmitter<ThyImageInfo> = new EventEmitter();
18✔
62

18✔
63
    private readonly destroyRef = inject(DestroyRef);
18✔
64

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

151
    private rotate: number;
18✔
152

18✔
153
    get previewImage(): InternalImageInfo {
18✔
154
        const image = this.images[this.previewIndex];
155
        if (image.size) {
156
            image.size = isNumber(image.size) ? humanizeBytes(image.size) : image.size;
17✔
157
        }
158
        return image;
159
    }
2✔
160

161
    get previewImageOriginSrc() {
162
        let imageSrc = this.previewImage.origin?.src || this.previewImage.src;
18✔
163
        if (imageSrc.startsWith('./')) {
164
            return window.location.host + '/' + imageSrc.split('./')[1];
UNCOV
165
        }
×
166
        return imageSrc;
167
    }
168

169
    get defaultZoom(): number {
170
        if (this.previewConfig?.zoom && this.previewConfig?.zoom > 0) {
1✔
171
            return this.previewConfig.zoom >= IMAGE_MAX_ZOOM
1✔
172
                ? IMAGE_MAX_ZOOM
1✔
173
                : this.previewConfig.zoom <= IMAGE_MIN_ZOOM
1✔
174
                  ? IMAGE_MIN_ZOOM
1✔
175
                  : this.previewConfig.zoom;
1✔
176
        }
1✔
177
    }
178

179
    @ViewChild('imgRef', { static: false }) imageRef!: ElementRef<HTMLImageElement>;
1✔
180
    @ViewChild('imagePreviewWrapper', { static: true }) imagePreviewWrapper!: ElementRef<HTMLElement>;
1✔
181

1✔
182
    constructor(
183
        public thyDialog: ThyDialog,
184
        public thyFullscreen: ThyFullscreen,
5✔
185
        private cdr: ChangeDetectorRef,
5✔
186
        private ngZone: NgZone,
5✔
187
        private notifyService: ThyNotifyService,
5!
188
        private host: ElementRef<HTMLElement>,
5✔
189
        private sanitizer: DomSanitizer
190
    ) {}
5✔
191

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

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

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

225
    setFitScreen() {
21!
UNCOV
226
        this.reset();
×
227
        this.isInsideScreen = true;
228
        this.updatePreviewImage();
21✔
229
    }
5✔
230

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

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

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

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

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

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

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

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

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

376
    viewOriginal() {
377
        window.open(this.previewImage?.origin?.src || this.previewImage.src, '_blank');
378
    }
UNCOV
379

×
380
    rotateRight(): void {
×
381
        this.rotate += 90;
×
382
        this.updatePreviewImageTransform();
383
    }
384

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

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

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

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

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

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

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

455
    private updatePreviewImageWrapperTransform(): void {
456
        this.previewImageWrapperTransform = `translate3d(${this.position.x}px, ${this.position.y}px, 0)`;
457
    }
458
}
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

© 2025 Coveralls, Inc