integration layer; merge work on indicators from forks with existing ingestion pipeline
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
<div class="viewer">
|
||||
<div class="viewer__toolbar">
|
||||
<button mat-icon-button type="button" [disabled]="pageNumber() <= 1" (click)="previous()" aria-label="Página anterior">
|
||||
<mat-icon aria-hidden="true">chevron_left</mat-icon>
|
||||
</button>
|
||||
<span class="viewer__page-label">Página {{ pageNumber() }} de {{ pageCount() }}</span>
|
||||
<button mat-icon-button type="button" [disabled]="pageNumber() >= pageCount()" (click)="next()" aria-label="Página siguiente">
|
||||
<mat-icon aria-hidden="true">chevron_right</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@if (loading()) {
|
||||
<mat-progress-bar mode="indeterminate" aria-label="Cargando página"></mat-progress-bar>
|
||||
}
|
||||
@if (error()) {
|
||||
<p class="viewer__error" role="alert">{{ error() }}</p>
|
||||
}
|
||||
|
||||
<div class="viewer__stage">
|
||||
@if (imageUrl(); as url) {
|
||||
<img [src]="url" [attr.alt]="'Página ' + pageNumber() + ' del PDF'" class="viewer__image" />
|
||||
<div class="region-overlay" appRegionDrawOverlay #overlay="appRegionDrawOverlay" (regionDrawn)="regionDrawn.emit($event)">
|
||||
@for (region of regionsOnCurrentPage(); track region.target_field) {
|
||||
<div
|
||||
class="region-overlay__box"
|
||||
[style.left.%]="region.bbox[0] * 100"
|
||||
[style.top.%]="region.bbox[1] * 100"
|
||||
[style.width.%]="(region.bbox[2] - region.bbox[0]) * 100"
|
||||
[style.height.%]="(region.bbox[3] - region.bbox[1]) * 100"
|
||||
>
|
||||
<span class="region-overlay__label">
|
||||
{{ region.target_field }}
|
||||
<button
|
||||
type="button"
|
||||
class="region-overlay__remove"
|
||||
(pointerdown)="$event.stopPropagation()"
|
||||
(click)="onRemoveClick($event, region)"
|
||||
[attr.aria-label]="'Quitar región ' + region.target_field"
|
||||
>×</button>
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (overlay.liveBox(); as box) {
|
||||
<div
|
||||
class="region-overlay__live"
|
||||
[style.left.px]="box.x"
|
||||
[style.top.px]="box.y"
|
||||
[style.width.px]="box.width"
|
||||
[style.height.px]="box.height"
|
||||
></div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,92 @@
|
||||
:host {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.viewer__toolbar {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.viewer__page-label {
|
||||
color: var(--color-text);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
min-width: 120px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.viewer__error {
|
||||
background: #fdeeee;
|
||||
border: 1px solid #e3a6a6;
|
||||
border-radius: 7px;
|
||||
color: #7a2222;
|
||||
font-size: 13px;
|
||||
margin: var(--space-2) 0 0;
|
||||
padding: var(--space-3) var(--space-4);
|
||||
}
|
||||
|
||||
.viewer__stage {
|
||||
background: var(--color-step);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 8px;
|
||||
margin-top: var(--space-3);
|
||||
overflow: auto;
|
||||
position: relative;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.viewer__image {
|
||||
display: block;
|
||||
margin: 0 auto;
|
||||
max-width: 100%;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.region-overlay {
|
||||
cursor: crosshair;
|
||||
inset: 0;
|
||||
position: absolute;
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
.region-overlay__box {
|
||||
background: rgb(168 194 67 / 18%);
|
||||
border: 2px solid var(--color-primary);
|
||||
pointer-events: none;
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
.region-overlay__live {
|
||||
background: rgb(168 194 67 / 12%);
|
||||
border: 2px dashed var(--color-primary);
|
||||
pointer-events: none;
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
.region-overlay__label {
|
||||
align-items: center;
|
||||
background: var(--color-primary);
|
||||
color: var(--color-text);
|
||||
display: inline-flex;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
gap: var(--space-1);
|
||||
left: -2px;
|
||||
padding: 1px var(--space-1);
|
||||
pointer-events: auto;
|
||||
position: absolute;
|
||||
top: -20px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.region-overlay__remove {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--color-text);
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
line-height: 1;
|
||||
padding: 0 0 0 var(--space-1);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { PdfSourceApi } from '../../api/pdf-source.api';
|
||||
import { PdfPageViewer } from './pdf-page-viewer';
|
||||
|
||||
class FakePdfSourceApi {
|
||||
readonly calls: number[] = [];
|
||||
|
||||
pageImage(_file: File, pageNumber: number): Observable<Blob> {
|
||||
this.calls.push(pageNumber);
|
||||
return of(new Blob([`page-${pageNumber}`], { type: 'image/png' }));
|
||||
}
|
||||
}
|
||||
|
||||
describe('PdfPageViewer', () => {
|
||||
let fakeApi: FakePdfSourceApi;
|
||||
let createObjectURL: ReturnType<typeof vi.spyOn>;
|
||||
let revokeObjectURL: ReturnType<typeof vi.spyOn>;
|
||||
let urlCounter = 0;
|
||||
|
||||
beforeEach(async () => {
|
||||
fakeApi = new FakePdfSourceApi();
|
||||
urlCounter = 0;
|
||||
createObjectURL = vi.spyOn(URL, 'createObjectURL').mockImplementation(() => `blob:mock-${++urlCounter}`);
|
||||
revokeObjectURL = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [PdfPageViewer],
|
||||
providers: [{ provide: PdfSourceApi, useValue: fakeApi }],
|
||||
}).compileComponents();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
createObjectURL.mockRestore();
|
||||
revokeObjectURL.mockRestore();
|
||||
});
|
||||
|
||||
function createFixture(pageNumber = 1, pageCount = 3) {
|
||||
const fixture = TestBed.createComponent(PdfPageViewer);
|
||||
fixture.componentRef.setInput('file', new File(['%PDF'], 'doc.pdf', { type: 'application/pdf' }));
|
||||
fixture.componentRef.setInput('pageNumber', pageNumber);
|
||||
fixture.componentRef.setInput('pageCount', pageCount);
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
|
||||
it('fetches and displays page 1 on init via an object URL', () => {
|
||||
const fixture = createFixture(1);
|
||||
const component = fixture.componentInstance;
|
||||
|
||||
expect(fakeApi.calls).toEqual([1]);
|
||||
expect(createObjectURL).toHaveBeenCalledTimes(1);
|
||||
expect(component.imageUrl()).toBe('blob:mock-1');
|
||||
});
|
||||
|
||||
it('revokes the previous object URL and creates a new one when navigating to a new page', () => {
|
||||
const fixture = createFixture(1);
|
||||
fixture.componentRef.setInput('pageNumber', 2);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fakeApi.calls).toEqual([1, 2]);
|
||||
expect(createObjectURL).toHaveBeenCalledTimes(2);
|
||||
expect(revokeObjectURL).toHaveBeenCalledWith('blob:mock-1');
|
||||
expect(fixture.componentInstance.imageUrl()).toBe('blob:mock-2');
|
||||
});
|
||||
|
||||
it('does not refetch an already-fetched page, but still swaps to a fresh object URL for it', () => {
|
||||
const fixture = createFixture(1);
|
||||
fixture.componentRef.setInput('pageNumber', 2);
|
||||
fixture.detectChanges();
|
||||
fixture.componentRef.setInput('pageNumber', 1);
|
||||
fixture.detectChanges();
|
||||
|
||||
// Only two distinct pages were ever fetched from the API, even though
|
||||
// page 1 was visited twice.
|
||||
expect(fakeApi.calls).toEqual([1, 2]);
|
||||
// But a fresh object URL is still minted from the cached Blob each time
|
||||
// the page is (re)displayed, and the previously-shown one is revoked.
|
||||
expect(createObjectURL).toHaveBeenCalledTimes(3);
|
||||
expect(revokeObjectURL).toHaveBeenCalledWith('blob:mock-2');
|
||||
expect(fixture.componentInstance.imageUrl()).toBe('blob:mock-3');
|
||||
});
|
||||
|
||||
it('revokes the current object URL on destroy', () => {
|
||||
const fixture = createFixture(1);
|
||||
fixture.destroy();
|
||||
expect(revokeObjectURL).toHaveBeenCalledWith('blob:mock-1');
|
||||
});
|
||||
|
||||
it('emits pageNumberChange from the pager buttons, clamped to [1, pageCount]', () => {
|
||||
const fixture = createFixture(2, 3);
|
||||
const component = fixture.componentInstance;
|
||||
const emitted: number[] = [];
|
||||
component.pageNumberChange.subscribe((n) => emitted.push(n));
|
||||
|
||||
component.next();
|
||||
component.previous();
|
||||
fixture.componentRef.setInput('pageNumber', 1);
|
||||
fixture.detectChanges();
|
||||
component.previous(); // no-op, already at page 1
|
||||
|
||||
expect(emitted).toEqual([3, 1]);
|
||||
});
|
||||
|
||||
it('filters regions to only those whose page_numbers include the current page', () => {
|
||||
const fixture = createFixture(1);
|
||||
fixture.componentRef.setInput('regions', [
|
||||
{ target_field: 'a', page_numbers: [1], bbox: [0, 0, 0.5, 0.5] },
|
||||
{ target_field: 'b', page_numbers: [2], bbox: [0, 0, 0.5, 0.5] },
|
||||
{ target_field: 'c', page_numbers: [1, 2], bbox: [0, 0, 0.5, 0.5] },
|
||||
]);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.componentInstance.regionsOnCurrentPage().map((r) => r.target_field)).toEqual(['a', 'c']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import { Component, OnDestroy, effect, inject, input, output, signal } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { RegionSpec } from '../../api/api.types';
|
||||
import { PdfSourceApi } from '../../api/pdf-source.api';
|
||||
import { DrawnRegionBox, RegionDrawOverlay } from './region-draw-overlay.directive';
|
||||
|
||||
/**
|
||||
* Shows one PDF page at a time as an image, with a prev/next pager and a
|
||||
* RegionDrawOverlay on top. The parent listens to `regionDrawn` and decides
|
||||
* what a drawn box means.
|
||||
*
|
||||
* Page images are cached as Blobs rather than object URLs. The displayed
|
||||
* URL is revoked on every navigation and a fresh one is created from the
|
||||
* cached Blob, so no URL is leaked and no page is fetched twice.
|
||||
*/
|
||||
@Component({
|
||||
imports: [MatButtonModule, MatIconModule, MatProgressBarModule, RegionDrawOverlay],
|
||||
selector: 'app-pdf-page-viewer',
|
||||
styleUrl: './pdf-page-viewer.scss',
|
||||
templateUrl: './pdf-page-viewer.html',
|
||||
})
|
||||
export class PdfPageViewer implements OnDestroy {
|
||||
readonly file = input.required<File>();
|
||||
readonly pageNumber = input.required<number>();
|
||||
readonly pageCount = input.required<number>();
|
||||
/** Drawn regions on all pages; only the current page's are rendered. */
|
||||
readonly regions = input<RegionSpec[]>([]);
|
||||
|
||||
readonly pageNumberChange = output<number>();
|
||||
readonly regionDrawn = output<DrawnRegionBox>();
|
||||
readonly regionRemove = output<RegionSpec>();
|
||||
|
||||
private readonly pdfApi = inject(PdfSourceApi);
|
||||
|
||||
readonly imageUrl = signal<string | null>(null);
|
||||
readonly loading = signal(false);
|
||||
readonly error = signal<string | null>(null);
|
||||
|
||||
private readonly blobCache = new Map<number, Blob>();
|
||||
private currentObjectUrl: string | null = null;
|
||||
private currentFile: File | null = null;
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const file = this.file();
|
||||
const pageNumber = this.pageNumber();
|
||||
if (file !== this.currentFile) {
|
||||
this.blobCache.clear();
|
||||
this.currentFile = file;
|
||||
}
|
||||
this.loadPage(file, pageNumber);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
if (this.currentObjectUrl) URL.revokeObjectURL(this.currentObjectUrl);
|
||||
}
|
||||
|
||||
previous(): void {
|
||||
if (this.pageNumber() > 1) this.pageNumberChange.emit(this.pageNumber() - 1);
|
||||
}
|
||||
|
||||
next(): void {
|
||||
if (this.pageNumber() < this.pageCount()) this.pageNumberChange.emit(this.pageNumber() + 1);
|
||||
}
|
||||
|
||||
regionsOnCurrentPage(): RegionSpec[] {
|
||||
return this.regions().filter((region) => region.page_numbers.includes(this.pageNumber()));
|
||||
}
|
||||
|
||||
onRemoveClick(event: Event, region: RegionSpec): void {
|
||||
event.stopPropagation();
|
||||
this.regionRemove.emit(region);
|
||||
}
|
||||
|
||||
private loadPage(file: File, pageNumber: number): void {
|
||||
const cached = this.blobCache.get(pageNumber);
|
||||
if (cached) {
|
||||
this.showBlob(cached);
|
||||
return;
|
||||
}
|
||||
this.loading.set(true);
|
||||
this.error.set(null);
|
||||
this.pdfApi.pageImage(file, pageNumber).subscribe({
|
||||
next: (blob) => {
|
||||
this.blobCache.set(pageNumber, blob);
|
||||
this.loading.set(false);
|
||||
this.showBlob(blob);
|
||||
},
|
||||
error: () => {
|
||||
this.loading.set(false);
|
||||
this.error.set('No se pudo cargar la página.');
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private showBlob(blob: Blob): void {
|
||||
const url = URL.createObjectURL(blob);
|
||||
if (this.currentObjectUrl) URL.revokeObjectURL(this.currentObjectUrl);
|
||||
this.currentObjectUrl = url;
|
||||
this.imageUrl.set(url);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { DrawnRegionBox, RegionDrawOverlay } from './region-draw-overlay.directive';
|
||||
|
||||
@Component({
|
||||
imports: [RegionDrawOverlay],
|
||||
template: `<div class="overlay" appRegionDrawOverlay (regionDrawn)="onRegionDrawn($event)"></div>`,
|
||||
})
|
||||
class TestHostComponent {
|
||||
readonly drawn: DrawnRegionBox[] = [];
|
||||
onRegionDrawn(box: DrawnRegionBox): void {
|
||||
this.drawn.push(box);
|
||||
}
|
||||
}
|
||||
|
||||
function pointerEvent(clientX: number, clientY: number, pointerId = 1, button = 0): PointerEvent {
|
||||
return { clientX, clientY, pointerId, button } as unknown as PointerEvent;
|
||||
}
|
||||
|
||||
describe('RegionDrawOverlay', () => {
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({ imports: [TestHostComponent] }).compileComponents();
|
||||
});
|
||||
|
||||
function createFixture(rect: { left?: number; top?: number; width: number; height: number }) {
|
||||
const fixture = TestBed.createComponent(TestHostComponent);
|
||||
fixture.detectChanges();
|
||||
const overlayEl = fixture.nativeElement.querySelector('.overlay') as HTMLElement;
|
||||
vi.spyOn(overlayEl, 'getBoundingClientRect').mockReturnValue({
|
||||
left: 0,
|
||||
top: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
x: 0,
|
||||
y: 0,
|
||||
toJSON: () => ({}),
|
||||
...rect,
|
||||
} as DOMRect);
|
||||
const directive = fixture.debugElement.query(By.directive(RegionDrawOverlay)).injector.get(RegionDrawOverlay);
|
||||
return { fixture, overlayEl, directive };
|
||||
}
|
||||
|
||||
it('emits a normalized bbox (relative to the overlay, not the viewport) on a drag above the minimum threshold', () => {
|
||||
const { fixture, directive } = createFixture({ left: 100, top: 50, width: 400, height: 300 });
|
||||
const host = fixture.componentInstance;
|
||||
|
||||
directive.onPointerDown(pointerEvent(140, 80)); // 40,30 relative to the overlay's origin
|
||||
directive.onPointerMove(pointerEvent(340, 230)); // 240,180 relative
|
||||
directive.onPointerUp(pointerEvent(340, 230));
|
||||
|
||||
expect(host.drawn).toHaveLength(1);
|
||||
const box = host.drawn[0];
|
||||
expect(box.x0).toBeCloseTo(40 / 400);
|
||||
expect(box.y0).toBeCloseTo(30 / 300);
|
||||
expect(box.x1).toBeCloseTo(240 / 400);
|
||||
expect(box.y1).toBeCloseTo(180 / 300);
|
||||
});
|
||||
|
||||
it('normalizes corners regardless of drag direction (bottom-right to top-left still yields x0<x1, y0<y1)', () => {
|
||||
const { fixture, directive } = createFixture({ width: 400, height: 300 });
|
||||
const host = fixture.componentInstance;
|
||||
|
||||
directive.onPointerDown(pointerEvent(240, 180));
|
||||
directive.onPointerMove(pointerEvent(40, 30));
|
||||
directive.onPointerUp(pointerEvent(40, 30));
|
||||
|
||||
expect(host.drawn).toHaveLength(1);
|
||||
const box = host.drawn[0];
|
||||
expect(box.x0).toBeCloseTo(40 / 400);
|
||||
expect(box.y0).toBeCloseTo(30 / 300);
|
||||
expect(box.x1).toBeCloseTo(240 / 400);
|
||||
expect(box.y1).toBeCloseTo(180 / 300);
|
||||
expect(box.x0).toBeLessThan(box.x1);
|
||||
expect(box.y0).toBeLessThan(box.y1);
|
||||
});
|
||||
|
||||
it('produces the same normalized bbox for the same relative drag, independent of the overlay rect size/position', () => {
|
||||
const drag = (rect: { left?: number; top?: number; width: number; height: number }) => {
|
||||
const { fixture, directive } = createFixture(rect);
|
||||
const host = fixture.componentInstance;
|
||||
const left = rect.left ?? 0;
|
||||
const top = rect.top ?? 0;
|
||||
const { width, height } = rect;
|
||||
// Same *relative* drag in both cases: from 10%,10% to 60%,70% of the overlay.
|
||||
directive.onPointerDown(pointerEvent(left + width * 0.1, top + height * 0.1));
|
||||
directive.onPointerMove(pointerEvent(left + width * 0.6, top + height * 0.7));
|
||||
directive.onPointerUp(pointerEvent(left + width * 0.6, top + height * 0.7));
|
||||
return host.drawn[0];
|
||||
};
|
||||
|
||||
const small = drag({ width: 200, height: 100 });
|
||||
const large = drag({ left: 500, top: 300, width: 1200, height: 900 });
|
||||
|
||||
expect(small).toBeDefined();
|
||||
expect(large).toBeDefined();
|
||||
expect(small.x0).toBeCloseTo(large.x0, 6);
|
||||
expect(small.y0).toBeCloseTo(large.y0, 6);
|
||||
expect(small.x1).toBeCloseTo(large.x1, 6);
|
||||
expect(small.y1).toBeCloseTo(large.y1, 6);
|
||||
});
|
||||
|
||||
it('ignores drags below the minimum pixel threshold, treating them as accidental clicks', () => {
|
||||
const { fixture, directive } = createFixture({ width: 400, height: 300 });
|
||||
const host = fixture.componentInstance;
|
||||
|
||||
directive.onPointerDown(pointerEvent(10, 10));
|
||||
directive.onPointerMove(pointerEvent(12, 11));
|
||||
directive.onPointerUp(pointerEvent(12, 11));
|
||||
|
||||
expect(host.drawn).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('exposes the in-progress drag via the exported liveBox signal, and clears it on pointerup', () => {
|
||||
const { directive } = createFixture({ width: 400, height: 300 });
|
||||
|
||||
expect(directive.liveBox()).toBeNull();
|
||||
directive.onPointerDown(pointerEvent(10, 10));
|
||||
directive.onPointerMove(pointerEvent(60, 90));
|
||||
expect(directive.liveBox()).toEqual({ x: 10, y: 10, width: 50, height: 80 });
|
||||
directive.onPointerUp(pointerEvent(60, 90));
|
||||
expect(directive.liveBox()).toBeNull();
|
||||
});
|
||||
|
||||
it('ignores non-primary pointer buttons on pointerdown', () => {
|
||||
const { fixture, directive } = createFixture({ width: 400, height: 300 });
|
||||
const host = fixture.componentInstance;
|
||||
|
||||
directive.onPointerDown(pointerEvent(10, 10, 1, 2)); // right-click
|
||||
directive.onPointerMove(pointerEvent(200, 200));
|
||||
directive.onPointerUp(pointerEvent(200, 200));
|
||||
|
||||
expect(host.drawn).toHaveLength(0);
|
||||
expect(directive.liveBox()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
import { Directive, ElementRef, HostListener, inject, output, signal } from '@angular/core';
|
||||
|
||||
/** A normalized (0..1) region box, corners already sorted so x0<x1 and y0<y1. */
|
||||
export interface DrawnRegionBox {
|
||||
x0: number;
|
||||
y0: number;
|
||||
x1: number;
|
||||
y1: number;
|
||||
}
|
||||
|
||||
/** A live-drag box in CSS pixels, relative to the overlay element's own origin. */
|
||||
export interface LiveDrawBox {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** Drags below this size (in either dimension) are treated as accidental clicks. */
|
||||
const MIN_DRAG_PX = 5;
|
||||
|
||||
/**
|
||||
* Draws boxes with plain pointer events on an overlay sized to the rendered
|
||||
* page, and emits each one normalized via `regionDrawn`. CDK drag-drop is
|
||||
* not used because it moves existing elements; here a box is defined by a
|
||||
* single drag.
|
||||
*
|
||||
* Pointer capture keeps move/up events on this element when the pointer
|
||||
* leaves it mid-drag. The in-progress box is exposed as `liveBox`
|
||||
* (`#overlay="appRegionDrawOverlay"`) for the host template to render.
|
||||
*/
|
||||
@Directive({
|
||||
selector: '[appRegionDrawOverlay]',
|
||||
exportAs: 'appRegionDrawOverlay',
|
||||
})
|
||||
export class RegionDrawOverlay {
|
||||
readonly regionDrawn = output<DrawnRegionBox>();
|
||||
|
||||
readonly liveBox = signal<LiveDrawBox | null>(null);
|
||||
|
||||
private readonly element = inject(ElementRef<HTMLElement>);
|
||||
private start: { x: number; y: number } | null = null;
|
||||
|
||||
@HostListener('pointerdown', ['$event'])
|
||||
onPointerDown(event: PointerEvent): void {
|
||||
if (event.button > 0) return;
|
||||
const rect = this.element.nativeElement.getBoundingClientRect();
|
||||
this.start = { x: event.clientX - rect.left, y: event.clientY - rect.top };
|
||||
this.liveBox.set({ x: this.start.x, y: this.start.y, width: 0, height: 0 });
|
||||
try {
|
||||
this.element.nativeElement.setPointerCapture?.(event.pointerId);
|
||||
} catch {
|
||||
// Pointer capture is unsupported in some test environments; drawing
|
||||
// still works through events dispatched on the host.
|
||||
}
|
||||
}
|
||||
|
||||
@HostListener('pointermove', ['$event'])
|
||||
onPointerMove(event: PointerEvent): void {
|
||||
if (!this.start) return;
|
||||
const rect = this.element.nativeElement.getBoundingClientRect();
|
||||
this.liveBox.set(this.boxFrom(this.start, { x: event.clientX - rect.left, y: event.clientY - rect.top }));
|
||||
}
|
||||
|
||||
@HostListener('pointerup', ['$event'])
|
||||
onPointerUp(event: PointerEvent): void {
|
||||
if (!this.start) return;
|
||||
const rect = this.element.nativeElement.getBoundingClientRect();
|
||||
const box = this.boxFrom(this.start, { x: event.clientX - rect.left, y: event.clientY - rect.top });
|
||||
this.start = null;
|
||||
this.liveBox.set(null);
|
||||
try {
|
||||
if (this.element.nativeElement.hasPointerCapture?.(event.pointerId)) {
|
||||
this.element.nativeElement.releasePointerCapture(event.pointerId);
|
||||
}
|
||||
} catch {
|
||||
// Capture may be unsupported here, see onPointerDown.
|
||||
}
|
||||
|
||||
if (box.width < MIN_DRAG_PX || box.height < MIN_DRAG_PX) return;
|
||||
if (rect.width <= 0 || rect.height <= 0) return;
|
||||
this.regionDrawn.emit({
|
||||
x0: box.x / rect.width,
|
||||
y0: box.y / rect.height,
|
||||
x1: (box.x + box.width) / rect.width,
|
||||
y1: (box.y + box.height) / rect.height,
|
||||
});
|
||||
}
|
||||
|
||||
private boxFrom(start: { x: number; y: number }, current: { x: number; y: number }): LiveDrawBox {
|
||||
const x0 = Math.min(start.x, current.x);
|
||||
const y0 = Math.min(start.y, current.y);
|
||||
const x1 = Math.max(start.x, current.x);
|
||||
const y1 = Math.max(start.y, current.y);
|
||||
return { x: x0, y: y0, width: x1 - x0, height: y1 - y0 };
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user