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

atinc / ngx-tethys / d589ffc2-a06b-47b9-9dc7-0e8686fc33a0

07 May 2025 02:28AM UTC coverage: 90.272%. Remained the same
d589ffc2-a06b-47b9-9dc7-0e8686fc33a0

push

circleci

web-flow
feat(image): support i18n for image (#3386)

5617 of 6882 branches covered (81.62%)

Branch coverage included in aggregate %.

2 of 2 new or added lines in 1 file covered. (100.0%)

13 existing lines in 1 file now uncovered.

13379 of 14161 relevant lines covered (94.48%)

921.65 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
    Signal,
14
    ViewChild,
15
    ViewEncapsulation,
16
    inject
17
} from '@angular/core';
18
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
19
import { DomSanitizer } from '@angular/platform-browser';
20
import { ThyAction, ThyActions } from 'ngx-tethys/action';
1✔
21
import { ThyCopyDirective, ThyCopyEvent } from 'ngx-tethys/copy';
22
import { ThyDialog } from 'ngx-tethys/dialog';
23
import { ThyDivider } from 'ngx-tethys/divider';
24
import { ThyFullscreen } from 'ngx-tethys/fullscreen';
1✔
25
import { ThyIcon } from 'ngx-tethys/icon';
1✔
26
import { ThyLoading } from 'ngx-tethys/loading';
1✔
27
import { ThyNotifyService } from 'ngx-tethys/notify';
1✔
28
import { ThyTooltipDirective } from 'ngx-tethys/tooltip';
29
import { getClientSize, getFitContentPosition, getOffset, helpers, humanizeBytes, isNumber, isUndefinedOrNull } from 'ngx-tethys/util';
30
import { Observable, fromEvent } from 'rxjs';
31
import { InternalImageInfo, ThyImageInfo, ThyImagePreviewMode, ThyImagePreviewOperation, ThyImagePreviewOptions } from '../image.class';
32
import { fetchImageBlob } from '../utils';
33
import { injectLocale, ThyImageLocale } from 'ngx-tethys/i18n';
1✔
34

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

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

2✔
71
    @Output() downloadClicked: EventEmitter<ThyImageInfo> = new EventEmitter();
72

73
    private readonly destroyRef = inject(DestroyRef);
74

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

161
    private rotate: number;
2✔
162

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

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

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

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

192
    ngOnInit(): void {
5✔
193
        this.initPreview();
194
        this.ngZone.runOutsideAngular(() => {
195
            fromEvent(this.host.nativeElement, 'click')
16✔
196
                .pipe(takeUntilDestroyed(this.destroyRef))
16✔
197
                .subscribe(event => {
16✔
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
                });
6!
206

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

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

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

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

21✔
241
    useCalculateZoomUpdate(isUpdateImageWrapper?: boolean) {
1✔
242
        let img = new Image();
1✔
243
        img.src = this.previewImage.src;
1✔
244
        img.onload = () => {
1✔
245
            const { width: offsetWidth, height: offsetHeight } = getClientSize();
246
            const innerWidth = offsetWidth - HORIZONTAL_SPACE;
20✔
247
            const innerHeight = offsetHeight - VERTICAL_SPACE;
19✔
248
            const { naturalWidth, naturalHeight } = img;
19✔
249
            const xRatio = innerWidth / naturalWidth;
250
            const yRatio = innerHeight / naturalHeight;
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
            }
1✔
257
            this.isLoadingDone = true;
1✔
258
            this.updatePreviewImageTransform();
UNCOV
259
            if (isUpdateImageWrapper) {
×
260
                this.updatePreviewImageWrapperTransform();
×
261
            }
262
            this.cdr.detectChanges();
263
        };
264
    }
265

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

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

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

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

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

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

365
    calculateInsideScreen() {
366
        const width = this.imageRef.nativeElement.offsetWidth * this.zoom;
UNCOV
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
    }
379

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

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

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

1✔
405
    prev() {
406
        if (this.previewIndex > 0) {
407
            this.previewIndex--;
408
            this.isLoadingDone = false;
409
            this.reset();
410
            this.updatePreviewImage();
411
        }
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

© 2026 Coveralls, Inc