@molecule/app-feature-image-canvas-angular 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Framework-free helpers of the Angular Canvas2D image-editing surface — the same
3
+ * values `@molecule/app-feature-image-canvas-react` exports.
4
+ *
5
+ * @module
6
+ */
7
+ /**
8
+ * Clamp a numeric value into the closed interval `[min, max]`. Returns
9
+ * `min` for non-finite inputs.
10
+ *
11
+ * @param value - The value to clamp.
12
+ * @param min - Inclusive minimum.
13
+ * @param max - Inclusive maximum.
14
+ * @returns The clamped value.
15
+ */
16
+ export function clamp(value, min, max) {
17
+ if (!Number.isFinite(value))
18
+ return min;
19
+ if (value < min)
20
+ return min;
21
+ if (value > max)
22
+ return max;
23
+ return value;
24
+ }
25
+ /**
26
+ * Compose a CSS filter string from a set of `ImageCanvasFilters` values.
27
+ * Out-of-range values are clamped; omitted / non-finite fields are
28
+ * ignored. Returns `'none'` when no filters are active so callers can
29
+ * assign the result directly to `CanvasRenderingContext2D.filter`.
30
+ *
31
+ * @param filters - The filter parameters. May be `undefined`.
32
+ * @returns A CSS filter string, or `'none'` when nothing applies.
33
+ */
34
+ export function composeFilterString(filters) {
35
+ if (!filters)
36
+ return 'none';
37
+ const parts = [];
38
+ if (filters.brightness !== undefined && Number.isFinite(filters.brightness)) {
39
+ const v = Math.max(0, filters.brightness);
40
+ if (v !== 1)
41
+ parts.push(`brightness(${v})`);
42
+ }
43
+ if (filters.contrast !== undefined && Number.isFinite(filters.contrast)) {
44
+ const v = Math.max(0, filters.contrast);
45
+ if (v !== 1)
46
+ parts.push(`contrast(${v})`);
47
+ }
48
+ if (filters.saturation !== undefined && Number.isFinite(filters.saturation)) {
49
+ const v = Math.max(0, filters.saturation);
50
+ if (v !== 1)
51
+ parts.push(`saturate(${v})`);
52
+ }
53
+ if (filters.hue !== undefined && Number.isFinite(filters.hue)) {
54
+ const v = ((filters.hue % 360) + 360) % 360;
55
+ if (v !== 0)
56
+ parts.push(`hue-rotate(${v}deg)`);
57
+ }
58
+ if (filters.sepia !== undefined && Number.isFinite(filters.sepia)) {
59
+ const v = clamp(filters.sepia, 0, 1);
60
+ if (v > 0)
61
+ parts.push(`sepia(${v})`);
62
+ }
63
+ if (filters.grayscale !== undefined && Number.isFinite(filters.grayscale)) {
64
+ const v = clamp(filters.grayscale, 0, 1);
65
+ if (v > 0)
66
+ parts.push(`grayscale(${v})`);
67
+ }
68
+ if (filters.blur !== undefined && Number.isFinite(filters.blur)) {
69
+ const v = Math.max(0, filters.blur);
70
+ if (v > 0)
71
+ parts.push(`blur(${v}px)`);
72
+ }
73
+ if (filters.sharpen !== undefined && Number.isFinite(filters.sharpen)) {
74
+ const v = clamp(filters.sharpen, 0, 1);
75
+ // Approximate sharpen as a small contrast bump. 1.0 = +50% contrast.
76
+ if (v > 0)
77
+ parts.push(`contrast(${1 + 0.5 * v})`);
78
+ }
79
+ return parts.length === 0 ? 'none' : parts.join(' ');
80
+ }
81
+ /**
82
+ * Convert a screen-space (canvas-relative) point into image-space
83
+ * coordinates given the current zoom + pan and the source image
84
+ * dimensions. Useful for tools that need to know which image pixel a
85
+ * pointer event hit (cropping, picking, masking).
86
+ *
87
+ * @param point - The canvas-space point in CSS pixels (origin top-left
88
+ * of the canvas element).
89
+ * @param canvasSize - The canvas size in CSS pixels.
90
+ * @param imageSize - The source image's natural size in pixels.
91
+ * @param zoom - The current zoom factor. Non-positive values fall back
92
+ * to `1`.
93
+ * @param pan - The current pan offset in CSS pixels.
94
+ * @returns The corresponding point in image-space coordinates.
95
+ */
96
+ export function screenToCanvas(point, canvasSize, imageSize, zoom, pan) {
97
+ const safeZoom = Number.isFinite(zoom) && zoom > 0 ? zoom : 1;
98
+ const cx = canvasSize.width / 2;
99
+ const cy = canvasSize.height / 2;
100
+ // The image is drawn centred at (cx + pan.x, cy + pan.y) and scaled by
101
+ // `safeZoom` from its natural size. Inverting that mapping yields the
102
+ // image-space pixel for an arbitrary canvas-space point.
103
+ const dx = point.x - cx - pan.x;
104
+ const dy = point.y - cy - pan.y;
105
+ return {
106
+ x: dx / safeZoom + imageSize.width / 2,
107
+ y: dy / safeZoom + imageSize.height / 2,
108
+ };
109
+ }
110
+ /**
111
+ * Clamp a pan offset so the (zoomed) image cannot be dragged entirely
112
+ * off-canvas. The clamp keeps at least half of the image visible in
113
+ * each axis. Non-finite inputs are treated as `0`.
114
+ *
115
+ * @param pan - The desired pan offset, in CSS pixels.
116
+ * @param canvasSize - The canvas size in CSS pixels.
117
+ * @param imageSize - The source image's natural size in pixels.
118
+ * @param zoom - The current zoom factor. Non-positive values fall back
119
+ * to `1`.
120
+ * @returns The clamped pan offset.
121
+ */
122
+ export function clampPan(pan, canvasSize, imageSize, zoom) {
123
+ const safeZoom = Number.isFinite(zoom) && zoom > 0 ? zoom : 1;
124
+ const halfImgW = (imageSize.width * safeZoom) / 2;
125
+ const halfImgH = (imageSize.height * safeZoom) / 2;
126
+ const halfCanvasW = canvasSize.width / 2;
127
+ const halfCanvasH = canvasSize.height / 2;
128
+ // Allow the image centre to move up to (halfCanvas + halfImg/2) — i.e.
129
+ // half the image always stays visible.
130
+ const maxX = halfCanvasW + halfImgW / 2;
131
+ const maxY = halfCanvasH + halfImgH / 2;
132
+ const px = Number.isFinite(pan.x) ? pan.x : 0;
133
+ const py = Number.isFinite(pan.y) ? pan.y : 0;
134
+ return {
135
+ x: clamp(px, -maxX, maxX),
136
+ y: clamp(py, -maxY, maxY),
137
+ };
138
+ }
139
+ //# sourceMappingURL=helpers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helpers.js","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH;;;;;;;;GAQG;AACH,MAAM,UAAU,KAAK,CAAC,KAAa,EAAE,GAAW,EAAE,GAAW;IAC3D,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;QAA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
6
+ import { type AfterViewInit, type OnChanges, type OnDestroy, type OnInit, type SimpleChanges } from '@angular/core';
7
+ import type { ImageCanvasFilters, ImageCanvasProps, PanOffset } from './types.js';
8
+ import * as i0 from "@angular/core";
9
+ /**
10
+ * Canvas2D image-editing surface: a source image drawn onto a canvas with a
11
+ * filter chain, pointer-drag panning, wheel zooming, and a `toDataURL()`
12
+ * export handle.
13
+ *
14
+ * The host IS React's root element (`div[mol-image-canvas]`), so the host
15
+ * carries the region role, the aria label, the ClassMap classes and the frame
16
+ * size exactly as React renders them. All user-visible text is translated
17
+ * through the binding's `useTranslation()`.
18
+ */
19
+ export declare class ImageCanvas implements OnInit, OnChanges, AfterViewInit, OnDestroy {
20
+ /** Image source: a URL/data-URL string, or an already-loaded `HTMLImageElement`. */
21
+ src?: string | HTMLImageElement;
22
+ /** Filter chain applied to the rendered image. */
23
+ filters?: ImageCanvasFilters;
24
+ /** Zoom factor; values <= 0 fall back to `1`. */
25
+ zoom?: number;
26
+ /** Pan offset in CSS pixels relative to the centre of the canvas. */
27
+ pan?: PanOffset;
28
+ /** Fired when the user pans or zooms the canvas. */
29
+ onChange?: (next: {
30
+ zoom: number;
31
+ pan: PanOffset;
32
+ }) => void;
33
+ /** Receives the `toDataURL()` handle while the canvas is mounted. */
34
+ exportRef?: ImageCanvasProps['exportRef'];
35
+ /** Pixel width of the canvas (defaults to `512`). */
36
+ width?: number;
37
+ /** Pixel height of the canvas (defaults to `512`). */
38
+ height?: number;
39
+ /** Extra classes merged onto the root element. */
40
+ className?: string;
41
+ /** The canvas surface, referenced for painting and the export handle. */
42
+ private surface?;
43
+ /** Reactive translation, read in the injection context. */
44
+ private readonly i18n;
45
+ /** The translation function for templates and host bindings. */
46
+ private t;
47
+ /** The bonded ClassMap (styling tokens resolve at render time). */
48
+ private readonly classMap;
49
+ private readonly image;
50
+ private readonly loadError;
51
+ private loadToken;
52
+ private viewReady;
53
+ private dragState;
54
+ /** The region's translated aria label. */
55
+ protected readonly ariaLabel: import("@angular/core").Signal<string>;
56
+ /** The canvas's translated aria label. */
57
+ protected readonly dragLabel: import("@angular/core").Signal<string>;
58
+ /** The translated loading message. */
59
+ protected readonly loadingLabel: import("@angular/core").Signal<string>;
60
+ /** The translated error message. */
61
+ protected readonly errorLabel: import("@angular/core").Signal<string>;
62
+ /** `data-loading`: `'true'` until an image arrives (React's expression, flattened). */
63
+ protected readonly loadingAttr: import("@angular/core").Signal<"false" | "true">;
64
+ /** `data-error`: `'true'` after a failed load. */
65
+ protected readonly errorAttr: import("@angular/core").Signal<"false" | "true">;
66
+ /**
67
+ * Seeds the internal image from an element source and starts a URL load —
68
+ * React's `useState` initial value plus its mount effect.
69
+ */
70
+ ngOnInit(): void;
71
+ /**
72
+ * Loads a changed `src` and re-paints for every other input change.
73
+ *
74
+ * @param changes - The changed inputs (React's effect dependencies).
75
+ */
76
+ ngOnChanges(changes: SimpleChanges): void;
77
+ /** Paints the first frame and hands out the export handle (React's mount effects). */
78
+ ngAfterViewInit(): void;
79
+ /** Clears the export handle, as React's `useImperativeHandle` cleanup does. */
80
+ ngOnDestroy(): void;
81
+ /** The frame's class list (`cm.cn(className)` only, as React composes it). */
82
+ classes(): string;
83
+ /** The canvas bitmap width (React's default parameter). */
84
+ widthValue(): number;
85
+ /** The canvas bitmap height (React's default parameter). */
86
+ heightValue(): number;
87
+ /** The cursor style: `grab` while `onChange` is provided. */
88
+ cursor(): string;
89
+ /** The loading/error paragraph's class list. */
90
+ noteClasses(): string;
91
+ /**
92
+ * Starts a drag, capturing the pointer for its duration.
93
+ *
94
+ * @param event - The pointerdown event.
95
+ */
96
+ handlePointerDown(event: PointerEvent): void;
97
+ /**
98
+ * Reports the proposed pan while a drag is in progress.
99
+ *
100
+ * @param event - The pointermove event.
101
+ */
102
+ handlePointerMove(event: PointerEvent): void;
103
+ /**
104
+ * Ends a drag, releasing the capture it took.
105
+ *
106
+ * @param event - The pointerup or pointercancel event.
107
+ */
108
+ endDrag(event: PointerEvent): void;
109
+ /**
110
+ * Reports the zoomed factor for a wheel scroll (negative `deltaY` zooms in).
111
+ *
112
+ * @param event - The wheel event.
113
+ */
114
+ handleWheel(event: WheelEvent): void;
115
+ /** The sanitised zoom factor (React's `safeZoom`). */
116
+ private safeZoom;
117
+ /** The sanitised pan offset (React's `safePan`). */
118
+ private safePan;
119
+ /**
120
+ * Loads a URL source into an internal image (React's loading effect).
121
+ *
122
+ * @param src - The URL or data URL.
123
+ */
124
+ private load;
125
+ /** Re-paints the canvas from the image, viewport and filter chain. */
126
+ private paint;
127
+ static ɵfac: i0.ɵɵFactoryDeclaration<ImageCanvas, never>;
128
+ static ɵcmp: i0.ɵɵComponentDeclaration<ImageCanvas, "div[mol-image-canvas]", never, { "src": { "alias": "src"; "required": false; }; "filters": { "alias": "filters"; "required": false; }; "zoom": { "alias": "zoom"; "required": false; }; "pan": { "alias": "pan"; "required": false; }; "onChange": { "alias": "onChange"; "required": false; }; "exportRef": { "alias": "exportRef"; "required": false; }; "width": { "alias": "width"; "required": false; }; "height": { "alias": "height"; "required": false; }; "className": { "alias": "className"; "required": false; }; }, {}, never, never, true, never>;
129
+ }
130
+ //# sourceMappingURL=image-canvas.component.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image-canvas.component.d.ts","sourceRoot":"","sources":["../src/image-canvas.component.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACL,KAAK,aAAa,EAIlB,KAAK,SAAS,EACd,KAAK,SAAS,EACd,KAAK,MAAM,EAEX,KAAK,aAAa,EAEnB,MAAM,eAAe,CAAA;AAQtB,OAAO,KAAK,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;;AAEjF;;;;;;;;;GASG;AACH,qBAoDa,WAAY,YAAW,MAAM,EAAE,SAAS,EAAE,aAAa,EAAE,SAAS;IAC7E,oFAAoF;IACpF,GAAG,CAAC,EAAE,MAAM,GAAG,gBAAgB,CAAA;IAC/B,kDAAkD;IAClD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,CAAC,SAAS,mDAAwD;IAEpF;;;OAGG;IACH,QAAQ,IAAI,IAAI;IAUhB;;;;OAIG;IACH,WAAW,CAAC,OAAO,EAAE,aAAa,GAAG,IAAI;IAazC,sFAAsF;IACtF,eAAe,IAAI,IAAI;IAcvB,+EAA+E;IAC/E,WAAW,IAAI,IAAI;IAInB,8EAA8E;IAC9E,OAAO,IAAI,MAAM;IAIjB,2DAA2D;IAC3D,UAAU,IAAI,MAAM;IAIpB,4DAA4D;IAC5D,WAAW,IAAI,MAAM;IAIrB,6DAA6D;IAC7D,MAAM,IAAI,MAAM;IAIhB,gDAAgD;IAChD,WAAW,IAAI,MAAM;IAIrB;;;;OAIG;IACH,iBAAiB,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI;IAY5C;;;;OAIG;IACH,iBAAiB,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI;IAiB5C;;;;OAIG;IACH,OAAO,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI;IAUlC;;;;OAIG;IACH,WAAW,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI;IAMpC,sDAAsD;IACtD,OAAO,CAAC,QAAQ;IAKhB,oDAAoD;IACpD,OAAO,CAAC,OAAO;IAOf;;;;OAIG;IACH,OAAO,CAAC,IAAI;IAmBZ,sEAAsE;IACtE,OAAO,CAAC,KAAK;yCA1PF,WAAW;2CAAX,WAAW;CAsRvB"}
@@ -0,0 +1,375 @@
1
+ /**
2
+ * ImageCanvas component (React parity).
3
+ *
4
+ * @module
5
+ */
6
+ import { Component, computed, signal, ViewChild, } from '@angular/core';
7
+ import { useTranslation } from '@molecule/app-angular';
8
+ import { getClassMap } from '@molecule/app-ui';
9
+ import { clamp, clampPan, composeFilterString } from './helpers.js';
10
+ import { isImageElement } from './image-source.js';
11
+ import * as i0 from "@angular/core";
12
+ const _c0 = ["surface"];
13
+ function ImageCanvas_Conditional_2_Template(rf, ctx) { if (rf & 1) {
14
+ i0.ɵɵdomElementStart(0, "p", 4);
15
+ i0.ɵɵtext(1);
16
+ i0.ɵɵdomElementEnd();
17
+ } if (rf & 2) {
18
+ const ctx_r0 = i0.ɵɵnextContext();
19
+ i0.ɵɵclassMap(ctx_r0.noteClasses());
20
+ i0.ɵɵadvance();
21
+ i0.ɵɵtextInterpolate(ctx_r0.loadingLabel());
22
+ } }
23
+ function ImageCanvas_Conditional_3_Template(rf, ctx) { if (rf & 1) {
24
+ i0.ɵɵdomElementStart(0, "p", 5);
25
+ i0.ɵɵtext(1);
26
+ i0.ɵɵdomElementEnd();
27
+ } if (rf & 2) {
28
+ const ctx_r0 = i0.ɵɵnextContext();
29
+ i0.ɵɵclassMap(ctx_r0.noteClasses());
30
+ i0.ɵɵadvance();
31
+ i0.ɵɵtextInterpolate1(" ", ctx_r0.errorLabel(), " ");
32
+ } }
33
+ /**
34
+ * Canvas2D image-editing surface: a source image drawn onto a canvas with a
35
+ * filter chain, pointer-drag panning, wheel zooming, and a `toDataURL()`
36
+ * export handle.
37
+ *
38
+ * The host IS React's root element (`div[mol-image-canvas]`), so the host
39
+ * carries the region role, the aria label, the ClassMap classes and the frame
40
+ * size exactly as React renders them. All user-visible text is translated
41
+ * through the binding's `useTranslation()`.
42
+ */
43
+ export class ImageCanvas {
44
+ /** Image source: a URL/data-URL string, or an already-loaded `HTMLImageElement`. */
45
+ src;
46
+ /** Filter chain applied to the rendered image. */
47
+ filters;
48
+ /** Zoom factor; values <= 0 fall back to `1`. */
49
+ zoom;
50
+ /** Pan offset in CSS pixels relative to the centre of the canvas. */
51
+ pan;
52
+ /** Fired when the user pans or zooms the canvas. */
53
+ onChange;
54
+ /** Receives the `toDataURL()` handle while the canvas is mounted. */
55
+ exportRef;
56
+ /** Pixel width of the canvas (defaults to `512`). */
57
+ width;
58
+ /** Pixel height of the canvas (defaults to `512`). */
59
+ height;
60
+ /** Extra classes merged onto the root element. */
61
+ className;
62
+ /** The canvas surface, referenced for painting and the export handle. */
63
+ surface;
64
+ /** Reactive translation, read in the injection context. */
65
+ i18n = useTranslation();
66
+ /** The translation function for templates and host bindings. */
67
+ t = this.i18n.t;
68
+ /** The bonded ClassMap (styling tokens resolve at render time). */
69
+ classMap = getClassMap();
70
+ image = signal(null, /* @ts-ignore */
71
+ ...(ngDevMode ? [{ debugName: "image" }] : /* istanbul ignore next */ []));
72
+ loadError = signal(null, /* @ts-ignore */
73
+ ...(ngDevMode ? [{ debugName: "loadError" }] : /* istanbul ignore next */ []));
74
+ loadToken = 0;
75
+ viewReady = false;
76
+ dragState = { pointerId: null, startX: 0, startY: 0, startPan: { x: 0, y: 0 } };
77
+ /** The region's translated aria label. */
78
+ ariaLabel = computed(() => this.t('imageCanvas.aria.region', {}, { defaultValue: 'Image canvas' }), /* @ts-ignore */
79
+ ...(ngDevMode ? [{ debugName: "ariaLabel" }] : /* istanbul ignore next */ []));
80
+ /** The canvas's translated aria label. */
81
+ dragLabel = computed(() => this.t('imageCanvas.aria.canvas', {}, { defaultValue: 'Drag to pan, scroll to zoom' }), /* @ts-ignore */
82
+ ...(ngDevMode ? [{ debugName: "dragLabel" }] : /* istanbul ignore next */ []));
83
+ /** The translated loading message. */
84
+ loadingLabel = computed(() => this.t('imageCanvas.loading', {}, { defaultValue: 'Loading image…' }), /* @ts-ignore */
85
+ ...(ngDevMode ? [{ debugName: "loadingLabel" }] : /* istanbul ignore next */ []));
86
+ /** The translated error message. */
87
+ errorLabel = computed(() => this.t('imageCanvas.error', {}, { defaultValue: 'Image failed to load.' }), /* @ts-ignore */
88
+ ...(ngDevMode ? [{ debugName: "errorLabel" }] : /* istanbul ignore next */ []));
89
+ /** `data-loading`: `'true'` until an image arrives (React's expression, flattened). */
90
+ loadingAttr = computed(() => this.image() ? 'false' : this.loadError() ? 'false' : 'true', /* @ts-ignore */
91
+ ...(ngDevMode ? [{ debugName: "loadingAttr" }] : /* istanbul ignore next */ []));
92
+ /** `data-error`: `'true'` after a failed load. */
93
+ errorAttr = computed(() => (this.loadError() ? 'true' : 'false'), /* @ts-ignore */
94
+ ...(ngDevMode ? [{ debugName: "errorAttr" }] : /* istanbul ignore next */ []));
95
+ /**
96
+ * Seeds the internal image from an element source and starts a URL load —
97
+ * React's `useState` initial value plus its mount effect.
98
+ */
99
+ ngOnInit() {
100
+ const src = this.src;
101
+ if (typeof src === 'string') {
102
+ this.load(src);
103
+ }
104
+ else if (src !== undefined && isImageElement(src)) {
105
+ this.image.set(src);
106
+ this.loadError.set(null);
107
+ }
108
+ }
109
+ /**
110
+ * Loads a changed `src` and re-paints for every other input change.
111
+ *
112
+ * @param changes - The changed inputs (React's effect dependencies).
113
+ */
114
+ ngOnChanges(changes) {
115
+ if (!this.viewReady)
116
+ return;
117
+ if (changes['src']) {
118
+ const src = changes['src'].currentValue;
119
+ if (typeof src === 'string')
120
+ this.load(src);
121
+ else if (src !== undefined && isImageElement(src)) {
122
+ this.image.set(src);
123
+ this.loadError.set(null);
124
+ }
125
+ }
126
+ this.paint();
127
+ }
128
+ /** Paints the first frame and hands out the export handle (React's mount effects). */
129
+ ngAfterViewInit() {
130
+ this.viewReady = true;
131
+ this.paint();
132
+ if (this.exportRef) {
133
+ this.exportRef.current = {
134
+ toDataURL: (type, quality) => {
135
+ const canvas = this.surface?.nativeElement;
136
+ if (!canvas)
137
+ return '';
138
+ return canvas.toDataURL(type, quality);
139
+ },
140
+ };
141
+ }
142
+ }
143
+ /** Clears the export handle, as React's `useImperativeHandle` cleanup does. */
144
+ ngOnDestroy() {
145
+ if (this.exportRef)
146
+ this.exportRef.current = null;
147
+ }
148
+ /** The frame's class list (`cm.cn(className)` only, as React composes it). */
149
+ classes() {
150
+ return this.classMap.cn(this.className);
151
+ }
152
+ /** The canvas bitmap width (React's default parameter). */
153
+ widthValue() {
154
+ return this.width ?? 512;
155
+ }
156
+ /** The canvas bitmap height (React's default parameter). */
157
+ heightValue() {
158
+ return this.height ?? 512;
159
+ }
160
+ /** The cursor style: `grab` while `onChange` is provided. */
161
+ cursor() {
162
+ return this.onChange ? 'grab' : 'default';
163
+ }
164
+ /** The loading/error paragraph's class list. */
165
+ noteClasses() {
166
+ return this.classMap.cn(this.classMap.textSize('xs'), this.classMap.sp('p', 2));
167
+ }
168
+ /**
169
+ * Starts a drag, capturing the pointer for its duration.
170
+ *
171
+ * @param event - The pointerdown event.
172
+ */
173
+ handlePointerDown(event) {
174
+ const canvas = this.surface?.nativeElement;
175
+ if (!canvas)
176
+ return;
177
+ canvas.setPointerCapture(event.pointerId);
178
+ this.dragState = {
179
+ pointerId: event.pointerId,
180
+ startX: event.clientX,
181
+ startY: event.clientY,
182
+ startPan: { ...this.safePan() },
183
+ };
184
+ }
185
+ /**
186
+ * Reports the proposed pan while a drag is in progress.
187
+ *
188
+ * @param event - The pointermove event.
189
+ */
190
+ handlePointerMove(event) {
191
+ const state = this.dragState;
192
+ if (state.pointerId !== event.pointerId)
193
+ return;
194
+ const dx = event.clientX - state.startX;
195
+ const dy = event.clientY - state.startY;
196
+ const image = this.image();
197
+ const next = clampPan({ x: state.startPan.x + dx, y: state.startPan.y + dy }, { width: this.widthValue(), height: this.heightValue() }, image
198
+ ? { width: image.naturalWidth, height: image.naturalHeight }
199
+ : { width: this.widthValue(), height: this.heightValue() }, this.safeZoom());
200
+ this.onChange?.({ zoom: this.safeZoom(), pan: next });
201
+ }
202
+ /**
203
+ * Ends a drag, releasing the capture it took.
204
+ *
205
+ * @param event - The pointerup or pointercancel event.
206
+ */
207
+ endDrag(event) {
208
+ const state = this.dragState;
209
+ if (state.pointerId !== event.pointerId)
210
+ return;
211
+ const canvas = this.surface?.nativeElement;
212
+ if (canvas && canvas.hasPointerCapture(event.pointerId)) {
213
+ canvas.releasePointerCapture(event.pointerId);
214
+ }
215
+ this.dragState = { pointerId: null, startX: 0, startY: 0, startPan: { x: 0, y: 0 } };
216
+ }
217
+ /**
218
+ * Reports the zoomed factor for a wheel scroll (negative `deltaY` zooms in).
219
+ *
220
+ * @param event - The wheel event.
221
+ */
222
+ handleWheel(event) {
223
+ const factor = event.deltaY < 0 ? 1.1 : 1 / 1.1;
224
+ const nextZoom = clamp(this.safeZoom() * factor, 0.05, 32);
225
+ this.onChange?.({ zoom: nextZoom, pan: this.safePan() });
226
+ }
227
+ /** The sanitised zoom factor (React's `safeZoom`). */
228
+ safeZoom() {
229
+ const zoom = this.zoom;
230
+ return zoom !== undefined && Number.isFinite(zoom) && zoom > 0 ? zoom : 1;
231
+ }
232
+ /** The sanitised pan offset (React's `safePan`). */
233
+ safePan() {
234
+ return {
235
+ x: Number.isFinite(this.pan?.x) ? this.pan?.x : 0,
236
+ y: Number.isFinite(this.pan?.y) ? this.pan?.y : 0,
237
+ };
238
+ }
239
+ /**
240
+ * Loads a URL source into an internal image (React's loading effect).
241
+ *
242
+ * @param src - The URL or data URL.
243
+ */
244
+ load(src) {
245
+ const token = ++this.loadToken;
246
+ this.loadError.set(null);
247
+ const img = new Image();
248
+ img.crossOrigin = 'anonymous';
249
+ img.onload = () => {
250
+ if (token !== this.loadToken)
251
+ return;
252
+ this.image.set(img);
253
+ this.paint();
254
+ };
255
+ img.onerror = () => {
256
+ if (token !== this.loadToken)
257
+ return;
258
+ this.loadError.set(src);
259
+ this.image.set(null);
260
+ this.paint();
261
+ };
262
+ img.src = src;
263
+ }
264
+ /** Re-paints the canvas from the image, viewport and filter chain. */
265
+ paint() {
266
+ const canvas = this.surface?.nativeElement;
267
+ if (!canvas)
268
+ return;
269
+ const ctx = canvas.getContext('2d');
270
+ if (!ctx)
271
+ return;
272
+ const image = this.image();
273
+ const zoom = this.safeZoom();
274
+ const pan = this.safePan();
275
+ const width = this.widthValue();
276
+ const height = this.heightValue();
277
+ ctx.save();
278
+ ctx.clearRect(0, 0, width, height);
279
+ if (!image) {
280
+ ctx.restore();
281
+ return;
282
+ }
283
+ ctx.filter = composeFilterString(this.filters);
284
+ const drawWidth = image.naturalWidth * zoom;
285
+ const drawHeight = image.naturalHeight * zoom;
286
+ const dx = width / 2 - drawWidth / 2 + pan.x;
287
+ const dy = height / 2 - drawHeight / 2 + pan.y;
288
+ ctx.drawImage(image, dx, dy, drawWidth, drawHeight);
289
+ ctx.restore();
290
+ }
291
+ static ɵfac = function ImageCanvas_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || ImageCanvas)(); };
292
+ static ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: ImageCanvas, selectors: [["div", "mol-image-canvas", ""]], viewQuery: function ImageCanvas_Query(rf, ctx) { if (rf & 1) {
293
+ i0.ɵɵviewQuery(_c0, 5);
294
+ } if (rf & 2) {
295
+ let _t;
296
+ i0.ɵɵqueryRefresh(_t = i0.ɵɵloadQuery()) && (ctx.surface = _t.first);
297
+ } }, hostAttrs: ["role", "region", "data-mol-id", "image-canvas"], hostVars: 11, hostBindings: function ImageCanvas_HostBindings(rf, ctx) { if (rf & 2) {
298
+ i0.ɵɵattribute("aria-label", ctx.ariaLabel());
299
+ i0.ɵɵclassMap(ctx.classes());
300
+ i0.ɵɵstyleProp("display", "inline-block")("width", ctx.widthValue(), "px")("height", ctx.heightValue(), "px")("position", "relative");
301
+ } }, inputs: { src: "src", filters: "filters", zoom: "zoom", pan: "pan", onChange: "onChange", exportRef: "exportRef", width: "width", height: "height", className: "className" }, features: [i0.ɵɵNgOnChangesFeature], decls: 4, vars: 17, consts: [["surface", ""], ["data-mol-id", "image-canvas-surface", 3, "pointerdown", "pointermove", "pointerup", "pointercancel", "wheel"], ["data-mol-id", "image-canvas-loading", 3, "class"], ["data-mol-id", "image-canvas-error", "role", "alert", 3, "class"], ["data-mol-id", "image-canvas-loading"], ["data-mol-id", "image-canvas-error", "role", "alert"]], template: function ImageCanvas_Template(rf, ctx) { if (rf & 1) {
302
+ i0.ɵɵdomElementStart(0, "canvas", 1, 0);
303
+ i0.ɵɵdomListener("pointerdown", function ImageCanvas_Template_canvas_pointerdown_0_listener($event) { return ctx.handlePointerDown($event); })("pointermove", function ImageCanvas_Template_canvas_pointermove_0_listener($event) { return ctx.handlePointerMove($event); })("pointerup", function ImageCanvas_Template_canvas_pointerup_0_listener($event) { return ctx.endDrag($event); })("pointercancel", function ImageCanvas_Template_canvas_pointercancel_0_listener($event) { return ctx.endDrag($event); })("wheel", function ImageCanvas_Template_canvas_wheel_0_listener($event) { return ctx.handleWheel($event); });
304
+ i0.ɵɵdomElementEnd();
305
+ i0.ɵɵconditionalCreate(2, ImageCanvas_Conditional_2_Template, 2, 3, "p", 2);
306
+ i0.ɵɵconditionalCreate(3, ImageCanvas_Conditional_3_Template, 2, 3, "p", 3);
307
+ } if (rf & 2) {
308
+ i0.ɵɵstyleProp("display", "block")("width", ctx.widthValue(), "px")("height", ctx.heightValue(), "px")("cursor", ctx.cursor())("touch-action", "none");
309
+ i0.ɵɵattribute("width", ctx.widthValue())("height", ctx.heightValue())("aria-label", ctx.dragLabel())("data-loading", ctx.loadingAttr())("data-error", ctx.errorAttr());
310
+ i0.ɵɵadvance(2);
311
+ i0.ɵɵconditional(ctx.loadingAttr() === "true" ? 2 : -1);
312
+ i0.ɵɵadvance();
313
+ i0.ɵɵconditional(ctx.loadError() !== null ? 3 : -1);
314
+ } }, encapsulation: 2 });
315
+ }
316
+ (() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(ImageCanvas, [{
317
+ type: Component,
318
+ args: [{
319
+ selector: 'div[mol-image-canvas]',
320
+ standalone: true,
321
+ inputs: [
322
+ 'src',
323
+ 'filters',
324
+ 'zoom',
325
+ 'pan',
326
+ 'onChange',
327
+ 'exportRef',
328
+ 'width',
329
+ 'height',
330
+ 'className',
331
+ ],
332
+ host: {
333
+ role: 'region',
334
+ 'data-mol-id': 'image-canvas',
335
+ '[attr.aria-label]': 'ariaLabel()',
336
+ '[class]': 'classes()',
337
+ '[style.display]': '"inline-block"',
338
+ '[style.width.px]': 'widthValue()',
339
+ '[style.height.px]': 'heightValue()',
340
+ '[style.position]': '"relative"',
341
+ },
342
+ template: `<canvas
343
+ #surface
344
+ [attr.width]="widthValue()"
345
+ [attr.height]="heightValue()"
346
+ [attr.aria-label]="dragLabel()"
347
+ data-mol-id="image-canvas-surface"
348
+ [attr.data-loading]="loadingAttr()"
349
+ [attr.data-error]="errorAttr()"
350
+ [style.display]="'block'"
351
+ [style.width.px]="widthValue()"
352
+ [style.height.px]="heightValue()"
353
+ [style.cursor]="cursor()"
354
+ [style.touch-action]="'none'"
355
+ (pointerdown)="handlePointerDown($event)"
356
+ (pointermove)="handlePointerMove($event)"
357
+ (pointerup)="endDrag($event)"
358
+ (pointercancel)="endDrag($event)"
359
+ (wheel)="handleWheel($event)"
360
+ ></canvas>
361
+ @if (loadingAttr() === 'true') {
362
+ <p [class]="noteClasses()" data-mol-id="image-canvas-loading">{{ loadingLabel() }}</p>
363
+ }
364
+ @if (loadError() !== null) {
365
+ <p [class]="noteClasses()" data-mol-id="image-canvas-error" role="alert">
366
+ {{ errorLabel() }}
367
+ </p>
368
+ }`,
369
+ }]
370
+ }], null, { surface: [{
371
+ type: ViewChild,
372
+ args: ['surface']
373
+ }] }); })();
374
+ (() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(ImageCanvas, { className: "ImageCanvas", filePath: "image-canvas.component.ts", lineNumber: 90 }); })();
375
+ //# sourceMappingURL=image-canvas.component.js.map