Skip to content

Commit 6243cd7

Browse files
committed
feat: improve Crop component initialization with ResizeObserver
- Adjust minimum width and height inputs to default to 100 for better flexibility. - Replace `effect` with ResizeObserver for more reliable shape handling after component load. - Refactor logic to ensure proper crop selection reset when shape is "circle".
1 parent 9062721 commit 6243cd7

File tree

1 file changed

+19
-16
lines changed
  • projects/components/crop/src/crop

1 file changed

+19
-16
lines changed

projects/components/crop/src/crop/crop.ts

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import {
33
ChangeDetectionStrategy,
44
Component,
55
computed,
6-
effect,
76
ElementRef,
87
inject,
98
input,
@@ -34,8 +33,8 @@ type DragHandle =
3433
},
3534
})
3635
export class Crop implements AfterViewInit {
37-
minWidth = input(20);
38-
minHeight = input(20);
36+
minWidth = input(100);
37+
minHeight = input(100);
3938
shape = input<'rectangle' | 'circle'>('rectangle');
4039
selectionApplied = output<CropSelection>();
4140

@@ -47,19 +46,23 @@ export class Crop implements AfterViewInit {
4746
private startDragPosition = signal<{ x: number; y: number } | null>(null);
4847
private startDragSelection = signal<CropSelection | null>(null);
4948

50-
constructor() {
51-
effect(() => {
52-
// Handles dynamic changes of the `shape` input after initialization.
53-
if (this.isCircle() && this.elementRef.nativeElement.offsetWidth > 0) {
54-
this.resetSelectionToSquare();
55-
}
56-
});
57-
}
58-
5949
ngAfterViewInit(): void {
60-
// Handles the initial case when the component loads with shape="circle".
6150
if (this.isCircle()) {
62-
this.resetSelectionToSquare();
51+
const hostEl = this.elementRef.nativeElement;
52+
53+
// If the element already has a size (e.g., cached image), reset immediately.
54+
if (hostEl.offsetWidth > 0 && hostEl.offsetHeight > 0) {
55+
this.resetSelectionToSquare();
56+
} else {
57+
// Otherwise, use ResizeObserver to wait for the host to get its final size.
58+
const observer = new ResizeObserver(() => {
59+
if (hostEl.offsetWidth > 0 && hostEl.offsetHeight > 0) {
60+
this.resetSelectionToSquare();
61+
observer.disconnect(); // We only need to do this once.
62+
}
63+
});
64+
observer.observe(hostEl);
65+
}
6366
}
6467
}
6568

@@ -75,8 +78,8 @@ export class Crop implements AfterViewInit {
7578

7679
this.selection.set({
7780
top: top,
78-
right: left,
79-
bottom: top,
81+
right: (hostWidth - size) / 2,
82+
bottom: (hostHeight - size) / 2,
8083
left: left,
8184
});
8285
}

0 commit comments

Comments
 (0)