@sdcorejs/angular 20.2.15 → 20.3.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.
Files changed (203) hide show
  1. package/README.md +7 -5
  2. package/assets/STYLE-GUIDE.md +6 -3
  3. package/assets/THEME.md +166 -0
  4. package/assets/fonts/fonts.scss +1 -1
  5. package/assets/scss/ckeditor5.scss +2 -2
  6. package/assets/scss/core/_inline-edit.scss +3 -3
  7. package/assets/scss/core/_read-state-panel.scss +2 -2
  8. package/assets/scss/core/color.scss +4 -2
  9. package/assets/scss/core/form.scss +35 -12
  10. package/assets/scss/core/scrollbar.scss +3 -3
  11. package/assets/scss/core/utilities/_base.scss +5 -5
  12. package/assets/scss/core/utilities/_typography.scss +22 -22
  13. package/assets/scss/sd-core.scss +12 -0
  14. package/assets/scss/themes/_component-tokens.scss +261 -0
  15. package/assets/scss/themes/_presets.scss +3 -0
  16. package/assets/scss/themes/_ramps.scss +56 -0
  17. package/assets/scss/themes/_scales.scss +90 -0
  18. package/assets/scss/themes/_semantic.scss +22 -0
  19. package/assets/scss/themes/default.scss +113 -10
  20. package/assets/scss/themes/material-theme.scss +3 -0
  21. package/components/breadcrumb/index.d.ts +2 -1
  22. package/components/data-state/index.d.ts +6 -2
  23. package/components/file-explorer/index.d.ts +3 -0
  24. package/components/form-generic/index.d.ts +897 -835
  25. package/components/highlight/index.d.ts +27 -0
  26. package/components/image-editor/index.d.ts +478 -0
  27. package/components/index.d.ts +2 -0
  28. package/components/inform/index.d.ts +5 -2
  29. package/components/mini-editor/index.d.ts +1 -1
  30. package/components/preview/index.d.ts +51 -2
  31. package/components/query-builder/index.d.ts +1 -1
  32. package/components/section/index.d.ts +5 -1
  33. package/components/table/index.d.ts +6 -0
  34. package/directives/index.d.ts +8 -0
  35. package/fesm2022/sdcorejs-angular-components-anchor.mjs +2 -2
  36. package/fesm2022/sdcorejs-angular-components-anchor.mjs.map +1 -1
  37. package/fesm2022/sdcorejs-angular-components-api-contract-builder.mjs +6 -6
  38. package/fesm2022/sdcorejs-angular-components-api-contract-builder.mjs.map +1 -1
  39. package/fesm2022/sdcorejs-angular-components-audit-diff.mjs +2 -2
  40. package/fesm2022/sdcorejs-angular-components-audit-diff.mjs.map +1 -1
  41. package/fesm2022/sdcorejs-angular-components-autoid-inspector.mjs +2 -2
  42. package/fesm2022/sdcorejs-angular-components-autoid-inspector.mjs.map +1 -1
  43. package/fesm2022/sdcorejs-angular-components-avatar.mjs +34 -27
  44. package/fesm2022/sdcorejs-angular-components-avatar.mjs.map +1 -1
  45. package/fesm2022/sdcorejs-angular-components-badge.mjs +2 -2
  46. package/fesm2022/sdcorejs-angular-components-badge.mjs.map +1 -1
  47. package/fesm2022/sdcorejs-angular-components-breadcrumb.mjs +35 -5
  48. package/fesm2022/sdcorejs-angular-components-breadcrumb.mjs.map +1 -1
  49. package/fesm2022/sdcorejs-angular-components-button.mjs +13 -11
  50. package/fesm2022/sdcorejs-angular-components-button.mjs.map +1 -1
  51. package/fesm2022/sdcorejs-angular-components-card.mjs +2 -2
  52. package/fesm2022/sdcorejs-angular-components-card.mjs.map +1 -1
  53. package/fesm2022/sdcorejs-angular-components-ckeditor-styles.mjs +2 -2
  54. package/fesm2022/sdcorejs-angular-components-ckeditor-styles.mjs.map +1 -1
  55. package/fesm2022/sdcorejs-angular-components-code-editor.mjs +2 -2
  56. package/fesm2022/sdcorejs-angular-components-code-editor.mjs.map +1 -1
  57. package/fesm2022/sdcorejs-angular-components-data-state.mjs +8 -4
  58. package/fesm2022/sdcorejs-angular-components-data-state.mjs.map +1 -1
  59. package/fesm2022/sdcorejs-angular-components-editor.mjs +12 -4
  60. package/fesm2022/sdcorejs-angular-components-editor.mjs.map +1 -1
  61. package/fesm2022/sdcorejs-angular-components-file-explorer.mjs +105 -50
  62. package/fesm2022/sdcorejs-angular-components-file-explorer.mjs.map +1 -1
  63. package/fesm2022/sdcorejs-angular-components-form-generic.mjs +5846 -6504
  64. package/fesm2022/sdcorejs-angular-components-form-generic.mjs.map +1 -1
  65. package/fesm2022/sdcorejs-angular-components-highlight.mjs +63 -0
  66. package/fesm2022/sdcorejs-angular-components-highlight.mjs.map +1 -0
  67. package/fesm2022/sdcorejs-angular-components-history.mjs +2 -2
  68. package/fesm2022/sdcorejs-angular-components-history.mjs.map +1 -1
  69. package/fesm2022/sdcorejs-angular-components-image-editor.mjs +2088 -0
  70. package/fesm2022/sdcorejs-angular-components-image-editor.mjs.map +1 -0
  71. package/fesm2022/sdcorejs-angular-components-import-excel.mjs +2 -2
  72. package/fesm2022/sdcorejs-angular-components-import-excel.mjs.map +1 -1
  73. package/fesm2022/sdcorejs-angular-components-inform.mjs +9 -5
  74. package/fesm2022/sdcorejs-angular-components-inform.mjs.map +1 -1
  75. package/fesm2022/sdcorejs-angular-components-job-progress.mjs +2 -2
  76. package/fesm2022/sdcorejs-angular-components-job-progress.mjs.map +1 -1
  77. package/fesm2022/sdcorejs-angular-components-mini-editor.mjs +40 -22
  78. package/fesm2022/sdcorejs-angular-components-mini-editor.mjs.map +1 -1
  79. package/fesm2022/sdcorejs-angular-components-modal-resizable.mjs +2 -2
  80. package/fesm2022/sdcorejs-angular-components-modal-resizable.mjs.map +1 -1
  81. package/fesm2022/sdcorejs-angular-components-modal.mjs +2 -2
  82. package/fesm2022/sdcorejs-angular-components-modal.mjs.map +1 -1
  83. package/fesm2022/sdcorejs-angular-components-operator.mjs +2 -2
  84. package/fesm2022/sdcorejs-angular-components-operator.mjs.map +1 -1
  85. package/fesm2022/sdcorejs-angular-components-org-chart.mjs +2 -2
  86. package/fesm2022/sdcorejs-angular-components-org-chart.mjs.map +1 -1
  87. package/fesm2022/sdcorejs-angular-components-preview.mjs +129 -7
  88. package/fesm2022/sdcorejs-angular-components-preview.mjs.map +1 -1
  89. package/fesm2022/sdcorejs-angular-components-query-bar.mjs +33 -24
  90. package/fesm2022/sdcorejs-angular-components-query-bar.mjs.map +1 -1
  91. package/fesm2022/sdcorejs-angular-components-query-builder.mjs +2 -2
  92. package/fesm2022/sdcorejs-angular-components-query-builder.mjs.map +1 -1
  93. package/fesm2022/sdcorejs-angular-components-quick-action.mjs +2 -2
  94. package/fesm2022/sdcorejs-angular-components-quick-action.mjs.map +1 -1
  95. package/fesm2022/sdcorejs-angular-components-section.mjs +11 -7
  96. package/fesm2022/sdcorejs-angular-components-section.mjs.map +1 -1
  97. package/fesm2022/sdcorejs-angular-components-side-drawer.mjs +28 -4
  98. package/fesm2022/sdcorejs-angular-components-side-drawer.mjs.map +1 -1
  99. package/fesm2022/sdcorejs-angular-components-splitter.mjs +2 -2
  100. package/fesm2022/sdcorejs-angular-components-splitter.mjs.map +1 -1
  101. package/fesm2022/sdcorejs-angular-components-stepper.mjs +2 -2
  102. package/fesm2022/sdcorejs-angular-components-stepper.mjs.map +1 -1
  103. package/fesm2022/sdcorejs-angular-components-tab-router.mjs +4 -4
  104. package/fesm2022/sdcorejs-angular-components-tab-router.mjs.map +1 -1
  105. package/fesm2022/sdcorejs-angular-components-tab.mjs +2 -2
  106. package/fesm2022/sdcorejs-angular-components-tab.mjs.map +1 -1
  107. package/fesm2022/sdcorejs-angular-components-table.mjs +308 -113
  108. package/fesm2022/sdcorejs-angular-components-table.mjs.map +1 -1
  109. package/fesm2022/sdcorejs-angular-components-tree.mjs +2 -2
  110. package/fesm2022/sdcorejs-angular-components-tree.mjs.map +1 -1
  111. package/fesm2022/sdcorejs-angular-components-upload-file.mjs +14 -5
  112. package/fesm2022/sdcorejs-angular-components-upload-file.mjs.map +1 -1
  113. package/fesm2022/sdcorejs-angular-components.mjs +2 -0
  114. package/fesm2022/sdcorejs-angular-components.mjs.map +1 -1
  115. package/fesm2022/sdcorejs-angular-directives.mjs +99 -13
  116. package/fesm2022/sdcorejs-angular-directives.mjs.map +1 -1
  117. package/fesm2022/sdcorejs-angular-forms-autocomplete.mjs +149 -6
  118. package/fesm2022/sdcorejs-angular-forms-autocomplete.mjs.map +1 -1
  119. package/fesm2022/sdcorejs-angular-forms-chip-calendar.mjs +19 -4
  120. package/fesm2022/sdcorejs-angular-forms-chip-calendar.mjs.map +1 -1
  121. package/fesm2022/sdcorejs-angular-forms-chip.mjs +19 -4
  122. package/fesm2022/sdcorejs-angular-forms-chip.mjs.map +1 -1
  123. package/fesm2022/sdcorejs-angular-forms-date-range.mjs +2 -2
  124. package/fesm2022/sdcorejs-angular-forms-date-range.mjs.map +1 -1
  125. package/fesm2022/sdcorejs-angular-forms-date.mjs +17 -7
  126. package/fesm2022/sdcorejs-angular-forms-date.mjs.map +1 -1
  127. package/fesm2022/sdcorejs-angular-forms-datetime.mjs +17 -7
  128. package/fesm2022/sdcorejs-angular-forms-datetime.mjs.map +1 -1
  129. package/fesm2022/sdcorejs-angular-forms-entity-picker.mjs +2 -2
  130. package/fesm2022/sdcorejs-angular-forms-entity-picker.mjs.map +1 -1
  131. package/fesm2022/sdcorejs-angular-forms-inline-text.mjs +3 -3
  132. package/fesm2022/sdcorejs-angular-forms-inline-text.mjs.map +1 -1
  133. package/fesm2022/sdcorejs-angular-forms-input-color.mjs +2 -2
  134. package/fesm2022/sdcorejs-angular-forms-input-color.mjs.map +1 -1
  135. package/fesm2022/sdcorejs-angular-forms-input-number.mjs +18 -4
  136. package/fesm2022/sdcorejs-angular-forms-input-number.mjs.map +1 -1
  137. package/fesm2022/sdcorejs-angular-forms-input.mjs +29 -5
  138. package/fesm2022/sdcorejs-angular-forms-input.mjs.map +1 -1
  139. package/fesm2022/sdcorejs-angular-forms-label.mjs +27 -2
  140. package/fesm2022/sdcorejs-angular-forms-label.mjs.map +1 -1
  141. package/fesm2022/sdcorejs-angular-forms-radio.mjs +1 -1
  142. package/fesm2022/sdcorejs-angular-forms-radio.mjs.map +1 -1
  143. package/fesm2022/sdcorejs-angular-forms-select.mjs +498 -7
  144. package/fesm2022/sdcorejs-angular-forms-select.mjs.map +1 -1
  145. package/fesm2022/sdcorejs-angular-forms-switch.mjs +1 -1
  146. package/fesm2022/sdcorejs-angular-forms-switch.mjs.map +1 -1
  147. package/fesm2022/sdcorejs-angular-forms-textarea.mjs +22 -4
  148. package/fesm2022/sdcorejs-angular-forms-textarea.mjs.map +1 -1
  149. package/fesm2022/sdcorejs-angular-forms-time-range.mjs +2 -2
  150. package/fesm2022/sdcorejs-angular-forms-time-range.mjs.map +1 -1
  151. package/fesm2022/sdcorejs-angular-forms-time.mjs +2 -2
  152. package/fesm2022/sdcorejs-angular-forms-time.mjs.map +1 -1
  153. package/fesm2022/sdcorejs-angular-forms-tree-select.mjs +1 -1
  154. package/fesm2022/sdcorejs-angular-forms-tree-select.mjs.map +1 -1
  155. package/fesm2022/sdcorejs-angular-i18n.mjs +1429 -271
  156. package/fesm2022/sdcorejs-angular-i18n.mjs.map +1 -1
  157. package/fesm2022/sdcorejs-angular-modules-auth.mjs +35 -3
  158. package/fesm2022/sdcorejs-angular-modules-auth.mjs.map +1 -1
  159. package/fesm2022/sdcorejs-angular-modules-icon.mjs +19 -0
  160. package/fesm2022/sdcorejs-angular-modules-icon.mjs.map +1 -1
  161. package/fesm2022/sdcorejs-angular-modules-layout.mjs +39 -48
  162. package/fesm2022/sdcorejs-angular-modules-layout.mjs.map +1 -1
  163. package/fesm2022/sdcorejs-angular-modules-permission.mjs.map +1 -1
  164. package/fesm2022/sdcorejs-angular-services-api.mjs +196 -8
  165. package/fesm2022/sdcorejs-angular-services-api.mjs.map +1 -1
  166. package/fesm2022/sdcorejs-angular-services-confirm.mjs +10 -3
  167. package/fesm2022/sdcorejs-angular-services-confirm.mjs.map +1 -1
  168. package/fesm2022/sdcorejs-angular-services-excel.mjs +5 -0
  169. package/fesm2022/sdcorejs-angular-services-excel.mjs.map +1 -1
  170. package/fesm2022/sdcorejs-angular-services-loading.mjs +1 -1
  171. package/fesm2022/sdcorejs-angular-services-loading.mjs.map +1 -1
  172. package/fesm2022/sdcorejs-angular-services-notify.mjs +107 -7
  173. package/fesm2022/sdcorejs-angular-services-notify.mjs.map +1 -1
  174. package/fesm2022/sdcorejs-angular-utilities-extensions.mjs +458 -1
  175. package/fesm2022/sdcorejs-angular-utilities-extensions.mjs.map +1 -1
  176. package/fesm2022/sdcorejs-angular-utilities-theme.mjs +169 -0
  177. package/fesm2022/sdcorejs-angular-utilities-theme.mjs.map +1 -0
  178. package/fesm2022/sdcorejs-angular-utilities.mjs +1 -0
  179. package/fesm2022/sdcorejs-angular-utilities.mjs.map +1 -1
  180. package/forms/autocomplete/index.d.ts +19 -1
  181. package/forms/chip/index.d.ts +13 -2
  182. package/forms/chip-calendar/index.d.ts +13 -2
  183. package/forms/date/index.d.ts +7 -2
  184. package/forms/datetime/index.d.ts +7 -2
  185. package/forms/inline-text/index.d.ts +1 -1
  186. package/forms/input/index.d.ts +21 -5
  187. package/forms/input-number/index.d.ts +12 -2
  188. package/forms/label/index.d.ts +16 -1
  189. package/forms/models/index.d.ts +16 -1
  190. package/forms/select/index.d.ts +66 -4
  191. package/forms/textarea/index.d.ts +9 -2
  192. package/i18n/index.d.ts +285 -54
  193. package/modules/auth/index.d.ts +3 -3
  194. package/modules/icon/index.d.ts +11 -1
  195. package/modules/layout/index.d.ts +2 -2
  196. package/modules/permission/index.d.ts +3 -2
  197. package/package.json +14 -2
  198. package/services/api/index.d.ts +49 -2
  199. package/services/confirm/index.d.ts +15 -0
  200. package/services/notify/index.d.ts +8 -0
  201. package/utilities/extensions/index.d.ts +68 -1
  202. package/utilities/index.d.ts +1 -0
  203. package/utilities/theme/index.d.ts +25 -0
@@ -0,0 +1,2088 @@
1
+ import { DOCUMENT, isPlatformBrowser } from '@angular/common';
2
+ import * as i0 from '@angular/core';
3
+ import { inject, ElementRef, Injector, NgZone, PLATFORM_ID, input, output, signal, viewChild, computed, effect, untracked, afterNextRender, DestroyRef, ChangeDetectionStrategy, Component } from '@angular/core';
4
+ import { SdButton } from '@sdcorejs/angular/components/button';
5
+ import { SdTooltipDirective } from '@sdcorejs/angular/directives';
6
+ import { SdInputNumber } from '@sdcorejs/angular/forms/input-number';
7
+ import { SdSelect } from '@sdcorejs/angular/forms/select';
8
+ import { I18nService, SdTranslatePipe } from '@sdcorejs/angular/i18n';
9
+ import { SdIcon } from '@sdcorejs/angular/modules/icon';
10
+
11
+ const SD_IMAGE_EDITOR_IDENTITY = [1, 0, 0, 1, 0, 0];
12
+ /** `m · n`: the returned matrix applies `n` first, then `m`. */
13
+ function sdImageEditorMultiply(m, n) {
14
+ const [a, b, c, d, e, f] = m;
15
+ const [a2, b2, c2, d2, e2, f2] = n;
16
+ return [a * a2 + c * b2, b * a2 + d * b2, a * c2 + c * d2, b * c2 + d * d2, a * e2 + c * f2 + e, b * e2 + d * f2 + f];
17
+ }
18
+ /** Product of the matrices, applied right to left (the last one first). */
19
+ function sdImageEditorCompose(...matrices) {
20
+ return matrices.reduce((acc, m) => sdImageEditorMultiply(acc, m), SD_IMAGE_EDITOR_IDENTITY);
21
+ }
22
+ function sdImageEditorInvert(m) {
23
+ const [a, b, c, d, e, f] = m;
24
+ const det = a * d - b * c;
25
+ if (!det)
26
+ throw new Error('sd-image-editor: matrix is not invertible');
27
+ const ia = d / det;
28
+ const ib = -b / det;
29
+ const ic = -c / det;
30
+ const id = a / det;
31
+ return [ia, ib, ic, id, -(ia * e + ic * f), -(ib * e + id * f)];
32
+ }
33
+ function sdImageEditorApply(m, x, y) {
34
+ return { x: m[0] * x + m[2] * y + m[4], y: m[1] * x + m[3] * y + m[5] };
35
+ }
36
+ function sdImageEditorTranslate(x, y) {
37
+ return [1, 0, 0, 1, x, y];
38
+ }
39
+ function sdImageEditorScale(x, y = x) {
40
+ return [x, 0, 0, y, 0, 0];
41
+ }
42
+ /** Size of the image once rotated: a quarter turn swaps width and height. */
43
+ function sdImageEditorOrientedSize(size, rotate) {
44
+ return rotate === 90 || rotate === 270 ? { width: size.height, height: size.width } : { width: size.width, height: size.height };
45
+ }
46
+ /**
47
+ * Maps a pixel of the decoded source (width × height, EXIF orientation already applied by the browser) to the
48
+ * oriented image the user edits: mirror horizontally first when `flip`, then rotate clockwise by `rotate`.
49
+ * The result always lies inside `[0, orientedWidth] × [0, orientedHeight]`.
50
+ */
51
+ function sdImageEditorOrientationMatrix(size, orientation) {
52
+ const { width: w, height: h } = size;
53
+ const mirror = orientation.flip ? [-1, 0, 0, 1, w, 0] : SD_IMAGE_EDITOR_IDENTITY;
54
+ return sdImageEditorMultiply(sdImageEditorRotationMatrix(size, orientation.rotate), mirror);
55
+ }
56
+ /** Clockwise rotation of a `size` box around its origin, translated back so the result starts at (0, 0). */
57
+ function sdImageEditorRotationMatrix(size, rotate) {
58
+ const { width: w, height: h } = size;
59
+ switch (rotate) {
60
+ case 90:
61
+ return [0, 1, -1, 0, h, 0];
62
+ case 180:
63
+ return [-1, 0, 0, -1, w, h];
64
+ case 270:
65
+ return [0, -1, 1, 0, 0, w];
66
+ default:
67
+ return SD_IMAGE_EDITOR_IDENTITY;
68
+ }
69
+ }
70
+ /**
71
+ * Matrix of a toolbar operation applied to the image as currently shown (`orientedSize`). Used to carry the crop
72
+ * rectangle along so it keeps framing the same content after a rotation or a flip.
73
+ */
74
+ function sdImageEditorOperationMatrix(op, orientedSize) {
75
+ const { width: w, height: h } = orientedSize;
76
+ switch (op) {
77
+ case 'rotate-cw':
78
+ return [0, 1, -1, 0, h, 0];
79
+ case 'rotate-ccw':
80
+ return [0, -1, 1, 0, 0, w];
81
+ case 'flip-horizontal':
82
+ return [-1, 0, 0, 1, w, 0];
83
+ default:
84
+ return [1, 0, 0, -1, 0, h];
85
+ }
86
+ }
87
+ /**
88
+ * Composes a screen-space operation into the canonical `{ flip, rotate }` pair.
89
+ *
90
+ * With `F` = horizontal mirror and `R(r)` = clockwise rotation, the state stands for `R(r)·F^flip`. Mirroring
91
+ * the displayed image gives `F·R(r) = R(−r)·F`, and a vertical mirror is `R(180)·F`, hence the formulas below.
92
+ */
93
+ function sdImageEditorApplyOperation(orientation, op) {
94
+ const r = orientation.rotate;
95
+ switch (op) {
96
+ case 'rotate-cw':
97
+ return { flip: orientation.flip, rotate: normalizeRotation(r + 90) };
98
+ case 'rotate-ccw':
99
+ return { flip: orientation.flip, rotate: normalizeRotation(r + 270) };
100
+ case 'flip-horizontal':
101
+ return { flip: !orientation.flip, rotate: normalizeRotation(360 - r) };
102
+ default:
103
+ return { flip: !orientation.flip, rotate: normalizeRotation(540 - r) };
104
+ }
105
+ }
106
+ function normalizeRotation(value) {
107
+ const r = (((Math.round(value / 90) * 90) % 360) + 360) % 360;
108
+ return r;
109
+ }
110
+ /**
111
+ * EXIF orientation (1–8) as the `{ flip, rotate }` pair that displays the stored pixels upright. Only used when
112
+ * the browser did not apply the orientation itself while decoding.
113
+ */
114
+ function sdImageEditorExifOrientation(value) {
115
+ switch (value) {
116
+ case 2:
117
+ return { flip: true, rotate: 0 };
118
+ case 3:
119
+ return { flip: false, rotate: 180 };
120
+ case 4:
121
+ return { flip: true, rotate: 180 };
122
+ case 5:
123
+ return { flip: true, rotate: 270 };
124
+ case 6:
125
+ return { flip: false, rotate: 90 };
126
+ case 7:
127
+ return { flip: true, rotate: 90 };
128
+ case 8:
129
+ return { flip: false, rotate: 270 };
130
+ default:
131
+ return { flip: false, rotate: 0 };
132
+ }
133
+ }
134
+ /** Bounding box of `rect` mapped through `m`, rounded to whole pixels. Exact for quarter turns and mirrors. */
135
+ function sdImageEditorTransformRect(rect, m) {
136
+ const p1 = sdImageEditorApply(m, rect.x, rect.y);
137
+ const p2 = sdImageEditorApply(m, rect.x + rect.width, rect.y + rect.height);
138
+ const x = Math.min(p1.x, p2.x);
139
+ const y = Math.min(p1.y, p2.y);
140
+ return {
141
+ x: roundPixel(x),
142
+ y: roundPixel(y),
143
+ width: roundPixel(Math.max(p1.x, p2.x) - x),
144
+ height: roundPixel(Math.max(p1.y, p2.y) - y),
145
+ };
146
+ }
147
+ /**
148
+ * Transform used by the export: source pixels → output canvas.
149
+ *
150
+ * `Scale(output / crop) · Translate(−crop) · Orientation`. Reads only the source, never a preview.
151
+ */
152
+ function sdImageEditorExportMatrix(sourceSize, orientation, crop, output) {
153
+ return sdImageEditorCompose(sdImageEditorScale(output.width / crop.width, output.height / crop.height), sdImageEditorTranslate(-crop.x, -crop.y), sdImageEditorOrientationMatrix(sourceSize, orientation));
154
+ }
155
+ const SD_IMAGE_EDITOR_FIT_VIEW = { zoom: 1, panX: 0, panY: 0 };
156
+ /** Scale at which the oriented image fits the stage minus `padding` on every side. */
157
+ function sdImageEditorFitScale(stage, image, padding) {
158
+ const width = Math.max(1, stage.width - padding * 2);
159
+ const height = Math.max(1, stage.height - padding * 2);
160
+ if (image.width <= 0 || image.height <= 0)
161
+ return 1;
162
+ return Math.min(width / image.width, height / image.height);
163
+ }
164
+ function sdImageEditorViewport(stage, image, view, padding) {
165
+ const scale = sdImageEditorFitScale(stage, image, padding) * view.zoom;
166
+ return {
167
+ scale,
168
+ originX: stage.width / 2 + view.panX - (image.width * scale) / 2,
169
+ originY: stage.height / 2 + view.panY - (image.height * scale) / 2,
170
+ };
171
+ }
172
+ /** Oriented image pixels → stage CSS pixels. */
173
+ function sdImageEditorViewMatrix(viewport) {
174
+ return [viewport.scale, 0, 0, viewport.scale, viewport.originX, viewport.originY];
175
+ }
176
+ function sdImageEditorImageToStage(viewport, rect) {
177
+ return {
178
+ x: viewport.originX + rect.x * viewport.scale,
179
+ y: viewport.originY + rect.y * viewport.scale,
180
+ width: rect.width * viewport.scale,
181
+ height: rect.height * viewport.scale,
182
+ };
183
+ }
184
+ function sdImageEditorStageToImage(viewport, x, y) {
185
+ return { x: (x - viewport.originX) / viewport.scale, y: (y - viewport.originY) / viewport.scale };
186
+ }
187
+ /**
188
+ * Keeps at least `margin` CSS pixels of the image inside the stage so the user cannot pan it out of reach.
189
+ */
190
+ function sdImageEditorClampPan(stage, image, view, padding, margin) {
191
+ const scale = sdImageEditorFitScale(stage, image, padding) * view.zoom;
192
+ const limitX = Math.max(0, (image.width * scale + stage.width) / 2 - margin);
193
+ const limitY = Math.max(0, (image.height * scale + stage.height) / 2 - margin);
194
+ return { zoom: view.zoom, panX: clamp(view.panX, -limitX, limitX), panY: clamp(view.panY, -limitY, limitY) };
195
+ }
196
+ /**
197
+ * Zooms by `factor` keeping the image point under (`anchorX`, `anchorY`) — stage CSS pixels — still under it.
198
+ */
199
+ function sdImageEditorZoomAt(stage, image, view, padding, zoom, anchorX, anchorY) {
200
+ const before = sdImageEditorViewport(stage, image, view, padding);
201
+ const point = sdImageEditorStageToImage(before, anchorX, anchorY);
202
+ const scale = sdImageEditorFitScale(stage, image, padding) * zoom;
203
+ // Solve origin so that `origin + point · scale = anchor`, then convert the origin back to a pan.
204
+ const originX = anchorX - point.x * scale;
205
+ const originY = anchorY - point.y * scale;
206
+ return {
207
+ zoom,
208
+ panX: originX + (image.width * scale) / 2 - stage.width / 2,
209
+ panY: originY + (image.height * scale) / 2 - stage.height / 2,
210
+ };
211
+ }
212
+ // ---- Crop rectangle ----
213
+ /** Whole-pixel rectangle inside `bounds`, at least 1 × 1. */
214
+ function sdImageEditorClampRect(rect, bounds) {
215
+ const width = clamp(Math.round(rect.width), 1, Math.max(1, bounds.width));
216
+ const height = clamp(Math.round(rect.height), 1, Math.max(1, bounds.height));
217
+ return {
218
+ x: clamp(Math.round(rect.x), 0, Math.max(0, bounds.width - width)),
219
+ y: clamp(Math.round(rect.y), 0, Math.max(0, bounds.height - height)),
220
+ width,
221
+ height,
222
+ };
223
+ }
224
+ /** Moves the rectangle by (`dx`, `dy`) without resizing it, stopping at the image edges. */
225
+ function sdImageEditorMoveRect(rect, dx, dy, bounds) {
226
+ return sdImageEditorClampRect({ ...rect, x: rect.x + dx, y: rect.y + dy }, bounds);
227
+ }
228
+ /** Largest whole-pixel size with `ratio` (width / height) inside `maxWidth × maxHeight`. */
229
+ function sdImageEditorFitRatio(maxWidth, maxHeight, ratio) {
230
+ let width = Math.min(maxWidth, maxHeight * ratio);
231
+ let height = width / ratio;
232
+ width = Math.max(1, Math.round(width));
233
+ height = Math.max(1, Math.round(height));
234
+ if (height > maxHeight)
235
+ height = Math.max(1, Math.floor(maxHeight));
236
+ if (width > maxWidth)
237
+ width = Math.max(1, Math.floor(maxWidth));
238
+ return { width, height };
239
+ }
240
+ /** Largest rectangle with `ratio` inside `bounds`, centred. `null` ratio returns the whole image. */
241
+ function sdImageEditorInitialCrop(bounds, ratio) {
242
+ if (!ratio)
243
+ return { x: 0, y: 0, width: bounds.width, height: bounds.height };
244
+ const size = sdImageEditorFitRatio(bounds.width, bounds.height, ratio);
245
+ return {
246
+ x: Math.round((bounds.width - size.width) / 2),
247
+ y: Math.round((bounds.height - size.height) / 2),
248
+ ...size,
249
+ };
250
+ }
251
+ /**
252
+ * Re-shapes `rect` to `ratio`, keeping its centre and roughly its area, then fits it inside `bounds`.
253
+ * Used when the user picks another ratio and when a quarter turn breaks a fixed ratio.
254
+ */
255
+ function sdImageEditorReshape(rect, ratio, bounds) {
256
+ const area = Math.max(1, rect.width * rect.height);
257
+ let width = Math.sqrt(area * ratio);
258
+ let height = width / ratio;
259
+ if (width > bounds.width) {
260
+ width = bounds.width;
261
+ height = width / ratio;
262
+ }
263
+ if (height > bounds.height) {
264
+ height = bounds.height;
265
+ width = height * ratio;
266
+ }
267
+ const size = sdImageEditorFitRatio(Math.min(bounds.width, Math.round(width)), Math.min(bounds.height, Math.round(height)), ratio);
268
+ const cx = rect.x + rect.width / 2;
269
+ const cy = rect.y + rect.height / 2;
270
+ return sdImageEditorClampRect({ x: cx - size.width / 2, y: cy - size.height / 2, ...size }, bounds);
271
+ }
272
+ /**
273
+ * Resizes `start` by dragging `handle` by (`dx`, `dy`) image pixels. The opposite edge or corner stays fixed; with
274
+ * a `ratio` the free dimension follows and edge handles grow symmetrically around the centre of the other axis.
275
+ * The result never leaves `bounds` and never gets smaller than `minSize` on either side.
276
+ */
277
+ function sdImageEditorResizeRect(start, handle, dx, dy, bounds, ratio, minSize) {
278
+ const min = Math.max(1, Math.min(minSize, bounds.width, bounds.height));
279
+ const hasW = handle.includes('w');
280
+ const hasE = handle.includes('e');
281
+ const hasN = handle.includes('n');
282
+ const hasS = handle.includes('s');
283
+ const left = start.x;
284
+ const top = start.y;
285
+ const right = start.x + start.width;
286
+ const bottom = start.y + start.height;
287
+ if (!ratio) {
288
+ const x1 = hasW ? clamp(left + dx, 0, right - min) : left;
289
+ const x2 = hasE ? clamp(right + dx, left + min, bounds.width) : right;
290
+ const y1 = hasN ? clamp(top + dy, 0, bottom - min) : top;
291
+ const y2 = hasS ? clamp(bottom + dy, top + min, bounds.height) : bottom;
292
+ return sdImageEditorClampRect({ x: x1, y: y1, width: x2 - x1, height: y2 - y1 }, bounds);
293
+ }
294
+ const minWidth = Math.max(min, min * ratio);
295
+ const horizontal = hasE || hasW;
296
+ const vertical = hasN || hasS;
297
+ let width;
298
+ let maxWidth;
299
+ if (horizontal && vertical) {
300
+ // Corner: follow the axis the pointer moved most along, relative to the ratio.
301
+ const byWidth = start.width + (hasE ? dx : -dx);
302
+ const byHeight = (start.height + (hasS ? dy : -dy)) * ratio;
303
+ width = Math.abs(byWidth - start.width) >= Math.abs(byHeight - start.width) ? byWidth : byHeight;
304
+ const roomX = hasE ? bounds.width - left : right;
305
+ const roomY = hasS ? bounds.height - top : bottom;
306
+ maxWidth = Math.min(roomX, roomY * ratio);
307
+ }
308
+ else if (horizontal) {
309
+ width = start.width + (hasE ? dx : -dx);
310
+ const cy = top + start.height / 2;
311
+ const roomX = hasE ? bounds.width - left : right;
312
+ maxWidth = Math.min(roomX, 2 * Math.min(cy, bounds.height - cy) * ratio);
313
+ }
314
+ else {
315
+ width = (start.height + (hasS ? dy : -dy)) * ratio;
316
+ const cx = left + start.width / 2;
317
+ const roomY = hasS ? bounds.height - top : bottom;
318
+ maxWidth = Math.min(roomY * ratio, 2 * Math.min(cx, bounds.width - cx));
319
+ }
320
+ width = maxWidth < minWidth ? maxWidth : clamp(width, minWidth, maxWidth);
321
+ const height = width / ratio;
322
+ let x;
323
+ let y;
324
+ if (horizontal)
325
+ x = hasE ? left : right - width;
326
+ else
327
+ x = left + start.width / 2 - width / 2;
328
+ if (vertical)
329
+ y = hasS ? top : bottom - height;
330
+ else
331
+ y = top + start.height / 2 - height / 2;
332
+ return sdImageEditorClampRect({ x, y, width, height }, bounds);
333
+ }
334
+ function sdImageEditorSameRect(a, b) {
335
+ return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
336
+ }
337
+ function clamp(value, min, max) {
338
+ return Math.min(max, Math.max(min, value));
339
+ }
340
+ function roundPixel(value) {
341
+ // why: `Math.round(-0)` là -0; so sánh bằng `===` vẫn đúng nhưng JSON/snapshot in ra "-0" gây nhiễu test.
342
+ return Math.round(value) || 0;
343
+ }
344
+
345
+ // Reads what the source is from its first bytes, before anything is decoded, then decodes it once.
346
+ // Browser APIs are only touched inside the functions, never at import time (SSR-safe).
347
+ /** How many leading bytes are read to find the format, the size, the alpha flag and the EXIF orientation. */
348
+ const SD_IMAGE_EDITOR_HEADER_BYTES = 256 * 1024;
349
+ /** Error raised by the loading and export pipeline; turned into `SdImageEditorError` by the component. */
350
+ class SdImageEditorFailure extends Error {
351
+ code;
352
+ detail;
353
+ constructor(code, detail) {
354
+ super(code);
355
+ this.code = code;
356
+ this.detail = detail;
357
+ this.name = 'SdImageEditorFailure';
358
+ }
359
+ }
360
+ const SD_IMAGE_EDITOR_EDITABLE_FORMATS = ['image/jpeg', 'image/png', 'image/webp'];
361
+ function sdImageEditorIsEditableFormat(format) {
362
+ return !!format && SD_IMAGE_EDITOR_EDITABLE_FORMATS.includes(format);
363
+ }
364
+ /** Format from magic bytes only — the declared `Blob.type` is never trusted. */
365
+ function sdImageEditorSniffFormat(bytes) {
366
+ const at = (offset, ...values) => values.every((value, i) => bytes[offset + i] === value);
367
+ const text = (offset, value) => at(offset, ...Array.from(value, char => char.charCodeAt(0)));
368
+ if (at(0, 0xff, 0xd8, 0xff))
369
+ return 'image/jpeg';
370
+ if (at(0, 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a))
371
+ return 'image/png';
372
+ if (text(0, 'RIFF') && text(8, 'WEBP'))
373
+ return 'image/webp';
374
+ if (text(0, 'GIF87a') || text(0, 'GIF89a'))
375
+ return 'image/gif';
376
+ if (text(0, 'BM'))
377
+ return 'image/bmp';
378
+ if (at(0, 0x49, 0x49, 0x2a, 0x00) || at(0, 0x4d, 0x4d, 0x00, 0x2a))
379
+ return 'image/tiff';
380
+ if (at(0, 0x00, 0x00, 0x01, 0x00))
381
+ return 'image/x-icon';
382
+ if (text(4, 'ftyp')) {
383
+ const brand = String.fromCharCode(...bytes.subarray(8, 12));
384
+ if (brand === 'avif' || brand === 'avis')
385
+ return 'image/avif';
386
+ if (['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1'].includes(brand))
387
+ return 'image/heic';
388
+ }
389
+ const head = new TextDecoder().decode(bytes.subarray(0, 512)).trimStart().toLowerCase();
390
+ if (head.startsWith('<svg') || (head.startsWith('<?xml') && head.includes('<svg')))
391
+ return 'image/svg+xml';
392
+ return null;
393
+ }
394
+ /** Parses the header of a JPEG, PNG or WebP. Other formats only report `format`. */
395
+ function sdImageEditorReadHeader(bytes) {
396
+ const format = sdImageEditorSniffFormat(bytes);
397
+ const base = { format, hasAlpha: false, animated: false, orientation: 1 };
398
+ try {
399
+ if (format === 'image/jpeg')
400
+ return { ...base, ...readJpeg(bytes) };
401
+ if (format === 'image/png')
402
+ return { ...base, ...readPng(bytes) };
403
+ if (format === 'image/webp')
404
+ return { ...base, ...readWebp(bytes) };
405
+ }
406
+ catch {
407
+ // why: header hỏng không được làm sập luồng — để bước decode của trình duyệt quyết định và báo decode-failed.
408
+ }
409
+ return base;
410
+ }
411
+ function view(bytes) {
412
+ return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
413
+ }
414
+ function readJpeg(bytes) {
415
+ const data = view(bytes);
416
+ const result = { orientation: 1 };
417
+ let offset = 2;
418
+ while (offset + 4 <= bytes.length) {
419
+ if (bytes[offset] !== 0xff)
420
+ break;
421
+ const marker = bytes[offset + 1];
422
+ if (marker === 0xff) {
423
+ offset++;
424
+ continue;
425
+ }
426
+ // Standalone markers carry no length.
427
+ if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
428
+ offset += 2;
429
+ continue;
430
+ }
431
+ if (marker === 0xd9 || marker === 0xda)
432
+ break;
433
+ const length = data.getUint16(offset + 2);
434
+ if (length < 2)
435
+ break;
436
+ const start = offset + 4;
437
+ if (marker === 0xe1 && start + 6 <= bytes.length && isExif(bytes, start)) {
438
+ result.orientation = readExifOrientation(bytes, start + 6, Math.min(bytes.length, offset + 2 + length));
439
+ }
440
+ const isSof = marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;
441
+ if (isSof && start + 5 <= bytes.length) {
442
+ result.height = data.getUint16(start + 1);
443
+ result.width = data.getUint16(start + 3);
444
+ break;
445
+ }
446
+ offset += 2 + length;
447
+ }
448
+ return result;
449
+ }
450
+ function isExif(bytes, start) {
451
+ return (bytes[start] === 0x45 && bytes[start + 1] === 0x78 && bytes[start + 2] === 0x69 && bytes[start + 3] === 0x66 && bytes[start + 4] === 0);
452
+ }
453
+ function readExifOrientation(bytes, tiff, end) {
454
+ const data = view(bytes);
455
+ if (tiff + 8 > end)
456
+ return 1;
457
+ const little = bytes[tiff] === 0x49 && bytes[tiff + 1] === 0x49;
458
+ const big = bytes[tiff] === 0x4d && bytes[tiff + 1] === 0x4d;
459
+ if (!little && !big)
460
+ return 1;
461
+ const u16 = (at) => data.getUint16(at, little);
462
+ const u32 = (at) => data.getUint32(at, little);
463
+ if (u16(tiff + 2) !== 42)
464
+ return 1;
465
+ const ifd = tiff + u32(tiff + 4);
466
+ if (ifd + 2 > end)
467
+ return 1;
468
+ const count = u16(ifd);
469
+ for (let i = 0; i < count; i++) {
470
+ const entry = ifd + 2 + i * 12;
471
+ if (entry + 12 > end)
472
+ break;
473
+ if (u16(entry) === 0x0112) {
474
+ const value = u16(entry + 8);
475
+ return value >= 1 && value <= 8 ? value : 1;
476
+ }
477
+ }
478
+ return 1;
479
+ }
480
+ function readPng(bytes) {
481
+ const data = view(bytes);
482
+ if (bytes.length < 33)
483
+ return {};
484
+ const width = data.getUint32(16);
485
+ const height = data.getUint32(20);
486
+ const colorType = bytes[25];
487
+ let hasAlpha = colorType === 4 || colorType === 6;
488
+ let animated = false;
489
+ let offset = 8;
490
+ // acTL (APNG) and tRNS must appear before the first IDAT chunk.
491
+ while (offset + 8 <= bytes.length) {
492
+ const length = data.getUint32(offset);
493
+ const type = String.fromCharCode(bytes[offset + 4], bytes[offset + 5], bytes[offset + 6], bytes[offset + 7]);
494
+ if (type === 'IDAT' || type === 'IEND')
495
+ break;
496
+ if (type === 'acTL')
497
+ animated = true;
498
+ if (type === 'tRNS')
499
+ hasAlpha = true;
500
+ offset += 12 + length;
501
+ }
502
+ return { width, height, hasAlpha, animated };
503
+ }
504
+ function readWebp(bytes) {
505
+ const data = view(bytes);
506
+ const chunk = String.fromCharCode(bytes[12], bytes[13], bytes[14], bytes[15]);
507
+ if (chunk === 'VP8X' && bytes.length >= 30) {
508
+ const flags = bytes[20];
509
+ const width = 1 + (bytes[24] | (bytes[25] << 8) | (bytes[26] << 16));
510
+ const height = 1 + (bytes[27] | (bytes[28] << 8) | (bytes[29] << 16));
511
+ return { width, height, hasAlpha: (flags & 0x10) !== 0, animated: (flags & 0x02) !== 0 };
512
+ }
513
+ if (chunk === 'VP8 ' && bytes.length >= 30) {
514
+ return { width: data.getUint16(26, true) & 0x3fff, height: data.getUint16(28, true) & 0x3fff, hasAlpha: false, animated: false };
515
+ }
516
+ if (chunk === 'VP8L' && bytes.length >= 25 && bytes[20] === 0x2f) {
517
+ const b1 = bytes[21];
518
+ const b2 = bytes[22];
519
+ const b3 = bytes[23];
520
+ const b4 = bytes[24];
521
+ const width = 1 + (b1 | ((b2 & 0x3f) << 8));
522
+ const height = 1 + ((b2 >> 6) | (b3 << 2) | ((b4 & 0x0f) << 10));
523
+ return { width, height, hasAlpha: ((b4 >> 4) & 1) === 1, animated: false };
524
+ }
525
+ return {};
526
+ }
527
+ async function sdImageEditorInspect(blob, limits) {
528
+ if (blob.size > limits.maxSourceSize)
529
+ throw new SdImageEditorFailure('source-too-large', blob.size);
530
+ if (blob.size === 0)
531
+ throw new SdImageEditorFailure('decode-failed');
532
+ const bytes = new Uint8Array(await blob.slice(0, SD_IMAGE_EDITOR_HEADER_BYTES).arrayBuffer());
533
+ const header = sdImageEditorReadHeader(bytes);
534
+ if (!sdImageEditorIsEditableFormat(header.format))
535
+ throw new SdImageEditorFailure('unsupported-format', header.format ?? blob.type);
536
+ if (header.animated)
537
+ throw new SdImageEditorFailure('animated', header.format);
538
+ if (header.width && header.height && header.width * header.height > limits.maxSourcePixels) {
539
+ throw new SdImageEditorFailure('source-too-many-pixels', { width: header.width, height: header.height });
540
+ }
541
+ return header;
542
+ }
543
+ /**
544
+ * Inspects then decodes `blob`. The pixel limit is checked on the header before decoding and again on the decoded
545
+ * size, for JPEGs whose frame header lies beyond the bytes read.
546
+ */
547
+ async function sdImageEditorLoad(blob, limits, doc) {
548
+ const header = await sdImageEditorInspect(blob, limits);
549
+ const decoded = await sdImageEditorDecode(blob, header, doc);
550
+ if (decoded.width * decoded.height > limits.maxSourcePixels) {
551
+ decoded.release();
552
+ throw new SdImageEditorFailure('source-too-many-pixels', { width: decoded.width, height: decoded.height });
553
+ }
554
+ return { header, decoded };
555
+ }
556
+ /**
557
+ * Decodes once, letting the browser apply the EXIF orientation (`imageOrientation: 'from-image'`, the default of
558
+ * every current engine). The pixels are never rotated again by the editor, so no double rotation can happen.
559
+ *
560
+ * Only if the decoded size shows that a swapping orientation (5–8) was ignored, the orientation is applied here,
561
+ * exactly once.
562
+ */
563
+ async function sdImageEditorDecode(blob, header, doc) {
564
+ const win = doc.defaultView;
565
+ let decoded;
566
+ try {
567
+ decoded = win && typeof win.createImageBitmap === 'function' ? await decodeBitmap(win, blob) : await decodeElement(doc, blob);
568
+ }
569
+ catch (error) {
570
+ if (error instanceof SdImageEditorFailure)
571
+ throw error;
572
+ throw new SdImageEditorFailure('decode-failed', error);
573
+ }
574
+ if (!decoded.width || !decoded.height) {
575
+ decoded.release();
576
+ throw new SdImageEditorFailure('decode-failed');
577
+ }
578
+ const swaps = header.orientation >= 5 && header.orientation <= 8;
579
+ const ignored = swaps && header.width !== header.height && decoded.width === header.width && decoded.height === header.height;
580
+ if (!ignored)
581
+ return decoded;
582
+ try {
583
+ return orient(doc, decoded, header.orientation);
584
+ }
585
+ finally {
586
+ decoded.release();
587
+ }
588
+ }
589
+ async function decodeBitmap(win, blob) {
590
+ let bitmap;
591
+ try {
592
+ bitmap = await win.createImageBitmap(blob, { imageOrientation: 'from-image' });
593
+ }
594
+ catch (error) {
595
+ // why: engine cũ chỉ biết 'none' | 'flipY' → option lạ ném TypeError ngay khi gọi. Thử lại với mặc định của engine.
596
+ if (!(error instanceof TypeError))
597
+ throw error;
598
+ bitmap = await win.createImageBitmap(blob);
599
+ }
600
+ return { image: bitmap, width: bitmap.width, height: bitmap.height, release: () => bitmap.close() };
601
+ }
602
+ async function decodeElement(doc, blob) {
603
+ const urlApi = doc.defaultView?.URL;
604
+ if (!urlApi?.createObjectURL)
605
+ throw new SdImageEditorFailure('decode-failed');
606
+ const url = urlApi.createObjectURL(blob);
607
+ const img = doc.createElement('img');
608
+ try {
609
+ img.src = url;
610
+ await img.decode();
611
+ }
612
+ catch (error) {
613
+ urlApi.revokeObjectURL(url);
614
+ throw error;
615
+ }
616
+ // why: giữ object URL tới khi release — trình duyệt có thể bỏ bản decode và đọc lại URL khi drawImage.
617
+ return { image: img, width: img.naturalWidth, height: img.naturalHeight, release: () => urlApi.revokeObjectURL(url) };
618
+ }
619
+ function orient(doc, decoded, exif) {
620
+ const orientation = sdImageEditorExifOrientation(exif);
621
+ const source = { width: decoded.width, height: decoded.height };
622
+ const size = sdImageEditorOrientedSize(source, orientation.rotate);
623
+ const canvas = doc.createElement('canvas');
624
+ canvas.width = size.width;
625
+ canvas.height = size.height;
626
+ const ctx = canvas.getContext('2d');
627
+ if (!ctx)
628
+ throw new SdImageEditorFailure('render-failed');
629
+ ctx.setTransform(...sdImageEditorOrientationMatrix(source, orientation));
630
+ ctx.drawImage(decoded.image, 0, 0, source.width, source.height);
631
+ return { image: canvas, width: size.width, height: size.height, release: () => sdImageEditorReleaseCanvas(canvas) };
632
+ }
633
+ /** Shrinks a canvas to 0 × 0 so its backing store is freed now (Safari keeps it until GC otherwise). */
634
+ function sdImageEditorReleaseCanvas(canvas) {
635
+ canvas.width = 0;
636
+ canvas.height = 0;
637
+ }
638
+
639
+ /** Draws the edited image at the output size. The caller owns the canvas and must release it. */
640
+ function sdImageEditorRender(doc, request) {
641
+ const { source, edits, output, format } = request;
642
+ const canvas = doc.createElement('canvas');
643
+ canvas.width = output.width;
644
+ canvas.height = output.height;
645
+ // why: trình duyệt trả canvas 0×0 hoặc context null khi vượt giới hạn bộ nhớ thiết bị (iOS ~16.7 MP) thay vì ném lỗi.
646
+ const ctx = canvas.width === output.width && canvas.height === output.height ? canvas.getContext('2d') : null;
647
+ if (!ctx) {
648
+ sdImageEditorReleaseCanvas(canvas);
649
+ throw new SdImageEditorFailure('render-failed', output);
650
+ }
651
+ if (format === 'image/jpeg') {
652
+ // JPEG has no alpha: composite over white first so a translucent background colour stays predictable.
653
+ ctx.fillStyle = 'white';
654
+ ctx.fillRect(0, 0, output.width, output.height);
655
+ ctx.fillStyle = request.background || 'white';
656
+ ctx.fillRect(0, 0, output.width, output.height);
657
+ }
658
+ ctx.imageSmoothingEnabled = true;
659
+ ctx.imageSmoothingQuality = 'high';
660
+ ctx.setTransform(...sdImageEditorExportMatrix({ width: source.width, height: source.height }, edits, edits.crop, output));
661
+ ctx.drawImage(source.image, 0, 0, source.width, source.height);
662
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
663
+ return canvas;
664
+ }
665
+ /**
666
+ * Encodes the canvas and verifies the result: a `null` blob is `encode-failed`, and bytes that are not the
667
+ * requested format (a browser silently falling back to PNG) are `format-unsupported` — never relabelled.
668
+ */
669
+ async function sdImageEditorEncode(canvas, format, quality) {
670
+ const lossy = format !== 'image/png';
671
+ let blob;
672
+ try {
673
+ blob = await new Promise(resolve => canvas.toBlob(resolve, format, lossy ? sdImageEditorClampQuality(quality) : undefined));
674
+ }
675
+ catch (error) {
676
+ throw new SdImageEditorFailure('encode-failed', error);
677
+ }
678
+ if (!blob || blob.size === 0)
679
+ throw new SdImageEditorFailure('encode-failed');
680
+ const actual = sdImageEditorSniffFormat(new Uint8Array(await blob.slice(0, 32).arrayBuffer()));
681
+ if (actual !== format)
682
+ throw new SdImageEditorFailure('format-unsupported', actual ?? blob.type);
683
+ // why: một số engine để trống `type` hoặc ghi khác chuẩn — gắn lại đúng MIME đã đọc từ byte thật.
684
+ return { blob: blob.type === format ? blob : blob.slice(0, blob.size, format), format };
685
+ }
686
+ /** Renders then encodes, always releasing the output canvas. */
687
+ async function sdImageEditorExport(doc, request) {
688
+ const canvas = sdImageEditorRender(doc, request);
689
+ try {
690
+ return await sdImageEditorEncode(canvas, request.format, request.quality);
691
+ }
692
+ finally {
693
+ sdImageEditorReleaseCanvas(canvas);
694
+ }
695
+ }
696
+ function sdImageEditorClampQuality(value) {
697
+ if (typeof value !== 'number' || !Number.isFinite(value))
698
+ return 0.92;
699
+ return Math.min(1, Math.max(0.01, value));
700
+ }
701
+ const supportCache = new WeakMap();
702
+ /**
703
+ * Output formats this browser really encodes, probed once per document with a 1 × 1 canvas. Safari, for example,
704
+ * returns PNG bytes when asked for WebP; such a format is reported as unsupported instead of being faked.
705
+ */
706
+ function sdImageEditorEncodableFormats(doc) {
707
+ let cached = supportCache.get(doc);
708
+ if (!cached) {
709
+ cached = probeFormats(doc);
710
+ supportCache.set(doc, cached);
711
+ }
712
+ return cached;
713
+ }
714
+ async function probeFormats(doc) {
715
+ const supported = new Set();
716
+ const canvas = doc.createElement('canvas');
717
+ canvas.width = 1;
718
+ canvas.height = 1;
719
+ if (!canvas.getContext('2d') || typeof canvas.toBlob !== 'function')
720
+ return supported;
721
+ try {
722
+ for (const format of SD_IMAGE_EDITOR_EDITABLE_FORMATS) {
723
+ try {
724
+ await sdImageEditorEncode(canvas, format, 0.9);
725
+ supported.add(format);
726
+ }
727
+ catch {
728
+ // not encodable here
729
+ }
730
+ }
731
+ }
732
+ finally {
733
+ sdImageEditorReleaseCanvas(canvas);
734
+ }
735
+ return supported;
736
+ }
737
+ /**
738
+ * Draws a downscaled copy of the source (at most `maxPixels`) into `canvas` for the on-screen preview. Returns the
739
+ * preview size. Interaction runs on this copy; the export always reads the full source.
740
+ */
741
+ function sdImageEditorDrawPreview(canvas, source, maxPixels) {
742
+ const scale = Math.min(1, Math.sqrt(maxPixels / (source.width * source.height)));
743
+ const width = Math.max(1, Math.round(source.width * scale));
744
+ const height = Math.max(1, Math.round(source.height * scale));
745
+ canvas.width = width;
746
+ canvas.height = height;
747
+ const ctx = canvas.getContext('2d');
748
+ if (!ctx)
749
+ throw new SdImageEditorFailure('render-failed', { width, height });
750
+ ctx.clearRect(0, 0, width, height);
751
+ ctx.imageSmoothingEnabled = true;
752
+ ctx.imageSmoothingQuality = 'high';
753
+ ctx.drawImage(source.image, 0, 0, width, height);
754
+ return { width, height };
755
+ }
756
+ /**
757
+ * `true` when the canvas holds at least one pixel that is not fully opaque. Used once per load on the preview copy,
758
+ * only when the header declares an alpha channel — encoders often write RGBA even for opaque images.
759
+ */
760
+ function sdImageEditorHasTransparency(canvas) {
761
+ const ctx = canvas.getContext('2d');
762
+ if (!ctx || !canvas.width || !canvas.height)
763
+ return false;
764
+ const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
765
+ for (let i = 3; i < data.length; i += 4) {
766
+ if (data[i] < 255)
767
+ return true;
768
+ }
769
+ return false;
770
+ }
771
+ const EXTENSIONS = {
772
+ 'image/jpeg': 'jpg',
773
+ 'image/png': 'png',
774
+ 'image/webp': 'webp',
775
+ };
776
+ const IMAGE_EXTENSION = /\.(?:jpe?g|jfif|png|apng|webp|gif|bmp|heic|heif|avif|tiff?|svg)$/i;
777
+ function sdImageEditorExtension(format) {
778
+ return EXTENSIONS[format];
779
+ }
780
+ /** `base` without its image extension, plus the extension of `format`. */
781
+ function sdImageEditorFileName(base, format) {
782
+ const stem = (base ?? '').trim().replace(IMAGE_EXTENSION, '').trim() || 'image';
783
+ return `${stem}.${EXTENSIONS[format]}`;
784
+ }
785
+ /** `1.2 MB`, `245 KB`, `830 B` in the given locale. */
786
+ function sdImageEditorFormatBytes(bytes, locale) {
787
+ const units = ['B', 'KB', 'MB', 'GB'];
788
+ let value = Math.max(0, bytes);
789
+ let unit = 0;
790
+ while (value >= 1024 && unit < units.length - 1) {
791
+ value /= 1024;
792
+ unit++;
793
+ }
794
+ const digits = unit === 0 || value >= 100 ? 0 : 1;
795
+ let text;
796
+ try {
797
+ text = new Intl.NumberFormat(locale, { maximumFractionDigits: digits }).format(value);
798
+ }
799
+ catch {
800
+ text = value.toFixed(digits);
801
+ }
802
+ return `${text} ${units[unit]}`;
803
+ }
804
+ /**
805
+ * Normalises a CSS colour to `#rrggbb` for `<input type="color">`, using the canvas colour parser. Returns `null`
806
+ * for an invalid colour.
807
+ */
808
+ function sdImageEditorColorToHex(doc, color) {
809
+ const ctx = doc.createElement('canvas').getContext('2d');
810
+ if (!ctx)
811
+ return null;
812
+ ctx.fillStyle = 'black';
813
+ ctx.fillStyle = color;
814
+ const first = String(ctx.fillStyle);
815
+ ctx.fillStyle = 'white';
816
+ ctx.fillStyle = color;
817
+ // why: màu không hợp lệ bị bỏ qua nên fillStyle giữ giá trị trước — hai lần gán khác nhau cho ra hai kết quả khác nhau.
818
+ if (String(ctx.fillStyle) !== first)
819
+ return null;
820
+ return /^#[0-9a-f]{6}$/i.test(first) ? first.toLowerCase() : null;
821
+ }
822
+
823
+ function sdImageEditorInitialEdits(source, aspectRatio) {
824
+ return { flip: false, rotate: 0, crop: sdImageEditorInitialCrop(source, aspectRatio), aspectRatio, resize: null };
825
+ }
826
+ /** Oriented image size for these edits. */
827
+ function sdImageEditorBounds(edits, source) {
828
+ return sdImageEditorOrientedSize(source, edits.rotate);
829
+ }
830
+ /**
831
+ * Applies a rotate/flip button. The crop follows the content; a quarter turn with a fixed ratio re-shapes the
832
+ * crop to that ratio around the same centre, and swaps a typed output size.
833
+ */
834
+ function sdImageEditorOperate(edits, op, source, rules) {
835
+ const before = sdImageEditorBounds(edits, source);
836
+ const orientation = sdImageEditorApplyOperation(edits, op);
837
+ const after = sdImageEditorOrientedSize(source, orientation.rotate);
838
+ const quarter = op === 'rotate-cw' || op === 'rotate-ccw';
839
+ let crop = sdImageEditorClampRect(sdImageEditorTransformRect(edits.crop, sdImageEditorOperationMatrix(op, before)), after);
840
+ if (quarter && edits.aspectRatio)
841
+ crop = sdImageEditorReshape(crop, edits.aspectRatio, after);
842
+ let resize = edits.resize;
843
+ if (quarter && resize)
844
+ resize = { width: resize.height, height: resize.width };
845
+ return { ...edits, ...orientation, crop, resize: sdImageEditorFitResize(resize, edits.crop, crop, rules) };
846
+ }
847
+ /** Replaces the crop (drag, keyboard or typed values). The rectangle is clamped inside the image. */
848
+ function sdImageEditorSetCrop(edits, crop, source, rules) {
849
+ const next = sdImageEditorClampRect(crop, sdImageEditorBounds(edits, source));
850
+ if (sdImageEditorSameRect(next, edits.crop))
851
+ return edits;
852
+ return { ...edits, crop: next, resize: sdImageEditorFitResize(edits.resize, edits.crop, next, rules) };
853
+ }
854
+ /** Selects a crop ratio. The crop keeps its centre and area; `null` keeps the current crop and frees it. */
855
+ function sdImageEditorSetAspectRatio(edits, ratio, source, rules) {
856
+ const value = ratio && Number.isFinite(ratio) && ratio > 0 ? ratio : null;
857
+ if (value === edits.aspectRatio)
858
+ return edits;
859
+ if (!value)
860
+ return { ...edits, aspectRatio: null };
861
+ const crop = sdImageEditorReshape(edits.crop, value, sdImageEditorBounds(edits, source));
862
+ return { ...edits, aspectRatio: value, crop, resize: sdImageEditorFitResize(edits.resize, edits.crop, crop, rules) };
863
+ }
864
+ /**
865
+ * "Keep ratio" on or off without moving the crop: on locks the current crop shape (`width / height`), off frees it.
866
+ */
867
+ function sdImageEditorKeepRatio(edits, keep) {
868
+ if (keep === (edits.aspectRatio !== null))
869
+ return edits;
870
+ return { ...edits, aspectRatio: keep ? edits.crop.width / edits.crop.height : null };
871
+ }
872
+ /**
873
+ * Sets the output width (`null` follows the crop again). The height always follows the crop ratio, and the size is
874
+ * clamped to the rules. To start from a height, convert it with `height × crop ratio` first.
875
+ */
876
+ function sdImageEditorSetResize(edits, size, rules) {
877
+ const resize = size ? sdImageEditorClampResize(size, edits.crop, rules).size : null;
878
+ if (resize === edits.resize || (resize && edits.resize && sameSize(resize, edits.resize)))
879
+ return edits;
880
+ return { ...edits, resize };
881
+ }
882
+ /**
883
+ * Output size: the typed size when there is one, otherwise the crop scaled into the default box, never above the
884
+ * crop unless upscaling is allowed, and always inside the output limits.
885
+ */
886
+ function sdImageEditorOutputSize(edits, rules) {
887
+ if (edits.resize)
888
+ return { ...edits.resize, limited: false };
889
+ const { width: cw, height: ch } = edits.crop;
890
+ let scale = 1;
891
+ const boxScale = Math.min(rules.targetWidth ? rules.targetWidth / cw : Infinity, rules.targetHeight ? rules.targetHeight / ch : Infinity);
892
+ if (Number.isFinite(boxScale))
893
+ scale = rules.allowUpscale ? boxScale : Math.min(1, boxScale);
894
+ const limitScale = sdImageEditorLimitScale(cw * scale, ch * scale, rules);
895
+ const limited = limitScale < 1;
896
+ scale *= limitScale;
897
+ return { ...roundSize(cw * scale, ch * scale, rules), limited };
898
+ }
899
+ /**
900
+ * Clamps a typed size: the height is derived from the width and the crop ratio, never above the crop unless
901
+ * upscaling is allowed, and always inside the output limits.
902
+ */
903
+ function sdImageEditorClampResize(size, crop, rules) {
904
+ const ratio = crop.width / crop.height;
905
+ let width = positive$1(size.width) ?? crop.width;
906
+ let height = width / ratio;
907
+ let limited = false;
908
+ if (!rules.allowUpscale && width > crop.width) {
909
+ width = crop.width;
910
+ height = crop.height;
911
+ limited = true;
912
+ }
913
+ const limitScale = sdImageEditorLimitScale(width, height, rules);
914
+ if (limitScale < 1) {
915
+ width *= limitScale;
916
+ height *= limitScale;
917
+ limited = true;
918
+ }
919
+ return { size: roundSize(width, height, rules), limited };
920
+ }
921
+ /** Largest scale (≤ 1) that keeps `width × height` inside the output limits. */
922
+ function sdImageEditorLimitScale(width, height, rules) {
923
+ let scale = 1;
924
+ const side = Math.max(width, height);
925
+ if (side > rules.maxSide)
926
+ scale = Math.min(scale, rules.maxSide / side);
927
+ const pixels = width * height;
928
+ if (pixels > rules.maxPixels)
929
+ scale = Math.min(scale, Math.sqrt(rules.maxPixels / pixels));
930
+ return scale;
931
+ }
932
+ /** Keeps a typed size meaningful after the crop changed. */
933
+ function sdImageEditorFitResize(resize, previousCrop, crop, rules) {
934
+ if (!resize)
935
+ return null;
936
+ if (sdImageEditorSameRect(previousCrop, crop))
937
+ return resize;
938
+ return sdImageEditorClampResize(resize, crop, rules).size;
939
+ }
940
+ function roundSize(width, height, rules) {
941
+ // why: làm tròn có thể đẩy vượt giới hạn 1px (ví dụ 4096.5 → 4097) — co lại bằng floor khi đó.
942
+ let w = Math.max(1, Math.round(width));
943
+ let h = Math.max(1, Math.round(height));
944
+ if (w * h > rules.maxPixels || Math.max(w, h) > rules.maxSide) {
945
+ w = Math.max(1, Math.floor(width));
946
+ h = Math.max(1, Math.floor(height));
947
+ }
948
+ return { width: w, height: h };
949
+ }
950
+ function positive$1(value) {
951
+ return Number.isFinite(value) && value >= 1 ? value : null;
952
+ }
953
+ function sameSize(a, b) {
954
+ return a.width === b.width && a.height === b.height;
955
+ }
956
+ function sdImageEditorSameEdits(a, b) {
957
+ return (a.flip === b.flip &&
958
+ a.rotate === b.rotate &&
959
+ a.aspectRatio === b.aspectRatio &&
960
+ sdImageEditorSameRect(a.crop, b.crop) &&
961
+ (a.resize === b.resize || (!!a.resize && !!b.resize && sameSize(a.resize, b.resize))));
962
+ }
963
+ /** Ratio that exactly fits the given size — used to format ratio chips. */
964
+ function sdImageEditorRatioLabel(ratio) {
965
+ const common = [
966
+ [1, 1],
967
+ [4, 3],
968
+ [3, 4],
969
+ [16, 9],
970
+ [9, 16],
971
+ [3, 2],
972
+ [2, 3],
973
+ [5, 4],
974
+ [4, 5],
975
+ [21, 9],
976
+ ];
977
+ const match = common.find(([w, h]) => Math.abs(w / h - ratio) < 1e-6);
978
+ if (match)
979
+ return `${match[0]}:${match[1]}`;
980
+ return `${Number(ratio.toFixed(2))}:1`;
981
+ }
982
+ function sdImageEditorHistoryStart(present) {
983
+ return { past: [], present, future: [] };
984
+ }
985
+ /** Records `next` as a new step. A value equal to `present` records nothing; the redo branch is dropped. */
986
+ function sdImageEditorHistoryCommit(history, next, limit, same) {
987
+ if (same(history.present, next))
988
+ return history;
989
+ const keep = Math.max(1, Math.floor(limit));
990
+ const past = [...history.past, history.present];
991
+ return { past: past.length > keep ? past.slice(past.length - keep) : past, present: next, future: [] };
992
+ }
993
+ function sdImageEditorHistoryUndo(history) {
994
+ if (!history.past.length)
995
+ return history;
996
+ const present = history.past[history.past.length - 1];
997
+ return { past: history.past.slice(0, -1), present, future: [history.present, ...history.future] };
998
+ }
999
+ function sdImageEditorHistoryRedo(history) {
1000
+ if (!history.future.length)
1001
+ return history;
1002
+ const [present, ...future] = history.future;
1003
+ return { past: [...history.past, history.present], present, future };
1004
+ }
1005
+
1006
+ const DEFAULT_RATIOS = [
1007
+ { value: null },
1008
+ { value: 1 },
1009
+ { value: 4 / 3 },
1010
+ { value: 16 / 9 },
1011
+ { value: 3 / 4 },
1012
+ ];
1013
+ const DEFAULT_LIMITS = {
1014
+ maxSourceSize: 40 * 1024 * 1024,
1015
+ maxSourcePixels: 40_000_000,
1016
+ maxOutputPixels: 16_777_216,
1017
+ maxOutputSide: 16_384,
1018
+ };
1019
+ const DEFAULT_HISTORY_LIMIT = 50;
1020
+ const DEFAULT_QUALITY = 0.92;
1021
+ /** The on-screen copy is downscaled to this many pixels; the export always reads the full source. */
1022
+ const PREVIEW_MAX_PIXELS = 4_000_000;
1023
+ /** Pause after the last edit before the output is encoded to measure its real size. */
1024
+ const ESTIMATE_DELAY_MS = 500;
1025
+ /** Above this output size the real size is only measured on Apply, to keep editing responsive. */
1026
+ const ESTIMATE_MAX_PIXELS = 24_000_000;
1027
+ const STAGE_PADDING = 24;
1028
+ const PAN_MARGIN = 48;
1029
+ const ZOOM_STEP = 1.25;
1030
+ /** Highest preview zoom, in CSS pixels per image pixel. */
1031
+ const MAX_SCALE = 8;
1032
+ /** Lowest zoom, relative to "fit". */
1033
+ const MIN_ZOOM = 0.5;
1034
+ /** Smallest crop the pointer can drag, in CSS pixels, so the handles stay usable. */
1035
+ const MIN_CROP_CSS = 24;
1036
+ /** Keyboard nudges closer than this are merged into one undo step. */
1037
+ const KEY_COALESCE_MS = 800;
1038
+ const COMPACT_MAX_WIDTH = 720;
1039
+ const FORMAT_LABELS = { 'image/jpeg': 'JPEG', 'image/png': 'PNG', 'image/webp': 'WebP' };
1040
+ const HANDLES = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'];
1041
+ let nextEditorId = 0;
1042
+ /**
1043
+ * Inline image editor: crop (free or fixed ratio), quarter-turn rotation, flips, resize, zoom/pan, undo/redo/reset and
1044
+ * the choice of output format and quality. It only edits: the consumer owns the Apply/Cancel buttons and asks for
1045
+ * the result with `getResult()`, `getFile()` or `getBlob()`. It never uploads or saves anything.
1046
+ *
1047
+ * Works inline or inside `sd-modal` / `sd-side-drawer` without extra setup. Pass a `File` or `Blob`: images behind
1048
+ * authentication or presigned URLs are fetched by the consumer first.
1049
+ *
1050
+ * Independent of `sd-upload-file` and `sd-file-explorer` (neither imports it): open it from their keys or `(open)`
1051
+ * event, then upload the result as a new file so the original is never overwritten (see `sd-image-editor.md`).
1052
+ *
1053
+ * @example
1054
+ * ```html
1055
+ * <sd-image-editor #editor [source]="file" [option]="{ aspectRatio: 1, lockAspectRatio: true, output: { width: 512 } }" />
1056
+ * <sd-button type="fill" color="primary" title="Save" [disabled]="editor.status() !== 'ready'" (click)="save(editor)" />
1057
+ * ```
1058
+ * ```ts
1059
+ * async save(editor: SdImageEditor): Promise<void> {
1060
+ * const file = await editor.getFile(); // 512 × 512, extension matching the real format
1061
+ * await this.api.uploadAvatar(file);
1062
+ * }
1063
+ * ```
1064
+ */
1065
+ class SdImageEditor {
1066
+ #i18n = inject(I18nService);
1067
+ #document = inject(DOCUMENT);
1068
+ #host = inject(ElementRef);
1069
+ #injector = inject(Injector);
1070
+ #zone = inject(NgZone);
1071
+ #browser = isPlatformBrowser(inject(PLATFORM_ID));
1072
+ /**
1073
+ * Image to edit: a `File` or `Blob` holding a still JPEG, PNG or WebP. The editor reads it and never modifies,
1074
+ * revokes or re-uploads it. Changing the value discards the current edits; `null` shows the empty state.
1075
+ */
1076
+ source = input(null, ...(ngDevMode ? [{ debugName: "source" }] : []));
1077
+ /** Ratios, output format/size and limits. See `SdImageEditorOption`. */
1078
+ option = input(undefined, ...(ngDevMode ? [{ debugName: "option" }] : []));
1079
+ /**
1080
+ * Emitted when the source cannot be loaded (unsupported, animated, too large, corrupt…), with `stage: 'load'`. The
1081
+ * same message is shown in the editor. Export failures reject the promise of `getResult()` instead.
1082
+ */
1083
+ failed = output();
1084
+ // ---- State ----
1085
+ #loadState = signal('empty', ...(ngDevMode ? [{ debugName: "#loadState" }] : []));
1086
+ #loaded = signal(null, ...(ngDevMode ? [{ debugName: "#loaded" }] : []));
1087
+ #history = signal(null, ...(ngDevMode ? [{ debugName: "#history" }] : []));
1088
+ /** Edits while a drag is in progress; committed to the history on pointer up. */
1089
+ #draft = signal(null, ...(ngDevMode ? [{ debugName: "#draft" }] : []));
1090
+ #stageSize = signal({ width: 0, height: 0 }, ...(ngDevMode ? [{ debugName: "#stageSize" }] : []));
1091
+ #hostWidth = signal(0, ...(ngDevMode ? [{ debugName: "#hostWidth" }] : []));
1092
+ #encodable = signal(null, ...(ngDevMode ? [{ debugName: "#encodable" }] : []));
1093
+ #exporting = signal(false, ...(ngDevMode ? [{ debugName: "#exporting" }] : []));
1094
+ #loadError = signal(null, ...(ngDevMode ? [{ debugName: "#loadError" }] : []));
1095
+ #estimate = signal(null, ...(ngDevMode ? [{ debugName: "#estimate" }] : []));
1096
+ view = signal(SD_IMAGE_EDITOR_FIT_VIEW, ...(ngDevMode ? [{ debugName: "view" }] : []));
1097
+ // why: kiểu khai báo tường minh bằng alias — union literal tự suy ra được in vào d.ts theo thứ tự nội bộ của
1098
+ // TypeScript, thứ tự này đổi theo máy build (xem file-explorer shareFeedback).
1099
+ dragging = signal(null, ...(ngDevMode ? [{ debugName: "dragging" }] : []));
1100
+ format = signal('image/png', ...(ngDevMode ? [{ debugName: "format" }] : []));
1101
+ quality = signal(DEFAULT_QUALITY, ...(ngDevMode ? [{ debugName: "quality" }] : []));
1102
+ background = signal('white', ...(ngDevMode ? [{ debugName: "background" }] : []));
1103
+ exportError = signal(null, ...(ngDevMode ? [{ debugName: "exportError" }] : []));
1104
+ /** Shown under the size fields when a typed size had to be reduced. */
1105
+ resizeNotice = signal('', ...(ngDevMode ? [{ debugName: "resizeNotice" }] : []));
1106
+ stage = viewChild('stage', ...(ngDevMode ? [{ debugName: "stage" }] : []));
1107
+ previewCanvas = viewChild('previewCanvas', ...(ngDevMode ? [{ debugName: "previewCanvas" }] : []));
1108
+ cropBox = viewChild('cropBox', ...(ngDevMode ? [{ debugName: "cropBox" }] : []));
1109
+ // ---- Non-reactive bookkeeping ----
1110
+ #loadSeq = 0;
1111
+ #drag = null;
1112
+ #estimateTimer = null;
1113
+ #estimating = false;
1114
+ #estimateQueued = false;
1115
+ /** Last encoded output, reused by Apply when nothing changed since. */
1116
+ #encoded = null;
1117
+ #coalesce = null;
1118
+ /** Export in progress, shared by concurrent `getResult()` calls. */
1119
+ #pendingResult = null;
1120
+ #resizeObserver = null;
1121
+ #destroyed = false;
1122
+ instanceId = `sd-image-editor-${nextEditorId++}`;
1123
+ handles = HANDLES;
1124
+ // ---- Public read-only state ----
1125
+ /** Current lifecycle state. See `SdImageEditorStatus`. */
1126
+ status = computed(() => {
1127
+ const state = this.#loadState();
1128
+ return state === 'ready' && this.#exporting() ? 'exporting' : state;
1129
+ }, ...(ngDevMode ? [{ debugName: "status" }] : []));
1130
+ /** Current edits (including a drag in progress), or `null` while no image is loaded. */
1131
+ edits = computed(() => this.#draft() ?? this.#history()?.present ?? null, ...(ngDevMode ? [{ debugName: "edits" }] : []));
1132
+ /** Facts about the loaded source, or `null`. */
1133
+ sourceInfo = computed(() => this.#loaded()?.info ?? null, ...(ngDevMode ? [{ debugName: "sourceInfo" }] : []));
1134
+ /** Last load or export error, or `null`. */
1135
+ error = computed(() => this.#loadError() ?? this.exportError(), ...(ngDevMode ? [{ debugName: "error" }] : []));
1136
+ canUndo = computed(() => this.#interactive() && !!this.#history()?.past.length, ...(ngDevMode ? [{ debugName: "canUndo" }] : []));
1137
+ canRedo = computed(() => this.#interactive() && !!this.#history()?.future.length, ...(ngDevMode ? [{ debugName: "canRedo" }] : []));
1138
+ /** The edits differ from the freshly loaded image. */
1139
+ dirty = computed(() => {
1140
+ const edits = this.edits();
1141
+ const loaded = this.#loaded();
1142
+ return !!edits && !!loaded && !sdImageEditorSameEdits(edits, loaded.initial);
1143
+ }, ...(ngDevMode ? [{ debugName: "dirty" }] : []));
1144
+ autoId = computed(() => {
1145
+ const scope = this.option()?.autoId;
1146
+ return scope ? `components-image-editor-${scope}` : undefined;
1147
+ }, ...(ngDevMode ? [{ debugName: "autoId" }] : []));
1148
+ // ---- Derived configuration ----
1149
+ #limits = computed(() => {
1150
+ const limits = this.option()?.limits ?? {};
1151
+ return {
1152
+ maxSourceSize: positive(limits.maxSourceSize) ?? DEFAULT_LIMITS.maxSourceSize,
1153
+ maxSourcePixels: positive(limits.maxSourcePixels) ?? DEFAULT_LIMITS.maxSourcePixels,
1154
+ maxOutputPixels: positive(limits.maxOutputPixels) ?? DEFAULT_LIMITS.maxOutputPixels,
1155
+ maxOutputSide: positive(limits.maxOutputSide) ?? DEFAULT_LIMITS.maxOutputSide,
1156
+ };
1157
+ }, ...(ngDevMode ? [{ debugName: "#limits" }] : []));
1158
+ #rules = computed(() => {
1159
+ const output = this.option()?.output ?? {};
1160
+ const limits = this.#limits();
1161
+ return {
1162
+ targetWidth: positive(output.width),
1163
+ targetHeight: positive(output.height),
1164
+ allowUpscale: !!output.allowUpscale,
1165
+ maxPixels: limits.maxOutputPixels,
1166
+ maxSide: limits.maxOutputSide,
1167
+ };
1168
+ }, ...(ngDevMode ? [{ debugName: "#rules" }] : []));
1169
+ #historyLimit = computed(() => positive(this.option()?.historyLimit) ?? DEFAULT_HISTORY_LIMIT, ...(ngDevMode ? [{ debugName: "#historyLimit" }] : []));
1170
+ #interactive = computed(() => this.#loadState() === 'ready' && !this.#exporting(), ...(ngDevMode ? [{ debugName: "#interactive" }] : []));
1171
+ interactive = this.#interactive;
1172
+ busy = computed(() => this.#exporting(), ...(ngDevMode ? [{ debugName: "busy" }] : []));
1173
+ compact = computed(() => {
1174
+ const width = this.#hostWidth();
1175
+ return width > 0 && width < COMPACT_MAX_WIDTH;
1176
+ }, ...(ngDevMode ? [{ debugName: "compact" }] : []));
1177
+ showRatios = computed(() => !this.option()?.lockAspectRatio, ...(ngDevMode ? [{ debugName: "showRatios" }] : []));
1178
+ /** "Keep ratio" is on: the crop keeps its shape while dragging, typing or rotating. */
1179
+ ratioLocked = computed(() => this.edits()?.aspectRatio != null, ...(ngDevMode ? [{ debugName: "ratioLocked" }] : []));
1180
+ /** The ratio is fixed by `option.lockAspectRatio`; the user cannot unlock it. */
1181
+ ratioFixed = computed(() => !!this.option()?.lockAspectRatio, ...(ngDevMode ? [{ debugName: "ratioFixed" }] : []));
1182
+ ratioText = computed(() => {
1183
+ const ratio = this.edits()?.aspectRatio;
1184
+ return ratio ? sdImageEditorRatioLabel(ratio) : '';
1185
+ }, ...(ngDevMode ? [{ debugName: "ratioText" }] : []));
1186
+ ratioChips = computed(() => {
1187
+ const list = this.option()?.aspectRatios;
1188
+ const ratios = list && list.length ? list : DEFAULT_RATIOS;
1189
+ return ratios.map((ratio, index) => {
1190
+ const value = positive(ratio.value ?? undefined) ?? null;
1191
+ const label = ratio.label || (value ? sdImageEditorRatioLabel(value) : this.#i18n.t('core.component.image-editor.ratio-free'));
1192
+ return { key: `${index}-${value ?? 'free'}`, label, value };
1193
+ });
1194
+ }, ...(ngDevMode ? [{ debugName: "ratioChips" }] : []));
1195
+ formatChoices = computed(() => {
1196
+ const encodable = this.#encodable();
1197
+ return this.#formats().map(format => {
1198
+ const disabled = !!encodable && !encodable.has(format);
1199
+ const label = disabled
1200
+ ? this.#i18n.t('core.component.image-editor.format-unsupported-option', { format: FORMAT_LABELS[format] })
1201
+ : FORMAT_LABELS[format];
1202
+ return { format, label, disabled };
1203
+ });
1204
+ }, ...(ngDevMode ? [{ debugName: "formatChoices" }] : []));
1205
+ showFormatPicker = computed(() => this.#formats().length > 1, ...(ngDevMode ? [{ debugName: "showFormatPicker" }] : []));
1206
+ lossy = computed(() => this.format() !== 'image/png', ...(ngDevMode ? [{ debugName: "lossy" }] : []));
1207
+ qualityPercent = computed(() => Math.round(this.quality() * 100), ...(ngDevMode ? [{ debugName: "qualityPercent" }] : []));
1208
+ showBackground = computed(() => this.format() === 'image/jpeg' && !!this.sourceInfo()?.hasAlpha, ...(ngDevMode ? [{ debugName: "showBackground" }] : []));
1209
+ backgroundHex = computed(() => (this.#browser ? sdImageEditorColorToHex(this.#document, this.background()) : null) ?? '', ...(ngDevMode ? [{ debugName: "backgroundHex" }] : []));
1210
+ formatLabel = computed(() => FORMAT_LABELS[this.format()], ...(ngDevMode ? [{ debugName: "formatLabel" }] : []));
1211
+ formatUnsupported = computed(() => {
1212
+ const encodable = this.#encodable();
1213
+ return !!encodable && !encodable.has(this.format());
1214
+ }, ...(ngDevMode ? [{ debugName: "formatUnsupported" }] : []));
1215
+ #formats = computed(() => {
1216
+ const list = (this.option()?.output?.formats ?? []).filter(sdImageEditorIsEditableFormat);
1217
+ return list.length ? [...new Set(list)] : SD_IMAGE_EDITOR_EDITABLE_FORMATS;
1218
+ }, ...(ngDevMode ? [{ debugName: "#formats" }] : []));
1219
+ // ---- Geometry ----
1220
+ #bounds = computed(() => {
1221
+ const edits = this.edits();
1222
+ const loaded = this.#loaded();
1223
+ return edits && loaded ? sdImageEditorBounds(edits, loaded.size) : null;
1224
+ }, ...(ngDevMode ? [{ debugName: "#bounds" }] : []));
1225
+ #viewport = computed(() => {
1226
+ const bounds = this.#bounds();
1227
+ return bounds ? sdImageEditorViewport(this.#stageSize(), bounds, this.view(), STAGE_PADDING) : null;
1228
+ }, ...(ngDevMode ? [{ debugName: "#viewport" }] : []));
1229
+ #maxZoom = computed(() => {
1230
+ const bounds = this.#bounds();
1231
+ if (!bounds)
1232
+ return 1;
1233
+ return Math.max(1, MAX_SCALE / sdImageEditorFitScale(this.#stageSize(), bounds, STAGE_PADDING));
1234
+ }, ...(ngDevMode ? [{ debugName: "#maxZoom" }] : []));
1235
+ #previewSize = signal({ width: 1, height: 1 }, ...(ngDevMode ? [{ debugName: "#previewSize" }] : []));
1236
+ /** CSS transform of the preview canvas: preview pixels → source pixels → oriented image → stage. */
1237
+ previewTransform = computed(() => {
1238
+ const viewport = this.#viewport();
1239
+ const edits = this.edits();
1240
+ const loaded = this.#loaded();
1241
+ if (!viewport || !edits || !loaded)
1242
+ return 'none';
1243
+ const preview = this.#previewSize();
1244
+ const m = sdImageEditorCompose(sdImageEditorViewMatrix(viewport), sdImageEditorOrientationMatrix(loaded.size, edits), sdImageEditorScale(loaded.size.width / preview.width, loaded.size.height / preview.height));
1245
+ return `matrix(${m.map(value => round(value, 6)).join(', ')})`;
1246
+ }, ...(ngDevMode ? [{ debugName: "previewTransform" }] : []));
1247
+ previewSize = this.#previewSize.asReadonly();
1248
+ imageBox = computed(() => {
1249
+ const viewport = this.#viewport();
1250
+ const bounds = this.#bounds();
1251
+ return viewport && bounds ? sdImageEditorImageToStage(viewport, { x: 0, y: 0, ...bounds }) : null;
1252
+ }, ...(ngDevMode ? [{ debugName: "imageBox" }] : []));
1253
+ cropStyle = computed(() => {
1254
+ const viewport = this.#viewport();
1255
+ const edits = this.edits();
1256
+ return viewport && edits ? sdImageEditorImageToStage(viewport, edits.crop) : null;
1257
+ }, ...(ngDevMode ? [{ debugName: "cropStyle" }] : []));
1258
+ zoomPercent = computed(() => Math.round((this.#viewport()?.scale ?? 1) * 100), ...(ngDevMode ? [{ debugName: "zoomPercent" }] : []));
1259
+ canZoomIn = computed(() => this.#interactive() && this.view().zoom < this.#maxZoom() - 1e-6, ...(ngDevMode ? [{ debugName: "canZoomIn" }] : []));
1260
+ canZoomOut = computed(() => this.#interactive() && this.view().zoom > MIN_ZOOM + 1e-6, ...(ngDevMode ? [{ debugName: "canZoomOut" }] : []));
1261
+ isFit = computed(() => {
1262
+ const view = this.view();
1263
+ return view.zoom === 1 && view.panX === 0 && view.panY === 0;
1264
+ }, ...(ngDevMode ? [{ debugName: "isFit" }] : []));
1265
+ cropLimits = computed(() => {
1266
+ const bounds = this.#bounds();
1267
+ const crop = this.edits()?.crop;
1268
+ if (!bounds || !crop)
1269
+ return null;
1270
+ return { maxX: bounds.width - crop.width, maxY: bounds.height - crop.height, maxWidth: bounds.width, maxHeight: bounds.height };
1271
+ }, ...(ngDevMode ? [{ debugName: "cropLimits" }] : []));
1272
+ cropLabel = computed(() => {
1273
+ const crop = this.edits()?.crop;
1274
+ if (!crop)
1275
+ return '';
1276
+ return this.#i18n.t('core.component.image-editor.crop-area', { x: crop.x, y: crop.y, width: crop.width, height: crop.height });
1277
+ }, ...(ngDevMode ? [{ debugName: "cropLabel" }] : []));
1278
+ // ---- Output ----
1279
+ #outputSize = computed(() => {
1280
+ const edits = this.edits();
1281
+ return edits ? sdImageEditorOutputSize(edits, this.#rules()) : null;
1282
+ }, ...(ngDevMode ? [{ debugName: "#outputSize" }] : []));
1283
+ outputSize = this.#outputSize;
1284
+ /** Largest size the user may type for the current crop (no upscaling unless allowed). */
1285
+ resizeMax = computed(() => {
1286
+ const edits = this.edits();
1287
+ if (!edits)
1288
+ return null;
1289
+ const huge = 1e9;
1290
+ return sdImageEditorClampResize({ width: huge, height: huge }, edits.crop, this.#rules()).size;
1291
+ }, ...(ngDevMode ? [{ debugName: "resizeMax" }] : []));
1292
+ /** Key of the committed output; `null` during a drag so nothing is encoded mid-gesture. */
1293
+ #outputKey = computed(() => {
1294
+ const loaded = this.#loaded();
1295
+ const edits = this.#history()?.present;
1296
+ const size = this.#outputSize();
1297
+ if (!loaded || !edits || !size || this.#draft() || this.#loadState() !== 'ready')
1298
+ return null;
1299
+ const format = this.format();
1300
+ return JSON.stringify({
1301
+ seq: loaded.seq,
1302
+ edits,
1303
+ size: [size.width, size.height],
1304
+ format,
1305
+ quality: format === 'image/png' ? null : sdImageEditorClampQuality(this.quality()),
1306
+ background: format === 'image/jpeg' ? this.background() : null,
1307
+ });
1308
+ }, ...(ngDevMode ? [{ debugName: "#outputKey" }] : []));
1309
+ estimateLabel = computed(() => {
1310
+ const estimate = this.#estimate();
1311
+ const key = this.#outputKey();
1312
+ if (!estimate || !key || estimate.key !== key)
1313
+ return this.#i18n.t('core.component.image-editor.size-pending');
1314
+ switch (estimate.status) {
1315
+ case 'ready':
1316
+ return sdImageEditorFormatBytes(estimate.size ?? 0, this.#i18n.locale());
1317
+ case 'skipped':
1318
+ return this.#i18n.t('core.component.image-editor.size-on-apply');
1319
+ case 'error':
1320
+ return this.#i18n.t('core.component.image-editor.size-unavailable');
1321
+ default:
1322
+ return this.#i18n.t('core.component.image-editor.size-pending');
1323
+ }
1324
+ }, ...(ngDevMode ? [{ debugName: "estimateLabel" }] : []));
1325
+ sourceSummary = computed(() => {
1326
+ const info = this.sourceInfo();
1327
+ if (!info)
1328
+ return '';
1329
+ return `${info.width} × ${info.height} px · ${FORMAT_LABELS[info.mimeType]} · ${sdImageEditorFormatBytes(info.size, this.#i18n.locale())}`;
1330
+ }, ...(ngDevMode ? [{ debugName: "sourceSummary" }] : []));
1331
+ outputSummary = computed(() => {
1332
+ const size = this.#outputSize();
1333
+ return size ? `${size.width} × ${size.height} px · ${FORMAT_LABELS[this.format()]}` : '';
1334
+ }, ...(ngDevMode ? [{ debugName: "outputSummary" }] : []));
1335
+ statusMessage = computed(() => {
1336
+ if (this.#exporting())
1337
+ return this.#i18n.t('core.component.image-editor.exporting');
1338
+ return this.exportError()?.message ?? '';
1339
+ }, ...(ngDevMode ? [{ debugName: "statusMessage" }] : []));
1340
+ constructor() {
1341
+ effect(() => {
1342
+ const source = this.source();
1343
+ untracked(() => void this.#load(source ?? null));
1344
+ });
1345
+ effect(() => {
1346
+ const key = this.#outputKey();
1347
+ untracked(() => this.#scheduleEstimate(key));
1348
+ });
1349
+ afterNextRender(() => {
1350
+ const host = this.#host.nativeElement;
1351
+ this.#hostWidth.set(host.offsetWidth);
1352
+ this.#measureStage();
1353
+ if (typeof ResizeObserver === 'undefined')
1354
+ return;
1355
+ this.#resizeObserver = new ResizeObserver(() => {
1356
+ this.#hostWidth.set(host.offsetWidth);
1357
+ this.#measureStage();
1358
+ });
1359
+ this.#resizeObserver.observe(host);
1360
+ const stage = this.stage()?.nativeElement;
1361
+ if (stage)
1362
+ this.#resizeObserver.observe(stage);
1363
+ });
1364
+ inject(DestroyRef).onDestroy(() => this.#teardown());
1365
+ }
1366
+ // ---- Public API ----
1367
+ /** Steps back one edit. Zoom and pan are not part of the history. */
1368
+ undo() {
1369
+ const history = this.#history();
1370
+ if (!history || !this.canUndo())
1371
+ return;
1372
+ this.#coalesce = null;
1373
+ this.#history.set(sdImageEditorHistoryUndo(history));
1374
+ this.#afterHistoryChange();
1375
+ }
1376
+ redo() {
1377
+ const history = this.#history();
1378
+ if (!history || !this.canRedo())
1379
+ return;
1380
+ this.#coalesce = null;
1381
+ this.#history.set(sdImageEditorHistoryRedo(history));
1382
+ this.#afterHistoryChange();
1383
+ }
1384
+ /** Returns to the image as loaded (no crop, rotation, flip or resize). Undoable. */
1385
+ reset() {
1386
+ const loaded = this.#loaded();
1387
+ if (!loaded || !this.#interactive())
1388
+ return;
1389
+ this.#commit(loaded.initial);
1390
+ this.fitToView();
1391
+ }
1392
+ /** Shows the whole image again. Does not change the edits. */
1393
+ fitToView() {
1394
+ this.view.set(SD_IMAGE_EDITOR_FIT_VIEW);
1395
+ }
1396
+ /** Rotates by 90° as the toolbar buttons do. Undoable. */
1397
+ rotate(direction) {
1398
+ this.operate(direction === 'left' ? 'rotate-ccw' : 'rotate-cw');
1399
+ }
1400
+ /** Mirrors the image as shown, as the toolbar buttons do. Undoable. */
1401
+ flip(axis) {
1402
+ this.operate(axis === 'horizontal' ? 'flip-horizontal' : 'flip-vertical');
1403
+ }
1404
+ /**
1405
+ * Encodes the current edits from the full-resolution source and resolves with the image and its facts. Reuses the
1406
+ * encoding made for the size preview when nothing changed; concurrent calls share one encoding. While it runs,
1407
+ * `status()` is `'exporting'` and the controls are disabled.
1408
+ *
1409
+ * Rejects with an `SdImageEditorError`: `not-ready` when no image is loaded (or it was replaced meanwhile), or an
1410
+ * export code such as `format-unsupported`, `render-failed` or `encode-failed`.
1411
+ *
1412
+ * @example
1413
+ * ```ts
1414
+ * try {
1415
+ * const result = await this.editor().getResult();
1416
+ * await this.api.upload(result.blob, result.fileName);
1417
+ * } catch (error) {
1418
+ * this.notify.error((error as SdImageEditorError).message);
1419
+ * }
1420
+ * ```
1421
+ */
1422
+ getResult() {
1423
+ if (this.#pendingResult)
1424
+ return this.#pendingResult;
1425
+ const loaded = this.#loaded();
1426
+ const edits = this.#history()?.present;
1427
+ const size = this.#outputSize();
1428
+ if (!loaded || !edits || !size || this.#loadState() !== 'ready') {
1429
+ return Promise.reject(this.#toError(new SdImageEditorFailure('not-ready'), 'export'));
1430
+ }
1431
+ const pending = this.#export(loaded, edits, size).finally(() => {
1432
+ if (this.#pendingResult === pending)
1433
+ this.#pendingResult = null;
1434
+ });
1435
+ this.#pendingResult = pending;
1436
+ return pending;
1437
+ }
1438
+ /** `getResult()` then its `blob`. */
1439
+ async getBlob() {
1440
+ return (await this.getResult()).blob;
1441
+ }
1442
+ /**
1443
+ * `getResult()` as a `File`, whatever `output.resultType` says. `fileName` (without extension) overrides
1444
+ * `output.fileName`; the extension always matches the encoded format.
1445
+ *
1446
+ * @example
1447
+ * ```ts
1448
+ * const file = await this.editor().getFile('receipt-0042'); // receipt-0042.jpg
1449
+ * ```
1450
+ */
1451
+ async getFile(fileName) {
1452
+ const result = await this.getResult();
1453
+ if (!fileName && result.file)
1454
+ return result.file;
1455
+ const name = fileName ? sdImageEditorFileName(fileName, result.mimeType) : result.fileName;
1456
+ return new File([result.blob], name, { type: result.mimeType, lastModified: Date.now() });
1457
+ }
1458
+ // ---- Toolbar ----
1459
+ operate(op) {
1460
+ const edits = this.#history()?.present;
1461
+ const loaded = this.#loaded();
1462
+ if (!edits || !loaded || !this.#interactive())
1463
+ return;
1464
+ this.#commit(sdImageEditorOperate(edits, op, loaded.size, this.#rules()));
1465
+ // why: xoay 90° đổi khung ảnh — giữ mức zoom nhưng đưa ảnh về giữa để không "mất" ảnh ngoài vùng nhìn.
1466
+ this.view.update(view => ({ ...view, panX: 0, panY: 0 }));
1467
+ }
1468
+ zoomIn() {
1469
+ this.#zoomTo(this.view().zoom * ZOOM_STEP);
1470
+ }
1471
+ zoomOut() {
1472
+ this.#zoomTo(this.view().zoom / ZOOM_STEP);
1473
+ }
1474
+ // ---- Panel ----
1475
+ selectRatio(value) {
1476
+ const edits = this.#history()?.present;
1477
+ const loaded = this.#loaded();
1478
+ if (!edits || !loaded || !this.#interactive())
1479
+ return;
1480
+ this.#commit(sdImageEditorSetAspectRatio(edits, value, loaded.size, this.#rules()));
1481
+ }
1482
+ /** Commits a crop field on blur or Enter (not per keystroke, so typing "1280" never passes through "1"). */
1483
+ onCropField(field, input, control) {
1484
+ const edits = this.#history()?.present;
1485
+ const loaded = this.#loaded();
1486
+ if (!edits || !loaded || !this.#interactive())
1487
+ return;
1488
+ const value = typeof input === 'number' ? input : Number(input);
1489
+ if (input === null || input === undefined || input === '' || !Number.isFinite(value)) {
1490
+ control?.valueModel.set(edits.crop[field]);
1491
+ return;
1492
+ }
1493
+ const bounds = sdImageEditorBounds(edits, loaded.size);
1494
+ const ratio = edits.aspectRatio;
1495
+ let rect = { ...edits.crop, [field]: Math.round(value) };
1496
+ if (ratio && (field === 'width' || field === 'height')) {
1497
+ const width = field === 'width' ? rect.width : rect.height * ratio;
1498
+ const fitted = sdImageEditorFitRatio(Math.min(bounds.width, Math.max(1, width)), bounds.height, ratio);
1499
+ // why: giữ tâm vùng cắt khi đổi kích thước theo tỷ lệ — cảm giác giống kéo handle đối xứng.
1500
+ const cx = edits.crop.x + edits.crop.width / 2;
1501
+ const cy = edits.crop.y + edits.crop.height / 2;
1502
+ rect = { x: cx - fitted.width / 2, y: cy - fitted.height / 2, ...fitted };
1503
+ }
1504
+ const next = sdImageEditorSetCrop(edits, rect, loaded.size, this.#rules());
1505
+ this.#commit(next);
1506
+ control?.valueModel.set(next.crop[field]);
1507
+ }
1508
+ /** Output width or height, committed on blur or Enter. The other side always follows the crop ratio. */
1509
+ onResizeField(field, input, control) {
1510
+ const edits = this.#history()?.present;
1511
+ const current = this.#outputSize();
1512
+ if (!edits || !current || !this.#interactive())
1513
+ return;
1514
+ const value = typeof input === 'number' ? input : Number(input);
1515
+ if (input === null || input === undefined || input === '' || !Number.isFinite(value) || value < 1) {
1516
+ control?.valueModel.set(current[field]);
1517
+ return;
1518
+ }
1519
+ const ratio = edits.crop.width / edits.crop.height;
1520
+ const typed = Math.round(value);
1521
+ const width = field === 'width' ? typed : typed * ratio;
1522
+ const { size: clamped, limited } = sdImageEditorClampResize({ width, height: width / ratio }, edits.crop, this.#rules());
1523
+ this.#commit(sdImageEditorSetResize(edits, clamped, this.#rules()));
1524
+ this.resizeNotice.set(limited ? this.#i18n.t('core.component.image-editor.resize-limited', { width: clamped.width, height: clamped.height }) : '');
1525
+ control?.valueModel.set(clamped[field]);
1526
+ }
1527
+ /** "Keep ratio": on locks the current crop shape, off lets the crop be dragged freely. */
1528
+ toggleKeepRatio() {
1529
+ const edits = this.#history()?.present;
1530
+ if (!edits || !this.#interactive() || this.ratioFixed())
1531
+ return;
1532
+ this.#commit(sdImageEditorKeepRatio(edits, edits.aspectRatio === null));
1533
+ }
1534
+ /** Output follows the crop again. */
1535
+ resetResize() {
1536
+ const edits = this.#history()?.present;
1537
+ if (!edits || !this.#interactive())
1538
+ return;
1539
+ this.resizeNotice.set('');
1540
+ this.#commit(sdImageEditorSetResize(edits, null, this.#rules()));
1541
+ }
1542
+ onFormatChange(value) {
1543
+ if (typeof value !== 'string' || !sdImageEditorIsEditableFormat(value))
1544
+ return;
1545
+ this.format.set(value);
1546
+ this.exportError.set(null);
1547
+ }
1548
+ onQualityInput(value) {
1549
+ const percent = Number(value);
1550
+ if (Number.isFinite(percent))
1551
+ this.quality.set(sdImageEditorClampQuality(percent / 100));
1552
+ }
1553
+ onBackgroundInput(value) {
1554
+ if (value)
1555
+ this.background.set(value);
1556
+ }
1557
+ sameRatio(a, b) {
1558
+ return a === b || (a !== null && b !== null && Math.abs(a - b) < 1e-6);
1559
+ }
1560
+ // ---- Pointer ----
1561
+ onCropPointerDown(event, handle) {
1562
+ event.stopPropagation();
1563
+ this.#startDrag(event, handle ? 'resize' : 'move', handle);
1564
+ }
1565
+ onStagePointerDown(event) {
1566
+ this.#startDrag(event, 'pan', null);
1567
+ }
1568
+ onPointerMove(event) {
1569
+ const drag = this.#drag;
1570
+ const loaded = this.#loaded();
1571
+ if (!drag || !loaded || event.pointerId !== drag.pointerId)
1572
+ return;
1573
+ event.preventDefault();
1574
+ const dxCss = (event.clientX - drag.startX) / drag.visual;
1575
+ const dyCss = (event.clientY - drag.startY) / drag.visual;
1576
+ if (drag.mode === 'pan') {
1577
+ const bounds = sdImageEditorBounds(drag.edits, loaded.size);
1578
+ const next = { zoom: drag.view.zoom, panX: drag.view.panX + dxCss, panY: drag.view.panY + dyCss };
1579
+ this.view.set(sdImageEditorClampPan(this.#stageSize(), bounds, next, STAGE_PADDING, PAN_MARGIN));
1580
+ return;
1581
+ }
1582
+ const dx = dxCss / drag.scale;
1583
+ const dy = dyCss / drag.scale;
1584
+ const bounds = sdImageEditorBounds(drag.edits, loaded.size);
1585
+ const crop = drag.mode === 'move'
1586
+ ? sdImageEditorMoveRect(drag.edits.crop, dx, dy, bounds)
1587
+ : sdImageEditorResizeRect(drag.edits.crop, drag.handle ?? 'se', dx, dy, bounds, drag.edits.aspectRatio, Math.ceil(MIN_CROP_CSS / drag.scale));
1588
+ this.#draft.set(sdImageEditorSetCrop(drag.edits, crop, loaded.size, this.#rules()));
1589
+ }
1590
+ onPointerUp(event) {
1591
+ const drag = this.#drag;
1592
+ if (!drag || event.pointerId !== drag.pointerId)
1593
+ return;
1594
+ this.#endDrag(event.pointerId);
1595
+ const draft = this.#draft();
1596
+ this.#draft.set(null);
1597
+ if (draft)
1598
+ this.#commit(draft);
1599
+ }
1600
+ /** The browser took the pointer away (touch interrupted): drop the gesture instead of committing it. */
1601
+ onPointerCancel(event) {
1602
+ const drag = this.#drag;
1603
+ if (!drag || event.pointerId !== drag.pointerId)
1604
+ return;
1605
+ this.#endDrag(event.pointerId);
1606
+ this.#draft.set(null);
1607
+ if (drag.mode === 'pan')
1608
+ this.view.set(drag.view);
1609
+ }
1610
+ onWheel(event) {
1611
+ // why: chỉ zoom khi giữ Ctrl/⌘ (hoặc pinch trên touchpad, trình duyệt gắn ctrlKey) — cuộn thường vẫn cuộn trang.
1612
+ if (!this.#interactive() || !(event.ctrlKey || event.metaKey))
1613
+ return;
1614
+ event.preventDefault();
1615
+ const stage = this.stage()?.nativeElement;
1616
+ if (!stage)
1617
+ return;
1618
+ const rect = stage.getBoundingClientRect();
1619
+ const visual = this.#visualScale(stage);
1620
+ this.#zoomTo(this.view().zoom * Math.exp(-event.deltaY * 0.002), (event.clientX - rect.left) / visual, (event.clientY - rect.top) / visual);
1621
+ }
1622
+ // ---- Keyboard ----
1623
+ onKeydown(event) {
1624
+ if (event.defaultPrevented || !this.#interactive())
1625
+ return;
1626
+ const editable = isEditableTarget(event.target);
1627
+ const mod = event.ctrlKey || event.metaKey;
1628
+ const key = event.key.toLowerCase();
1629
+ if (mod && !event.altKey && (key === 'z' || key === 'y')) {
1630
+ // why: trong ô nhập số, Ctrl+Z phải là undo của chính ô đó — không cướp phím của trình duyệt.
1631
+ if (editable)
1632
+ return;
1633
+ event.preventDefault();
1634
+ if (key === 'y' || event.shiftKey)
1635
+ this.redo();
1636
+ else
1637
+ this.undo();
1638
+ return;
1639
+ }
1640
+ if (editable || mod || event.altKey)
1641
+ return;
1642
+ if (event.key === '+' || event.key === '=')
1643
+ this.zoomIn();
1644
+ else if (event.key === '-' || event.key === '_')
1645
+ this.zoomOut();
1646
+ else if (event.key === '0')
1647
+ this.fitToView();
1648
+ else
1649
+ return;
1650
+ event.preventDefault();
1651
+ }
1652
+ onCropKeydown(event) {
1653
+ const edits = this.#history()?.present;
1654
+ const loaded = this.#loaded();
1655
+ if (!edits || !loaded || !this.#interactive() || event.altKey)
1656
+ return;
1657
+ const step = event.shiftKey ? 10 : 1;
1658
+ let dx = 0;
1659
+ let dy = 0;
1660
+ if (event.key === 'ArrowLeft')
1661
+ dx = -step;
1662
+ else if (event.key === 'ArrowRight')
1663
+ dx = step;
1664
+ else if (event.key === 'ArrowUp')
1665
+ dy = -step;
1666
+ else if (event.key === 'ArrowDown')
1667
+ dy = step;
1668
+ else
1669
+ return;
1670
+ event.preventDefault();
1671
+ event.stopPropagation();
1672
+ const bounds = sdImageEditorBounds(edits, loaded.size);
1673
+ const resize = event.ctrlKey || event.metaKey;
1674
+ const crop = resize
1675
+ ? sdImageEditorResizeRect(edits.crop, 'se', dx, dy, bounds, edits.aspectRatio, 1)
1676
+ : sdImageEditorMoveRect(edits.crop, dx, dy, bounds);
1677
+ this.#commit(sdImageEditorSetCrop(edits, crop, loaded.size, this.#rules()), resize ? 'key-resize' : 'key-move');
1678
+ }
1679
+ // ---- Internals: loading ----
1680
+ async #load(source) {
1681
+ const seq = ++this.#loadSeq;
1682
+ this.#releaseSource();
1683
+ this.#loadError.set(null);
1684
+ this.exportError.set(null);
1685
+ this.resizeNotice.set('');
1686
+ this.view.set(SD_IMAGE_EDITOR_FIT_VIEW);
1687
+ if (!source || !this.#browser) {
1688
+ this.#loadState.set('empty');
1689
+ return;
1690
+ }
1691
+ this.#loadState.set('loading');
1692
+ try {
1693
+ if (typeof Blob === 'undefined' || !(source instanceof Blob))
1694
+ throw new SdImageEditorFailure('unsupported-format', typeof source);
1695
+ const [{ header, decoded }, encodable] = await Promise.all([
1696
+ sdImageEditorLoad(source, this.#limits(), this.#document),
1697
+ sdImageEditorEncodableFormats(this.#document),
1698
+ ]);
1699
+ if (seq !== this.#loadSeq || this.#destroyed) {
1700
+ decoded.release();
1701
+ return;
1702
+ }
1703
+ const size = { width: decoded.width, height: decoded.height };
1704
+ const info = {
1705
+ mimeType: header.format,
1706
+ width: size.width,
1707
+ height: size.height,
1708
+ size: source.size,
1709
+ hasAlpha: header.format !== 'image/jpeg' && header.hasAlpha,
1710
+ exifOrientation: header.orientation,
1711
+ };
1712
+ const option = this.option();
1713
+ const ratio = positive(option?.aspectRatio ?? undefined) ?? null;
1714
+ const initial = sdImageEditorInitialEdits(size, ratio);
1715
+ this.#encodable.set(encodable);
1716
+ this.#loaded.set({ seq, blob: source, decoded, info, size, initial });
1717
+ this.#history.set(sdImageEditorHistoryStart(initial));
1718
+ this.#applyOutputDefaults(info);
1719
+ this.#loadState.set('ready');
1720
+ this.#drawPreview(decoded);
1721
+ }
1722
+ catch (error) {
1723
+ if (seq !== this.#loadSeq || this.#destroyed)
1724
+ return;
1725
+ const failure = this.#toError(error, 'load');
1726
+ this.#loadError.set(failure);
1727
+ this.#loadState.set('error');
1728
+ this.failed.emit(failure);
1729
+ }
1730
+ }
1731
+ #applyOutputDefaults(info) {
1732
+ const output = this.option()?.output ?? {};
1733
+ this.format.set(this.#defaultFormat(info, output.format));
1734
+ this.quality.set(sdImageEditorClampQuality(output.quality ?? DEFAULT_QUALITY));
1735
+ this.background.set(output.background?.trim() || 'white');
1736
+ }
1737
+ /** Requested format, else the source format, else PNG (transparency) or JPEG — among the encodable formats. */
1738
+ #defaultFormat(info, requested) {
1739
+ const formats = this.#formats();
1740
+ const encodable = this.#encodable();
1741
+ const usable = formats.filter(format => !encodable || encodable.has(format));
1742
+ // why: consumer chỉ định rõ định dạng thì giữ nguyên, kể cả khi trình duyệt không encode được — panel báo lỗi,
1743
+ // Apply trả `format-unsupported`; không âm thầm đổi sang định dạng khác.
1744
+ if (requested && formats.includes(requested))
1745
+ return requested;
1746
+ if (usable.includes(info.mimeType))
1747
+ return info.mimeType;
1748
+ const fallback = info.hasAlpha ? 'image/png' : 'image/jpeg';
1749
+ if (usable.includes(fallback))
1750
+ return fallback;
1751
+ return usable[0] ?? formats[0];
1752
+ }
1753
+ #drawPreview(decoded) {
1754
+ const draw = () => {
1755
+ const canvas = this.previewCanvas()?.nativeElement;
1756
+ if (!canvas || this.#destroyed || this.#loaded()?.decoded !== decoded)
1757
+ return;
1758
+ try {
1759
+ const size = sdImageEditorDrawPreview(canvas, decoded, PREVIEW_MAX_PIXELS);
1760
+ this.#previewSize.set(size);
1761
+ const loaded = this.#loaded();
1762
+ // why: encoder canvas/PNG thường ghi kênh alpha cả khi ảnh đục — chỉ báo "có trong suốt" khi thật sự có pixel trong suốt.
1763
+ if (loaded?.info.hasAlpha && !sdImageEditorHasTransparency(canvas)) {
1764
+ const info = { ...loaded.info, hasAlpha: false };
1765
+ this.#loaded.set({ ...loaded, info });
1766
+ this.#applyOutputDefaults(info);
1767
+ }
1768
+ }
1769
+ catch (error) {
1770
+ const failure = this.#toError(error, 'load');
1771
+ this.#releaseSource();
1772
+ this.#loadError.set(failure);
1773
+ this.#loadState.set('error');
1774
+ this.failed.emit(failure);
1775
+ }
1776
+ this.#measureStage();
1777
+ };
1778
+ if (this.previewCanvas())
1779
+ draw();
1780
+ else
1781
+ afterNextRender(draw, { injector: this.#injector });
1782
+ }
1783
+ #releaseSource() {
1784
+ this.#endDrag(null);
1785
+ this.#draft.set(null);
1786
+ this.#clearEstimate();
1787
+ this.#encoded = null;
1788
+ this.#coalesce = null;
1789
+ const loaded = this.#loaded();
1790
+ if (loaded)
1791
+ loaded.decoded.release();
1792
+ this.#loaded.set(null);
1793
+ this.#history.set(null);
1794
+ this.#exporting.set(false);
1795
+ this.#pendingResult = null;
1796
+ const canvas = this.previewCanvas()?.nativeElement;
1797
+ if (canvas) {
1798
+ canvas.width = 0;
1799
+ canvas.height = 0;
1800
+ }
1801
+ }
1802
+ // ---- Internals: history ----
1803
+ #commit(next, coalesce) {
1804
+ const history = this.#history();
1805
+ if (!history)
1806
+ return;
1807
+ const now = Date.now();
1808
+ const merge = !!coalesce && this.#coalesce?.kind === coalesce && now - this.#coalesce.at < KEY_COALESCE_MS && history.past.length > 0;
1809
+ if (merge) {
1810
+ if (!sdImageEditorSameEdits(history.present, next))
1811
+ this.#history.set({ past: history.past, present: next, future: [] });
1812
+ }
1813
+ else {
1814
+ this.#history.set(sdImageEditorHistoryCommit(history, next, this.#historyLimit(), sdImageEditorSameEdits));
1815
+ }
1816
+ this.#coalesce = coalesce ? { kind: coalesce, at: now } : null;
1817
+ this.#afterHistoryChange();
1818
+ }
1819
+ #afterHistoryChange() {
1820
+ this.exportError.set(null);
1821
+ this.resizeNotice.set('');
1822
+ }
1823
+ // ---- Internals: view ----
1824
+ #zoomTo(zoom, anchorX, anchorY) {
1825
+ const bounds = this.#bounds();
1826
+ if (!bounds || !this.#interactive())
1827
+ return;
1828
+ const stage = this.#stageSize();
1829
+ const next = clamp(zoom, MIN_ZOOM, this.#maxZoom());
1830
+ const view = sdImageEditorZoomAt(stage, bounds, this.view(), STAGE_PADDING, next, anchorX ?? stage.width / 2, anchorY ?? stage.height / 2);
1831
+ // why: về đúng mức "vừa khung" thì bỏ luôn độ lệch pan, để nút Fit hiển thị trạng thái active chính xác.
1832
+ this.view.set(Math.abs(next - 1) < 1e-6 ? SD_IMAGE_EDITOR_FIT_VIEW : sdImageEditorClampPan(stage, bounds, view, STAGE_PADDING, PAN_MARGIN));
1833
+ }
1834
+ #measureStage() {
1835
+ const stage = this.stage()?.nativeElement;
1836
+ if (!stage)
1837
+ return;
1838
+ // why: đo kích thước layout, không dùng getBoundingClientRect — modal/drawer mở bằng animation scale nên rect lúc đó
1839
+ // nhỏ hơn thật, còn ResizeObserver không bắn lại khi chỉ transform thay đổi → ảnh lệch tâm vĩnh viễn.
1840
+ const width = stage.clientWidth;
1841
+ const height = stage.clientHeight;
1842
+ const current = this.#stageSize();
1843
+ if (current.width !== width || current.height !== height)
1844
+ this.#stageSize.set({ width, height });
1845
+ }
1846
+ /** Screen pixels per CSS pixel of the stage — not 1 while an ancestor is transformed (opening animation, zoom). */
1847
+ #visualScale(stage) {
1848
+ const width = stage.clientWidth;
1849
+ const ratio = width ? stage.getBoundingClientRect().width / width : 1;
1850
+ return Number.isFinite(ratio) && ratio > 0 ? ratio : 1;
1851
+ }
1852
+ #startDrag(event, mode, handle) {
1853
+ const edits = this.#history()?.present;
1854
+ const viewport = this.#viewport();
1855
+ if (!edits || !viewport || !this.#interactive() || this.#drag || event.button !== 0)
1856
+ return;
1857
+ event.preventDefault();
1858
+ const stage = this.stage()?.nativeElement;
1859
+ try {
1860
+ stage?.setPointerCapture(event.pointerId);
1861
+ }
1862
+ catch {
1863
+ // why: pointer tổng hợp (test, một số trình duyệt) có thể không capture được — vẫn kéo được trong stage.
1864
+ }
1865
+ this.#drag = {
1866
+ pointerId: event.pointerId,
1867
+ mode,
1868
+ handle,
1869
+ startX: event.clientX,
1870
+ startY: event.clientY,
1871
+ edits,
1872
+ view: this.view(),
1873
+ scale: viewport.scale,
1874
+ visual: stage ? this.#visualScale(stage) : 1,
1875
+ };
1876
+ this.dragging.set(mode);
1877
+ if (mode !== 'pan')
1878
+ this.cropBox()?.nativeElement.focus({ preventScroll: true });
1879
+ }
1880
+ #endDrag(pointerId) {
1881
+ if (!this.#drag)
1882
+ return;
1883
+ const stage = this.stage()?.nativeElement;
1884
+ if (pointerId !== null && stage?.hasPointerCapture?.(pointerId))
1885
+ stage.releasePointerCapture(pointerId);
1886
+ this.#drag = null;
1887
+ this.dragging.set(null);
1888
+ }
1889
+ // ---- Internals: output ----
1890
+ async #export(loaded, edits, size) {
1891
+ const seq = loaded.seq;
1892
+ const key = this.#outputKey();
1893
+ const format = this.format();
1894
+ const quality = sdImageEditorClampQuality(this.quality());
1895
+ const current = () => seq === this.#loadSeq && !this.#destroyed;
1896
+ this.#exporting.set(true);
1897
+ this.exportError.set(null);
1898
+ try {
1899
+ let encoded;
1900
+ try {
1901
+ const cached = this.#encoded && key && this.#encoded.key === key ? this.#encoded : null;
1902
+ encoded = cached ?? (await sdImageEditorExport(this.#document, this.#request(loaded, edits, size, format, quality)));
1903
+ if (key && !cached && current())
1904
+ this.#encoded = { key, blob: encoded.blob, format: encoded.format };
1905
+ }
1906
+ catch (error) {
1907
+ const failure = this.#toError(error, 'export');
1908
+ if (current())
1909
+ this.exportError.set(failure);
1910
+ throw failure;
1911
+ }
1912
+ // why: nguồn bị thay (hoặc editor bị huỷ) trong lúc encode — kết quả thuộc ảnh cũ, không được trả ra.
1913
+ if (!current())
1914
+ throw this.#toError(new SdImageEditorFailure('not-ready'), 'export');
1915
+ return this.#result(loaded, edits, size, encoded.blob, encoded.format, quality);
1916
+ }
1917
+ finally {
1918
+ if (current())
1919
+ this.#exporting.set(false);
1920
+ }
1921
+ }
1922
+ #request(loaded, edits, size, format, quality) {
1923
+ return {
1924
+ source: loaded.decoded,
1925
+ edits,
1926
+ output: { width: size.width, height: size.height },
1927
+ format,
1928
+ quality,
1929
+ background: this.background(),
1930
+ };
1931
+ }
1932
+ #result(loaded, edits, size, blob, format, quality) {
1933
+ const output = this.option()?.output ?? {};
1934
+ const sourceName = typeof File !== 'undefined' && loaded.blob instanceof File ? loaded.blob.name : undefined;
1935
+ const fileName = sdImageEditorFileName(output.fileName ?? sourceName, format);
1936
+ const resultType = output.resultType ?? 'auto';
1937
+ const wantsFile = resultType === 'file' || (resultType === 'auto' && sourceName !== undefined);
1938
+ const file = wantsFile && typeof File !== 'undefined' ? new File([blob], fileName, { type: format, lastModified: Date.now() }) : null;
1939
+ return {
1940
+ blob: file ?? blob,
1941
+ file,
1942
+ fileName,
1943
+ mimeType: format,
1944
+ width: size.width,
1945
+ height: size.height,
1946
+ size: blob.size,
1947
+ quality: format === 'image/png' ? null : quality,
1948
+ edits,
1949
+ sizeLimited: size.limited,
1950
+ };
1951
+ }
1952
+ #scheduleEstimate(key) {
1953
+ if (this.#estimateTimer)
1954
+ clearTimeout(this.#estimateTimer);
1955
+ this.#estimateTimer = null;
1956
+ if (!key)
1957
+ return;
1958
+ if (this.#encoded?.key === key) {
1959
+ this.#estimate.set({ key, status: 'ready', size: this.#encoded.blob.size });
1960
+ return;
1961
+ }
1962
+ const size = this.#outputSize();
1963
+ if (size && size.width * size.height > ESTIMATE_MAX_PIXELS) {
1964
+ this.#estimate.set({ key, status: 'skipped' });
1965
+ return;
1966
+ }
1967
+ this.#estimate.set({ key, status: 'pending' });
1968
+ // why: timer chạy ngoài zone — chờ debounce không được giữ app ở trạng thái "chưa ổn định" (whenStable, e2e).
1969
+ this.#estimateTimer = this.#zone.runOutsideAngular(() => setTimeout(() => this.#zone.run(() => void this.#runEstimate()), ESTIMATE_DELAY_MS));
1970
+ }
1971
+ /** Encodes the committed output once to learn its real size. Single-flight: a newer request waits its turn. */
1972
+ async #runEstimate() {
1973
+ this.#estimateTimer = null;
1974
+ if (this.#estimating) {
1975
+ this.#estimateQueued = true;
1976
+ return;
1977
+ }
1978
+ const key = this.#outputKey();
1979
+ const loaded = this.#loaded();
1980
+ const edits = this.#history()?.present;
1981
+ const size = this.#outputSize();
1982
+ if (!key || !loaded || !edits || !size || this.#destroyed)
1983
+ return;
1984
+ this.#estimating = true;
1985
+ const format = this.format();
1986
+ const quality = sdImageEditorClampQuality(this.quality());
1987
+ try {
1988
+ const encoded = await sdImageEditorExport(this.#document, this.#request(loaded, edits, size, format, quality));
1989
+ if (this.#destroyed || loaded.seq !== this.#loadSeq)
1990
+ return;
1991
+ this.#encoded = { key, blob: encoded.blob, format: encoded.format };
1992
+ if (this.#outputKey() === key)
1993
+ this.#estimate.set({ key, status: 'ready', size: encoded.blob.size });
1994
+ }
1995
+ catch (error) {
1996
+ if (this.#destroyed || loaded.seq !== this.#loadSeq)
1997
+ return;
1998
+ if (this.#outputKey() === key)
1999
+ this.#estimate.set({ key, status: 'error', error: this.#toError(error, 'export') });
2000
+ }
2001
+ finally {
2002
+ this.#estimating = false;
2003
+ if (this.#estimateQueued && !this.#destroyed) {
2004
+ this.#estimateQueued = false;
2005
+ const current = this.#outputKey();
2006
+ if (current && this.#estimate()?.key === current && this.#estimate()?.status === 'pending')
2007
+ void this.#runEstimate();
2008
+ }
2009
+ }
2010
+ }
2011
+ #clearEstimate() {
2012
+ if (this.#estimateTimer)
2013
+ clearTimeout(this.#estimateTimer);
2014
+ this.#estimateTimer = null;
2015
+ this.#estimateQueued = false;
2016
+ this.#estimate.set(null);
2017
+ }
2018
+ #toError(error, stage) {
2019
+ const failure = error instanceof SdImageEditorFailure ? error : null;
2020
+ const code = failure?.code ?? (stage === 'load' ? 'decode-failed' : 'encode-failed');
2021
+ return { code, stage, message: this.#message(code, failure?.detail), cause: failure ? failure.detail : error };
2022
+ }
2023
+ #message(code, detail) {
2024
+ const t = (key, params) => this.#i18n.t(`core.component.image-editor.error.${key}`, params);
2025
+ const locale = this.#i18n.locale();
2026
+ const limits = this.#limits();
2027
+ switch (code) {
2028
+ case 'source-too-large':
2029
+ return t(code, {
2030
+ size: sdImageEditorFormatBytes(typeof detail === 'number' ? detail : 0, locale),
2031
+ max: sdImageEditorFormatBytes(limits.maxSourceSize, locale),
2032
+ });
2033
+ case 'source-too-many-pixels': {
2034
+ const size = detail;
2035
+ return t(code, {
2036
+ width: size?.width ?? 0,
2037
+ height: size?.height ?? 0,
2038
+ max: round(limits.maxSourcePixels / 1_000_000, 1),
2039
+ });
2040
+ }
2041
+ case 'format-unsupported':
2042
+ return t(code, { format: FORMAT_LABELS[this.format()] });
2043
+ default:
2044
+ return t(code);
2045
+ }
2046
+ }
2047
+ #teardown() {
2048
+ this.#destroyed = true;
2049
+ this.#loadSeq++;
2050
+ this.#resizeObserver?.disconnect();
2051
+ this.#resizeObserver = null;
2052
+ this.#releaseSource();
2053
+ }
2054
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.25", ngImport: i0, type: SdImageEditor, deps: [], target: i0.ɵɵFactoryTarget.Component });
2055
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "20.3.25", type: SdImageEditor, isStandalone: true, selector: "sd-image-editor", inputs: { source: { classPropertyName: "source", publicName: "source", isSignal: true, isRequired: false, transformFunction: null }, option: { classPropertyName: "option", publicName: "option", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { failed: "failed" }, host: { listeners: { "keydown": "onKeydown($event)" }, properties: { "class.sd-image-editor--compact": "compact()", "class.sd-image-editor--dragging": "dragging() !== null", "attr.data-autoid": "autoId()", "attr.aria-busy": "status() === 'loading' || status() === 'exporting' ? 'true' : null" }, classAttribute: "sd-image-editor" }, viewQueries: [{ propertyName: "stage", first: true, predicate: ["stage"], descendants: true, isSignal: true }, { propertyName: "previewCanvas", first: true, predicate: ["previewCanvas"], descendants: true, isSignal: true }, { propertyName: "cropBox", first: true, predicate: ["cropBox"], descendants: true, isSignal: true }], ngImport: i0, template: "@let _status = status();\n@let _autoId = autoId();\n@let _interactive = interactive();\n@let _busy = busy();\n@let _edits = edits();\n@let _crop = cropStyle();\n@let _image = imageBox();\n@let _output = outputSize();\n@let _limits = cropLimits();\n@let _max = resizeMax();\n@let _visible = _status === 'ready' || _status === 'exporting';\n@let _error = error();\n@let _locked = ratioLocked();\n@let _fixed = ratioFixed();\n\n<div class=\"toolbar\">\n <div class=\"toolbar-group\" role=\"group\" [attr.aria-label]=\"'core.component.image-editor.group-history' | sdTranslate\">\n <sd-button\n type=\"text\"\n size=\"sm\"\n prefixIcon=\"undo\"\n [tooltip]=\"'core.component.image-editor.undo' | sdTranslate\"\n [disabled]=\"!canUndo()\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-undo' : null\"\n (click)=\"undo()\" />\n <sd-button\n type=\"text\"\n size=\"sm\"\n prefixIcon=\"redo\"\n [tooltip]=\"'core.component.image-editor.redo' | sdTranslate\"\n [disabled]=\"!canRedo()\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-redo' : null\"\n (click)=\"redo()\" />\n <sd-button\n type=\"text\"\n size=\"sm\"\n prefixIcon=\"restart_alt\"\n [tooltip]=\"'core.component.image-editor.reset' | sdTranslate\"\n [disabled]=\"!_interactive || !dirty()\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-reset' : null\"\n (click)=\"reset()\" />\n </div>\n\n <div class=\"toolbar-group\" role=\"group\" [attr.aria-label]=\"'core.component.image-editor.group-transform' | sdTranslate\">\n <sd-button\n type=\"text\"\n size=\"sm\"\n prefixIcon=\"rotate_left\"\n [tooltip]=\"'core.component.image-editor.rotate-left' | sdTranslate\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-rotate-left' : null\"\n (click)=\"operate('rotate-ccw')\" />\n <sd-button\n type=\"text\"\n size=\"sm\"\n prefixIcon=\"rotate_right\"\n [tooltip]=\"'core.component.image-editor.rotate-right' | sdTranslate\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-rotate-right' : null\"\n (click)=\"operate('rotate-cw')\" />\n <sd-button\n type=\"text\"\n size=\"sm\"\n prefixIcon=\"flip\"\n [tooltip]=\"'core.component.image-editor.flip-horizontal' | sdTranslate\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-flip-horizontal' : null\"\n (click)=\"operate('flip-horizontal')\" />\n <sd-button\n class=\"flip-vertical\"\n type=\"text\"\n size=\"sm\"\n prefixIcon=\"flip\"\n [tooltip]=\"'core.component.image-editor.flip-vertical' | sdTranslate\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-flip-vertical' : null\"\n (click)=\"operate('flip-vertical')\" />\n </div>\n\n <div class=\"toolbar-group toolbar-group--zoom\" role=\"group\" [attr.aria-label]=\"'core.component.image-editor.group-zoom' | sdTranslate\">\n <sd-button\n type=\"text\"\n size=\"sm\"\n prefixIcon=\"zoom_out\"\n [tooltip]=\"'core.component.image-editor.zoom-out' | sdTranslate\"\n [disabled]=\"!canZoomOut()\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-zoom-out' : null\"\n (click)=\"zoomOut()\" />\n <span class=\"zoom-value\" [attr.data-autoid]=\"_autoId ? _autoId + '-zoom-value' : null\">{{ _visible ? zoomPercent() + '%' : '\u2013' }}</span>\n <sd-button\n type=\"text\"\n size=\"sm\"\n prefixIcon=\"zoom_in\"\n [tooltip]=\"'core.component.image-editor.zoom-in' | sdTranslate\"\n [disabled]=\"!canZoomIn()\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-zoom-in' : null\"\n (click)=\"zoomIn()\" />\n <sd-button\n type=\"text\"\n size=\"sm\"\n prefixIcon=\"fit_screen\"\n [tooltip]=\"'core.component.image-editor.fit' | sdTranslate\"\n [disabled]=\"!_interactive || isFit()\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-fit' : null\"\n (click)=\"fitToView()\" />\n </div>\n</div>\n\n<div class=\"body\">\n <div\n #stage\n class=\"stage\"\n role=\"group\"\n [id]=\"instanceId + '-stage'\"\n [class.stage--panning]=\"dragging() === 'pan'\"\n [attr.aria-label]=\"'core.component.image-editor.stage' | sdTranslate\"\n [attr.aria-describedby]=\"instanceId + '-hint'\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-stage' : null\"\n (pointerdown)=\"onStagePointerDown($event)\"\n (pointermove)=\"onPointerMove($event)\"\n (pointerup)=\"onPointerUp($event)\"\n (pointercancel)=\"onPointerCancel($event)\"\n (lostpointercapture)=\"onPointerCancel($event)\"\n (wheel)=\"onWheel($event)\">\n @if (_visible && _image) {\n <div\n class=\"checker\"\n aria-hidden=\"true\"\n [style.left.px]=\"_image.x\"\n [style.top.px]=\"_image.y\"\n [style.width.px]=\"_image.width\"\n [style.height.px]=\"_image.height\"></div>\n }\n <!-- why: canvas lu\u00F4n n\u1EB1m trong DOM \u0111\u1EC3 v\u1EBD preview ngay khi decode xong; \u1EA9n khi ch\u01B0a c\u00F3 \u1EA3nh. -->\n <canvas\n #previewCanvas\n class=\"preview\"\n aria-hidden=\"true\"\n [class.preview--hidden]=\"!_visible\"\n [style.width.px]=\"previewSize().width\"\n [style.height.px]=\"previewSize().height\"\n [style.transform]=\"previewTransform()\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-preview' : null\"></canvas>\n\n @if (_visible && _crop && _edits) {\n <div\n #cropBox\n class=\"crop\"\n tabindex=\"0\"\n role=\"group\"\n [attr.aria-roledescription]=\"'core.component.image-editor.crop-role' | sdTranslate\"\n [attr.aria-label]=\"cropLabel()\"\n [attr.aria-describedby]=\"instanceId + '-hint'\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-crop' : null\"\n [style.left.px]=\"_crop.x\"\n [style.top.px]=\"_crop.y\"\n [style.width.px]=\"_crop.width\"\n [style.height.px]=\"_crop.height\"\n (pointerdown)=\"onCropPointerDown($event, null)\"\n (keydown)=\"onCropKeydown($event)\">\n <span class=\"crop-grid\" aria-hidden=\"true\"></span>\n @for (handle of handles; track handle) {\n <span\n class=\"handle\"\n aria-hidden=\"true\"\n [attr.data-handle]=\"handle\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-handle-' + handle : null\"\n (pointerdown)=\"onCropPointerDown($event, handle)\"></span>\n }\n </div>\n }\n\n @switch (_status) {\n @case ('empty') {\n <div class=\"state\">\n <sd-icon name=\"image\" size=\"32px\" />\n <p class=\"state-title\">{{ 'core.component.image-editor.empty' | sdTranslate }}</p>\n <p class=\"state-text\">{{ 'core.component.image-editor.empty-hint' | sdTranslate }}</p>\n </div>\n }\n @case ('loading') {\n <div class=\"state\" role=\"status\">\n <span class=\"spinner\" aria-hidden=\"true\"></span>\n <p class=\"state-title\">{{ 'core.component.image-editor.loading' | sdTranslate }}</p>\n </div>\n }\n @case ('error') {\n <div class=\"state state--error\" role=\"alert\" [attr.data-autoid]=\"_autoId ? _autoId + '-error' : null\">\n <sd-icon name=\"broken_image\" size=\"32px\" />\n <p class=\"state-title\">{{ 'core.component.image-editor.load-error' | sdTranslate }}</p>\n <p class=\"state-text\">{{ _error?.message }}</p>\n </div>\n }\n }\n @if (_busy) {\n <div class=\"busy\" aria-hidden=\"true\"><span class=\"spinner\"></span></div>\n }\n <p class=\"visually-hidden\" [id]=\"instanceId + '-hint'\">{{ 'core.component.image-editor.keyboard-hint' | sdTranslate }}</p>\n <p class=\"visually-hidden\" role=\"status\" [attr.data-autoid]=\"_autoId ? _autoId + '-status' : null\">{{ statusMessage() }}</p>\n </div>\n\n <aside class=\"panel\" [attr.aria-label]=\"'core.component.image-editor.panel' | sdTranslate\" [attr.inert]=\"_visible ? null : ''\">\n <section class=\"section\">\n <h3 class=\"section-title\">\n <sd-icon name=\"crop\" size=\"18px\" />\n {{ 'core.component.image-editor.crop' | sdTranslate }}\n </h3>\n @if (showRatios()) {\n <div class=\"chips\" role=\"group\" [attr.aria-label]=\"'core.component.image-editor.ratio' | sdTranslate\">\n @for (chip of ratioChips(); track chip.key) {\n @let _active = sameRatio(_edits?.aspectRatio ?? null, chip.value);\n <button\n type=\"button\"\n class=\"chip\"\n [class.chip--active]=\"_active\"\n [attr.aria-pressed]=\"_active\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-ratio-' + chip.key : null\"\n (click)=\"selectRatio(chip.value)\">\n {{ chip.label }}\n </button>\n }\n </div>\n }\n @if (_edits && _limits) {\n <div class=\"option-row\">\n <span class=\"prop-label\">\n <span [id]=\"instanceId + '-keep-ratio'\">{{ 'core.component.image-editor.keep-ratio' | sdTranslate }}</span>\n @if (_fixed) {\n @let _fixedText = 'core.component.image-editor.keep-ratio-fixed' | sdTranslate;\n <!-- why: n\u00FAt (kh\u00F4ng ph\u1EA3i span) \u0111\u1EC3 b\u00E0n ph\u00EDm focus \u0111\u01B0\u1EE3c; sdTooltip m\u1EDF khi hover v\u00E0 focus, Escape \u0111\u00F3ng. -->\n <button\n type=\"button\"\n class=\"info\"\n sdTooltipPosition=\"top\"\n [sdTooltip]=\"_fixedText\"\n [attr.aria-label]=\"_fixedText\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-ratio-fixed-info' : null\">\n <sd-icon name=\"info\" size=\"16px\" />\n </button>\n }\n @if (_locked) {\n <span class=\"prop-value\" [attr.data-autoid]=\"_autoId ? _autoId + '-ratio-value' : null\">{{ ratioText() }}</span>\n }\n </span>\n <button\n type=\"button\"\n class=\"lock\"\n [class.lock--on]=\"_locked\"\n [attr.aria-pressed]=\"_locked\"\n [attr.aria-labelledby]=\"instanceId + '-keep-ratio'\"\n [title]=\"'core.component.image-editor.keep-ratio' | sdTranslate\"\n [disabled]=\"!_interactive || _fixed\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-keep-ratio' : null\"\n (click)=\"toggleKeepRatio()\">\n <sd-icon [name]=\"_locked ? 'lock' : 'lock_open'\" size=\"18px\" />\n </button>\n </div>\n <div class=\"fields\">\n <sd-input-number\n #cropX\n size=\"sm\"\n type=\"positive\"\n hideInlineError\n label=\"X\"\n [precision]=\"0\"\n [model]=\"_edits.crop.x\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-crop-x' : null\"\n (sdBlur)=\"onCropField('x', $event, cropX)\"\n (keyupEnter)=\"onCropField('x', cropX.valueModel(), cropX)\" />\n <sd-input-number\n #cropY\n size=\"sm\"\n type=\"positive\"\n hideInlineError\n label=\"Y\"\n [precision]=\"0\"\n [model]=\"_edits.crop.y\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-crop-y' : null\"\n (sdBlur)=\"onCropField('y', $event, cropY)\"\n (keyupEnter)=\"onCropField('y', cropY.valueModel(), cropY)\" />\n <sd-input-number\n #cropW\n size=\"sm\"\n type=\"positive\"\n hideInlineError\n [label]=\"'core.component.image-editor.width' | sdTranslate\"\n [precision]=\"0\"\n [model]=\"_edits.crop.width\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-crop-width' : null\"\n (sdBlur)=\"onCropField('width', $event, cropW)\"\n (keyupEnter)=\"onCropField('width', cropW.valueModel(), cropW)\" />\n <sd-input-number\n #cropH\n size=\"sm\"\n type=\"positive\"\n hideInlineError\n [label]=\"'core.component.image-editor.height' | sdTranslate\"\n [precision]=\"0\"\n [model]=\"_edits.crop.height\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-crop-height' : null\"\n (sdBlur)=\"onCropField('height', $event, cropH)\"\n (keyupEnter)=\"onCropField('height', cropH.valueModel(), cropH)\" />\n </div>\n }\n </section>\n\n <section class=\"section\">\n <h3 class=\"section-title\">\n <sd-icon name=\"photo_size_select_large\" size=\"18px\" />\n {{ 'core.component.image-editor.resize' | sdTranslate }}\n </h3>\n @if (_output && _max) {\n <div class=\"fields\">\n <sd-input-number\n #outW\n size=\"sm\"\n type=\"positive\"\n hideInlineError\n [label]=\"'core.component.image-editor.width' | sdTranslate\"\n [precision]=\"0\"\n [model]=\"_output.width\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-output-width' : null\"\n (sdBlur)=\"onResizeField('width', $event, outW)\"\n (keyupEnter)=\"onResizeField('width', outW.valueModel(), outW)\" />\n <sd-input-number\n #outH\n size=\"sm\"\n type=\"positive\"\n hideInlineError\n [label]=\"'core.component.image-editor.height' | sdTranslate\"\n [precision]=\"0\"\n [model]=\"_output.height\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-output-height' : null\"\n (sdBlur)=\"onResizeField('height', $event, outH)\"\n (keyupEnter)=\"onResizeField('height', outH.valueModel(), outH)\" />\n </div>\n <p class=\"hint\">\n {{ 'core.component.image-editor.resize-max' | sdTranslate: { width: _max.width, height: _max.height } }}\n </p>\n @if (_edits?.resize) {\n <button\n type=\"button\"\n class=\"text-button\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-resize-reset' : null\"\n (click)=\"resetResize()\">\n {{ 'core.component.image-editor.resize-follow-crop' | sdTranslate }}\n </button>\n }\n @if (resizeNotice()) {\n <p class=\"notice\" role=\"status\">{{ resizeNotice() }}</p>\n }\n @if (_output.limited) {\n <p class=\"notice\" [attr.data-autoid]=\"_autoId ? _autoId + '-limited' : null\">\n {{ 'core.component.image-editor.output-limited' | sdTranslate }}\n </p>\n }\n }\n </section>\n\n <section class=\"section\">\n <h3 class=\"section-title\">\n <sd-icon name=\"tune\" size=\"18px\" />\n {{ 'core.component.image-editor.output' | sdTranslate }}\n </h3>\n @if (showFormatPicker()) {\n <sd-select\n size=\"sm\"\n required\n hideInlineError\n valueField=\"format\"\n displayField=\"label\"\n disabledField=\"disabled\"\n [label]=\"'core.component.image-editor.format' | sdTranslate\"\n [items]=\"formatChoices()\"\n [clearable]=\"false\"\n [model]=\"format()\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-format' : null\"\n (sdChange)=\"onFormatChange($event)\" />\n }\n @if (formatUnsupported()) {\n <p class=\"notice notice--error\" role=\"alert\">\n {{ 'core.component.image-editor.error.format-unsupported' | sdTranslate: { format: formatLabel() } }}\n </p>\n }\n @if (lossy()) {\n <label class=\"prop\">\n <span class=\"prop-label prop-label--row\">\n {{ 'core.component.image-editor.quality' | sdTranslate }}\n <span class=\"prop-value\">{{ qualityPercent() }}%</span>\n </span>\n <input\n #qualityInput\n type=\"range\"\n min=\"1\"\n max=\"100\"\n step=\"1\"\n [value]=\"qualityPercent()\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-quality' : null\"\n (input)=\"onQualityInput(qualityInput.value)\" />\n </label>\n }\n @if (showBackground()) {\n <label class=\"prop prop--inline\">\n <span class=\"prop-label\">{{ 'core.component.image-editor.background' | sdTranslate }}</span>\n <input\n #backgroundInput\n type=\"color\"\n [value]=\"backgroundHex()\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-background' : null\"\n (input)=\"onBackgroundInput(backgroundInput.value)\" />\n </label>\n <p class=\"hint\">{{ 'core.component.image-editor.background-hint' | sdTranslate }}</p>\n }\n\n @if (exportError(); as exportFailure) {\n <p class=\"notice notice--error\" role=\"alert\" [attr.data-autoid]=\"_autoId ? _autoId + '-export-error' : null\">\n {{ exportFailure.message }}\n </p>\n }\n <dl class=\"meta\">\n <div class=\"meta-row\">\n <dt>{{ 'core.component.image-editor.meta-source' | sdTranslate }}</dt>\n <dd [attr.data-autoid]=\"_autoId ? _autoId + '-meta-source' : null\">{{ sourceSummary() || '\u2013' }}</dd>\n </div>\n <div class=\"meta-row\">\n <dt>{{ 'core.component.image-editor.meta-output' | sdTranslate }}</dt>\n <dd [attr.data-autoid]=\"_autoId ? _autoId + '-meta-output' : null\">{{ outputSummary() || '\u2013' }}</dd>\n </div>\n <div class=\"meta-row\">\n <dt>{{ 'core.component.image-editor.meta-size' | sdTranslate }}</dt>\n <dd [attr.data-autoid]=\"_autoId ? _autoId + '-meta-size' : null\">{{ _visible ? estimateLabel() : '\u2013' }}</dd>\n </div>\n </dl>\n </section>\n </aside>\n</div>\n", styles: [":host{--sd-ie-accent: var(--sd-image-editor-accent, var(--sd-primary, #005cbb));--sd-ie-accent-contrast: var(--sd-image-editor-accent-contrast, var(--sd-primary-contrast, #ffffff));--sd-ie-surface: var(--sd-image-editor-surface, var(--sd-surface, #ffffff));--sd-ie-muted-surface: var( --sd-image-editor-muted-surface, color-mix(in srgb, var(--sd-surface-muted, #e7e8ed) 45%, var(--sd-ie-surface)) );--sd-ie-stage-bg: var(--sd-image-editor-stage-bg, color-mix(in srgb, var(--sd-surface-muted, #e7e8ed) 80%, var(--sd-ie-surface)));--sd-ie-border: var(--sd-image-editor-border, var(--sd-border, #c4c6d0));--sd-ie-text: var(--sd-image-editor-text, var(--sd-text, #1a1b1f));--sd-ie-text-secondary: var(--sd-image-editor-text-secondary, var(--sd-text-secondary, #44474f));--sd-ie-error: var(--sd-image-editor-error, var(--sd-error, #ba1a1a));--sd-ie-warning-bg: var(--sd-image-editor-warning-bg, var(--sd-status-warning-bg, #fff4e5));--sd-ie-warning-fg: var(--sd-image-editor-warning-fg, var(--sd-status-warning-fg, #8a5400));--sd-ie-checker-a: var(--sd-image-editor-checker-light, #ffffff);--sd-ie-checker-b: var(--sd-image-editor-checker-dark, #e3e5ea);--sd-ie-checker-size: var(--sd-image-editor-checker-size, 16px);--sd-ie-shade: var(--sd-image-editor-shade, rgba(0, 0, 0, .55));--sd-ie-frame: var(--sd-image-editor-frame, white);--sd-ie-radius: var(--sd-image-editor-radius, var(--sd-radius-12, 12px));--sd-ie-panel-width: var(--sd-image-editor-panel-width, 288px);position:relative;display:flex;flex-direction:column;height:100%;min-height:520px;overflow:hidden;border:1px solid var(--sd-ie-border);border-radius:var(--sd-ie-radius);background:var(--sd-ie-surface);color:var(--sd-ie-text);font-size:var(--sd-font-size-14, 14px);line-height:var(--sd-line-height-20, 20px)}.toolbar{display:flex;flex-wrap:wrap;align-items:center;gap:var(--sd-space-4, 4px) var(--sd-space-12, 12px);padding:var(--sd-space-8, 8px) var(--sd-space-12, 12px);border-bottom:1px solid var(--sd-ie-border)}.toolbar-group{display:flex;align-items:center;gap:var(--sd-space-2, 2px)}.toolbar-group+.toolbar-group{padding-left:var(--sd-space-12, 12px);border-left:1px solid var(--sd-ie-border)}.toolbar-group--zoom{margin-left:auto}.zoom-value{min-width:48px;font-size:var(--sd-font-size-13, 13px);font-variant-numeric:tabular-nums;text-align:center;color:var(--sd-ie-text-secondary)}.flip-vertical ::ng-deep sd-icon{transform:rotate(90deg)}.body{flex:1 1 auto;display:grid;grid-template-columns:minmax(0,1fr) var(--sd-ie-panel-width);min-height:0}.stage{position:relative;min-width:0;min-height:320px;overflow:hidden;background:var(--sd-ie-stage-bg);cursor:grab;touch-action:none;-webkit-user-select:none;user-select:none}.stage:focus-visible{outline:var(--sd-focus-ring-width, 2px) solid var(--sd-focus-ring-color);outline-offset:calc(-1 * var(--sd-focus-ring-width, 2px))}.stage--panning{cursor:grabbing}.checker{position:absolute;pointer-events:none;background:repeating-conic-gradient(var(--sd-ie-checker-b) 0% 25%,var(--sd-ie-checker-a) 0% 50%) 0 0/var(--sd-ie-checker-size) var(--sd-ie-checker-size)}.preview{position:absolute;top:0;left:0;transform-origin:0 0;pointer-events:none}.preview--hidden{visibility:hidden}.crop{position:absolute;box-sizing:border-box;border:1px solid var(--sd-ie-frame);box-shadow:0 0 0 100vmax var(--sd-ie-shade);cursor:move;touch-action:none}.crop:focus-visible{outline:var(--sd-focus-ring-width, 2px) solid var(--sd-focus-ring-color);outline-offset:var(--sd-focus-ring-offset, 2px)}.crop-grid{position:absolute;inset:0;pointer-events:none;opacity:.55;background:linear-gradient(to right,transparent calc(33.333% - .5px),var(--sd-ie-frame) calc(33.333% - .5px) calc(33.333% + .5px),transparent calc(33.333% + .5px)),linear-gradient(to right,transparent calc(66.666% - .5px),var(--sd-ie-frame) calc(66.666% - .5px) calc(66.666% + .5px),transparent calc(66.666% + .5px)),linear-gradient(to bottom,transparent calc(33.333% - .5px),var(--sd-ie-frame) calc(33.333% - .5px) calc(33.333% + .5px),transparent calc(33.333% + .5px)),linear-gradient(to bottom,transparent calc(66.666% - .5px),var(--sd-ie-frame) calc(66.666% - .5px) calc(66.666% + .5px),transparent calc(66.666% + .5px))}.sd-image-editor--dragging .crop-grid{opacity:.85}.handle{--sd-ie-handle-size: 14px;--sd-ie-handle-hit: 28px;position:absolute;width:var(--sd-ie-handle-hit);height:var(--sd-ie-handle-hit);margin:calc(var(--sd-ie-handle-hit) / -2) 0 0 calc(var(--sd-ie-handle-hit) / -2);touch-action:none}.handle:after{content:\"\";position:absolute;top:50%;left:50%;width:var(--sd-ie-handle-size);height:var(--sd-ie-handle-size);transform:translate(-50%,-50%);box-sizing:border-box;border:2px solid var(--sd-ie-accent);border-radius:var(--sd-radius-2, 2px);background:var(--sd-ie-frame);box-shadow:var(--sd-shadow-xs, 0 1px 2px rgba(0, 0, 0, .3))}.handle[data-handle=n]:after,.handle[data-handle=s]:after{width:22px;height:8px}.handle[data-handle=e]:after,.handle[data-handle=w]:after{width:8px;height:22px}.handle[data-handle=nw]{top:0;left:0;cursor:nwse-resize}.handle[data-handle=n]{top:0;left:50%;cursor:ns-resize}.handle[data-handle=ne]{top:0;left:100%;cursor:nesw-resize}.handle[data-handle=e]{top:50%;left:100%;cursor:ew-resize}.handle[data-handle=se]{top:100%;left:100%;cursor:nwse-resize}.handle[data-handle=s]{top:100%;left:50%;cursor:ns-resize}.handle[data-handle=sw]{top:100%;left:0;cursor:nesw-resize}.handle[data-handle=w]{top:50%;left:0;cursor:ew-resize}@media(pointer:coarse){.handle{--sd-ie-handle-size: 18px;--sd-ie-handle-hit: 40px}}.state{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:var(--sd-space-6, 6px);padding:var(--sd-space-24, 24px);text-align:center;color:var(--sd-ie-text-secondary);cursor:default}.state-title{margin:0;font-weight:var(--sd-font-weight-semibold, 600);color:var(--sd-ie-text)}.state-text{max-width:420px;margin:0;font-size:var(--sd-font-size-13, 13px)}.state--error sd-icon,.state--error .state-title{color:var(--sd-ie-error)}.busy{position:absolute;inset:0;display:grid;place-items:center;background:color-mix(in srgb,var(--sd-ie-surface) 45%,transparent);cursor:progress}.spinner{width:28px;height:28px;border:3px solid color-mix(in srgb,var(--sd-ie-accent) 25%,transparent);border-top-color:var(--sd-ie-accent);border-radius:50%;animation:sd-image-editor-spin .8s linear infinite}@keyframes sd-image-editor-spin{to{transform:rotate(360deg)}}@media(prefers-reduced-motion:reduce){.spinner{animation-duration:2.4s}}.visually-hidden{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}.panel{min-width:0;overflow-y:auto;border-left:1px solid var(--sd-ie-border);background:var(--sd-ie-surface)}.section{display:flex;flex-direction:column;gap:var(--sd-space-8, 8px);padding:var(--sd-space-12, 12px) var(--sd-space-16, 16px)}.section+.section{border-top:1px solid var(--sd-ie-border)}.section-title{display:flex;align-items:center;gap:var(--sd-space-6, 6px);margin:0;font-size:var(--sd-font-size-13, 13px);font-weight:var(--sd-font-weight-semibold, 600);line-height:var(--sd-line-height-18, 18px);color:var(--sd-ie-text)}.section-title sd-icon{color:var(--sd-ie-text-secondary)}.chips{display:flex;flex-wrap:wrap;gap:var(--sd-space-6, 6px)}.chip{min-width:44px;height:28px;padding:0 var(--sd-space-10, 10px);border:1px solid var(--sd-ie-border);border-radius:var(--sd-radius-999, 999px);background:var(--sd-ie-surface);color:var(--sd-ie-text);font:inherit;font-size:var(--sd-font-size-13, 13px);cursor:pointer;transition:background-color var(--sd-duration-fast, .12s) ease,border-color var(--sd-duration-fast, .12s) ease}.chip:hover:not(:disabled){background:var(--sd-ie-muted-surface)}.chip:focus-visible{outline:var(--sd-focus-ring-width, 2px) solid var(--sd-focus-ring-color);outline-offset:var(--sd-focus-ring-offset, 2px)}.chip:disabled{cursor:default;opacity:.55}.chip--active{border-color:var(--sd-ie-accent);background:var(--sd-ie-accent);color:var(--sd-ie-accent-contrast)}.chip--active:hover:not(:disabled){background:var(--sd-ie-accent)}.fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--sd-space-8, 8px)}.fields sd-input-number,.section>sd-select{display:block;min-width:0}.section>sd-select ::ng-deep .mat-mdc-form-field-required-marker{display:none}.prop-label{display:flex;align-items:baseline;gap:var(--sd-space-6, 6px);margin:0;font-size:var(--sd-font-size-12, 12px);font-weight:var(--sd-font-weight-bold, 700);line-height:var(--sd-line-height-18, 18px);color:var(--sd-ie-text-secondary)}.prop-label--row{justify-content:space-between}.prop-value{font-weight:var(--sd-font-weight-regular, 400);font-variant-numeric:tabular-nums;color:var(--sd-ie-text)}.prop{display:flex;flex-direction:column;gap:var(--sd-space-4, 4px);min-width:0}.prop input[type=range]{width:100%;margin:0;accent-color:var(--sd-ie-accent)}.prop input[type=range]:focus-visible{outline:var(--sd-focus-ring-width, 2px) solid var(--sd-focus-ring-color);outline-offset:var(--sd-focus-ring-offset, 2px)}.prop--inline{flex-direction:row;align-items:center;justify-content:space-between}.prop--inline input[type=color]{width:40px;height:28px;padding:0 2px;border:1px solid var(--sd-ie-border);border-radius:var(--sd-radius-6, 6px);background:var(--sd-ie-surface);cursor:pointer}.prop--inline input[type=color]:focus-visible{outline:var(--sd-focus-ring-width, 2px) solid var(--sd-focus-ring-color);outline-offset:var(--sd-focus-ring-offset, 2px)}.option-row{display:flex;align-items:center;justify-content:space-between;gap:var(--sd-space-8, 8px);min-height:32px}.info{display:inline-grid;place-items:center;align-self:center;width:18px;height:18px;padding:0;border:0;border-radius:50%;background:transparent;color:var(--sd-ie-text-secondary);cursor:help}.info:hover{color:var(--sd-ie-text)}.info:focus-visible{outline:var(--sd-focus-ring-width, 2px) solid var(--sd-focus-ring-color);outline-offset:var(--sd-focus-ring-offset, 2px)}.lock{display:grid;place-items:center;width:32px;height:32px;padding:0;border:1px solid transparent;border-radius:var(--sd-radius-6, 6px);background:transparent;color:var(--sd-ie-text-secondary);cursor:pointer}.lock:hover:not(:disabled){background:var(--sd-ie-muted-surface)}.lock:focus-visible{outline:var(--sd-focus-ring-width, 2px) solid var(--sd-focus-ring-color);outline-offset:var(--sd-focus-ring-offset, 2px)}.lock:disabled{cursor:default;opacity:.55}.lock--on{color:var(--sd-ie-accent)}.hint{margin:0;font-size:var(--sd-font-size-12, 12px);line-height:var(--sd-line-height-16, 16px);color:var(--sd-ie-text-secondary)}.notice{margin:0;padding:var(--sd-space-6, 6px) var(--sd-space-8, 8px);border-radius:var(--sd-radius-6, 6px);background:var(--sd-ie-warning-bg);color:var(--sd-ie-warning-fg);font-size:var(--sd-font-size-12, 12px);line-height:var(--sd-line-height-16, 16px)}.notice--error{background:color-mix(in srgb,var(--sd-ie-error) 10%,var(--sd-ie-surface));color:var(--sd-ie-error)}.text-button{align-self:flex-start;padding:0;border:0;background:none;color:var(--sd-ie-accent);font:inherit;font-size:var(--sd-font-size-13, 13px);cursor:pointer}.text-button:hover:not(:disabled){text-decoration:underline}.text-button:focus-visible{outline:var(--sd-focus-ring-width, 2px) solid var(--sd-focus-ring-color);outline-offset:var(--sd-focus-ring-offset, 2px)}.meta{display:flex;flex-direction:column;gap:var(--sd-space-4, 4px);margin:var(--sd-space-4, 4px) 0 0;padding:var(--sd-space-8, 8px) var(--sd-space-10, 10px);border-radius:var(--sd-radius-8, 8px);background:var(--sd-ie-muted-surface)}.meta-row{display:flex;justify-content:space-between;gap:var(--sd-space-8, 8px);font-size:var(--sd-font-size-12, 12px);line-height:var(--sd-line-height-18, 18px)}.meta-row dt{flex:none;font-weight:var(--sd-font-weight-bold, 700);color:var(--sd-ie-text-secondary)}.meta-row dd{margin:0;min-width:0;text-align:right;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}:host(.sd-image-editor--compact){min-height:0}:host(.sd-image-editor--compact) .toolbar{column-gap:var(--sd-space-16, 16px)}:host(.sd-image-editor--compact) .toolbar-group+.toolbar-group{padding-left:0;border-left:0}:host(.sd-image-editor--compact) .toolbar-group--zoom{margin-left:0}:host(.sd-image-editor--compact) .body{display:flex;flex-direction:column;overflow-y:auto}:host(.sd-image-editor--compact) .stage{flex:none;height:clamp(240px,50vh,480px);min-height:0}:host(.sd-image-editor--compact) .panel{flex:none;overflow:visible;border-top:1px solid var(--sd-ie-border);border-left:0}\n"], dependencies: [{ kind: "component", type: SdButton, selector: "sd-button", inputs: ["autoId", "type", "color", "size", "fontSet", "title", "width", "tooltip", "prefixIcon", "suffixIcon", "disabled", "openOnHover", "loading", "block", "htmlType"], outputs: ["click"] }, { kind: "component", type: SdIcon, selector: "sd-icon", inputs: ["name", "fontIcon", "color", "set", "fontSet", "size", "strokeWidth", "absoluteStrokeWidth", "ariaLabel"] }, { kind: "component", type: SdInputNumber, selector: "sd-input-number", inputs: ["autoId", "name", "size", "form", "label", "helperText", "placeholder", "hideInlineError", "blurOnEnter", "clearable", "required", "readonly", "disabled", "viewed", "type", "precision", "format", "min", "max", "validator", "inlineError", "hyperlink", "appearance", "floatLabel", "labelPlacement", "inputmode", "model"], outputs: ["modelChange", "sdChange", "sdFocus", "sdBlur", "keyupEnter", "cleared", "sdFocusForceBlur"] }, { kind: "component", type: SdSelect, selector: "sd-select", inputs: ["autoId", "name", "size", "form", "label", "helperText", "placeholder", "valueField", "displayField", "disabledField", "cacheChecksum", "limit", "virtualScroll", "itemSize", "hyperlink", "minWidthPanel", "hideInlineError", "hideReadError", "required", "disabled", "viewed", "multiple", "showSelectAll", "clearable", "validator", "inlineError", "appearance", "floatLabel", "labelPlacement", "items", "model"], outputs: ["sdReadStateChange", "modelChange", "sdChange", "sdSelection"] }, { kind: "directive", type: SdTooltipDirective, selector: "[sdTooltip]", inputs: ["sdTooltip", "sdTooltipPosition", "sdTooltipDelay", "sdTooltipColor"] }, { kind: "pipe", type: SdTranslatePipe, name: "sdTranslate" }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
2056
+ }
2057
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.25", ngImport: i0, type: SdImageEditor, decorators: [{
2058
+ type: Component,
2059
+ args: [{ selector: 'sd-image-editor', standalone: true, imports: [SdButton, SdIcon, SdInputNumber, SdSelect, SdTooltipDirective, SdTranslatePipe], changeDetection: ChangeDetectionStrategy.OnPush, host: {
2060
+ class: 'sd-image-editor',
2061
+ '[class.sd-image-editor--compact]': 'compact()',
2062
+ '[class.sd-image-editor--dragging]': 'dragging() !== null',
2063
+ '[attr.data-autoid]': 'autoId()',
2064
+ '[attr.aria-busy]': "status() === 'loading' || status() === 'exporting' ? 'true' : null",
2065
+ '(keydown)': 'onKeydown($event)',
2066
+ }, template: "@let _status = status();\n@let _autoId = autoId();\n@let _interactive = interactive();\n@let _busy = busy();\n@let _edits = edits();\n@let _crop = cropStyle();\n@let _image = imageBox();\n@let _output = outputSize();\n@let _limits = cropLimits();\n@let _max = resizeMax();\n@let _visible = _status === 'ready' || _status === 'exporting';\n@let _error = error();\n@let _locked = ratioLocked();\n@let _fixed = ratioFixed();\n\n<div class=\"toolbar\">\n <div class=\"toolbar-group\" role=\"group\" [attr.aria-label]=\"'core.component.image-editor.group-history' | sdTranslate\">\n <sd-button\n type=\"text\"\n size=\"sm\"\n prefixIcon=\"undo\"\n [tooltip]=\"'core.component.image-editor.undo' | sdTranslate\"\n [disabled]=\"!canUndo()\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-undo' : null\"\n (click)=\"undo()\" />\n <sd-button\n type=\"text\"\n size=\"sm\"\n prefixIcon=\"redo\"\n [tooltip]=\"'core.component.image-editor.redo' | sdTranslate\"\n [disabled]=\"!canRedo()\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-redo' : null\"\n (click)=\"redo()\" />\n <sd-button\n type=\"text\"\n size=\"sm\"\n prefixIcon=\"restart_alt\"\n [tooltip]=\"'core.component.image-editor.reset' | sdTranslate\"\n [disabled]=\"!_interactive || !dirty()\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-reset' : null\"\n (click)=\"reset()\" />\n </div>\n\n <div class=\"toolbar-group\" role=\"group\" [attr.aria-label]=\"'core.component.image-editor.group-transform' | sdTranslate\">\n <sd-button\n type=\"text\"\n size=\"sm\"\n prefixIcon=\"rotate_left\"\n [tooltip]=\"'core.component.image-editor.rotate-left' | sdTranslate\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-rotate-left' : null\"\n (click)=\"operate('rotate-ccw')\" />\n <sd-button\n type=\"text\"\n size=\"sm\"\n prefixIcon=\"rotate_right\"\n [tooltip]=\"'core.component.image-editor.rotate-right' | sdTranslate\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-rotate-right' : null\"\n (click)=\"operate('rotate-cw')\" />\n <sd-button\n type=\"text\"\n size=\"sm\"\n prefixIcon=\"flip\"\n [tooltip]=\"'core.component.image-editor.flip-horizontal' | sdTranslate\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-flip-horizontal' : null\"\n (click)=\"operate('flip-horizontal')\" />\n <sd-button\n class=\"flip-vertical\"\n type=\"text\"\n size=\"sm\"\n prefixIcon=\"flip\"\n [tooltip]=\"'core.component.image-editor.flip-vertical' | sdTranslate\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-flip-vertical' : null\"\n (click)=\"operate('flip-vertical')\" />\n </div>\n\n <div class=\"toolbar-group toolbar-group--zoom\" role=\"group\" [attr.aria-label]=\"'core.component.image-editor.group-zoom' | sdTranslate\">\n <sd-button\n type=\"text\"\n size=\"sm\"\n prefixIcon=\"zoom_out\"\n [tooltip]=\"'core.component.image-editor.zoom-out' | sdTranslate\"\n [disabled]=\"!canZoomOut()\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-zoom-out' : null\"\n (click)=\"zoomOut()\" />\n <span class=\"zoom-value\" [attr.data-autoid]=\"_autoId ? _autoId + '-zoom-value' : null\">{{ _visible ? zoomPercent() + '%' : '\u2013' }}</span>\n <sd-button\n type=\"text\"\n size=\"sm\"\n prefixIcon=\"zoom_in\"\n [tooltip]=\"'core.component.image-editor.zoom-in' | sdTranslate\"\n [disabled]=\"!canZoomIn()\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-zoom-in' : null\"\n (click)=\"zoomIn()\" />\n <sd-button\n type=\"text\"\n size=\"sm\"\n prefixIcon=\"fit_screen\"\n [tooltip]=\"'core.component.image-editor.fit' | sdTranslate\"\n [disabled]=\"!_interactive || isFit()\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-fit' : null\"\n (click)=\"fitToView()\" />\n </div>\n</div>\n\n<div class=\"body\">\n <div\n #stage\n class=\"stage\"\n role=\"group\"\n [id]=\"instanceId + '-stage'\"\n [class.stage--panning]=\"dragging() === 'pan'\"\n [attr.aria-label]=\"'core.component.image-editor.stage' | sdTranslate\"\n [attr.aria-describedby]=\"instanceId + '-hint'\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-stage' : null\"\n (pointerdown)=\"onStagePointerDown($event)\"\n (pointermove)=\"onPointerMove($event)\"\n (pointerup)=\"onPointerUp($event)\"\n (pointercancel)=\"onPointerCancel($event)\"\n (lostpointercapture)=\"onPointerCancel($event)\"\n (wheel)=\"onWheel($event)\">\n @if (_visible && _image) {\n <div\n class=\"checker\"\n aria-hidden=\"true\"\n [style.left.px]=\"_image.x\"\n [style.top.px]=\"_image.y\"\n [style.width.px]=\"_image.width\"\n [style.height.px]=\"_image.height\"></div>\n }\n <!-- why: canvas lu\u00F4n n\u1EB1m trong DOM \u0111\u1EC3 v\u1EBD preview ngay khi decode xong; \u1EA9n khi ch\u01B0a c\u00F3 \u1EA3nh. -->\n <canvas\n #previewCanvas\n class=\"preview\"\n aria-hidden=\"true\"\n [class.preview--hidden]=\"!_visible\"\n [style.width.px]=\"previewSize().width\"\n [style.height.px]=\"previewSize().height\"\n [style.transform]=\"previewTransform()\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-preview' : null\"></canvas>\n\n @if (_visible && _crop && _edits) {\n <div\n #cropBox\n class=\"crop\"\n tabindex=\"0\"\n role=\"group\"\n [attr.aria-roledescription]=\"'core.component.image-editor.crop-role' | sdTranslate\"\n [attr.aria-label]=\"cropLabel()\"\n [attr.aria-describedby]=\"instanceId + '-hint'\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-crop' : null\"\n [style.left.px]=\"_crop.x\"\n [style.top.px]=\"_crop.y\"\n [style.width.px]=\"_crop.width\"\n [style.height.px]=\"_crop.height\"\n (pointerdown)=\"onCropPointerDown($event, null)\"\n (keydown)=\"onCropKeydown($event)\">\n <span class=\"crop-grid\" aria-hidden=\"true\"></span>\n @for (handle of handles; track handle) {\n <span\n class=\"handle\"\n aria-hidden=\"true\"\n [attr.data-handle]=\"handle\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-handle-' + handle : null\"\n (pointerdown)=\"onCropPointerDown($event, handle)\"></span>\n }\n </div>\n }\n\n @switch (_status) {\n @case ('empty') {\n <div class=\"state\">\n <sd-icon name=\"image\" size=\"32px\" />\n <p class=\"state-title\">{{ 'core.component.image-editor.empty' | sdTranslate }}</p>\n <p class=\"state-text\">{{ 'core.component.image-editor.empty-hint' | sdTranslate }}</p>\n </div>\n }\n @case ('loading') {\n <div class=\"state\" role=\"status\">\n <span class=\"spinner\" aria-hidden=\"true\"></span>\n <p class=\"state-title\">{{ 'core.component.image-editor.loading' | sdTranslate }}</p>\n </div>\n }\n @case ('error') {\n <div class=\"state state--error\" role=\"alert\" [attr.data-autoid]=\"_autoId ? _autoId + '-error' : null\">\n <sd-icon name=\"broken_image\" size=\"32px\" />\n <p class=\"state-title\">{{ 'core.component.image-editor.load-error' | sdTranslate }}</p>\n <p class=\"state-text\">{{ _error?.message }}</p>\n </div>\n }\n }\n @if (_busy) {\n <div class=\"busy\" aria-hidden=\"true\"><span class=\"spinner\"></span></div>\n }\n <p class=\"visually-hidden\" [id]=\"instanceId + '-hint'\">{{ 'core.component.image-editor.keyboard-hint' | sdTranslate }}</p>\n <p class=\"visually-hidden\" role=\"status\" [attr.data-autoid]=\"_autoId ? _autoId + '-status' : null\">{{ statusMessage() }}</p>\n </div>\n\n <aside class=\"panel\" [attr.aria-label]=\"'core.component.image-editor.panel' | sdTranslate\" [attr.inert]=\"_visible ? null : ''\">\n <section class=\"section\">\n <h3 class=\"section-title\">\n <sd-icon name=\"crop\" size=\"18px\" />\n {{ 'core.component.image-editor.crop' | sdTranslate }}\n </h3>\n @if (showRatios()) {\n <div class=\"chips\" role=\"group\" [attr.aria-label]=\"'core.component.image-editor.ratio' | sdTranslate\">\n @for (chip of ratioChips(); track chip.key) {\n @let _active = sameRatio(_edits?.aspectRatio ?? null, chip.value);\n <button\n type=\"button\"\n class=\"chip\"\n [class.chip--active]=\"_active\"\n [attr.aria-pressed]=\"_active\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-ratio-' + chip.key : null\"\n (click)=\"selectRatio(chip.value)\">\n {{ chip.label }}\n </button>\n }\n </div>\n }\n @if (_edits && _limits) {\n <div class=\"option-row\">\n <span class=\"prop-label\">\n <span [id]=\"instanceId + '-keep-ratio'\">{{ 'core.component.image-editor.keep-ratio' | sdTranslate }}</span>\n @if (_fixed) {\n @let _fixedText = 'core.component.image-editor.keep-ratio-fixed' | sdTranslate;\n <!-- why: n\u00FAt (kh\u00F4ng ph\u1EA3i span) \u0111\u1EC3 b\u00E0n ph\u00EDm focus \u0111\u01B0\u1EE3c; sdTooltip m\u1EDF khi hover v\u00E0 focus, Escape \u0111\u00F3ng. -->\n <button\n type=\"button\"\n class=\"info\"\n sdTooltipPosition=\"top\"\n [sdTooltip]=\"_fixedText\"\n [attr.aria-label]=\"_fixedText\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-ratio-fixed-info' : null\">\n <sd-icon name=\"info\" size=\"16px\" />\n </button>\n }\n @if (_locked) {\n <span class=\"prop-value\" [attr.data-autoid]=\"_autoId ? _autoId + '-ratio-value' : null\">{{ ratioText() }}</span>\n }\n </span>\n <button\n type=\"button\"\n class=\"lock\"\n [class.lock--on]=\"_locked\"\n [attr.aria-pressed]=\"_locked\"\n [attr.aria-labelledby]=\"instanceId + '-keep-ratio'\"\n [title]=\"'core.component.image-editor.keep-ratio' | sdTranslate\"\n [disabled]=\"!_interactive || _fixed\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-keep-ratio' : null\"\n (click)=\"toggleKeepRatio()\">\n <sd-icon [name]=\"_locked ? 'lock' : 'lock_open'\" size=\"18px\" />\n </button>\n </div>\n <div class=\"fields\">\n <sd-input-number\n #cropX\n size=\"sm\"\n type=\"positive\"\n hideInlineError\n label=\"X\"\n [precision]=\"0\"\n [model]=\"_edits.crop.x\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-crop-x' : null\"\n (sdBlur)=\"onCropField('x', $event, cropX)\"\n (keyupEnter)=\"onCropField('x', cropX.valueModel(), cropX)\" />\n <sd-input-number\n #cropY\n size=\"sm\"\n type=\"positive\"\n hideInlineError\n label=\"Y\"\n [precision]=\"0\"\n [model]=\"_edits.crop.y\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-crop-y' : null\"\n (sdBlur)=\"onCropField('y', $event, cropY)\"\n (keyupEnter)=\"onCropField('y', cropY.valueModel(), cropY)\" />\n <sd-input-number\n #cropW\n size=\"sm\"\n type=\"positive\"\n hideInlineError\n [label]=\"'core.component.image-editor.width' | sdTranslate\"\n [precision]=\"0\"\n [model]=\"_edits.crop.width\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-crop-width' : null\"\n (sdBlur)=\"onCropField('width', $event, cropW)\"\n (keyupEnter)=\"onCropField('width', cropW.valueModel(), cropW)\" />\n <sd-input-number\n #cropH\n size=\"sm\"\n type=\"positive\"\n hideInlineError\n [label]=\"'core.component.image-editor.height' | sdTranslate\"\n [precision]=\"0\"\n [model]=\"_edits.crop.height\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-crop-height' : null\"\n (sdBlur)=\"onCropField('height', $event, cropH)\"\n (keyupEnter)=\"onCropField('height', cropH.valueModel(), cropH)\" />\n </div>\n }\n </section>\n\n <section class=\"section\">\n <h3 class=\"section-title\">\n <sd-icon name=\"photo_size_select_large\" size=\"18px\" />\n {{ 'core.component.image-editor.resize' | sdTranslate }}\n </h3>\n @if (_output && _max) {\n <div class=\"fields\">\n <sd-input-number\n #outW\n size=\"sm\"\n type=\"positive\"\n hideInlineError\n [label]=\"'core.component.image-editor.width' | sdTranslate\"\n [precision]=\"0\"\n [model]=\"_output.width\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-output-width' : null\"\n (sdBlur)=\"onResizeField('width', $event, outW)\"\n (keyupEnter)=\"onResizeField('width', outW.valueModel(), outW)\" />\n <sd-input-number\n #outH\n size=\"sm\"\n type=\"positive\"\n hideInlineError\n [label]=\"'core.component.image-editor.height' | sdTranslate\"\n [precision]=\"0\"\n [model]=\"_output.height\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-output-height' : null\"\n (sdBlur)=\"onResizeField('height', $event, outH)\"\n (keyupEnter)=\"onResizeField('height', outH.valueModel(), outH)\" />\n </div>\n <p class=\"hint\">\n {{ 'core.component.image-editor.resize-max' | sdTranslate: { width: _max.width, height: _max.height } }}\n </p>\n @if (_edits?.resize) {\n <button\n type=\"button\"\n class=\"text-button\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-resize-reset' : null\"\n (click)=\"resetResize()\">\n {{ 'core.component.image-editor.resize-follow-crop' | sdTranslate }}\n </button>\n }\n @if (resizeNotice()) {\n <p class=\"notice\" role=\"status\">{{ resizeNotice() }}</p>\n }\n @if (_output.limited) {\n <p class=\"notice\" [attr.data-autoid]=\"_autoId ? _autoId + '-limited' : null\">\n {{ 'core.component.image-editor.output-limited' | sdTranslate }}\n </p>\n }\n }\n </section>\n\n <section class=\"section\">\n <h3 class=\"section-title\">\n <sd-icon name=\"tune\" size=\"18px\" />\n {{ 'core.component.image-editor.output' | sdTranslate }}\n </h3>\n @if (showFormatPicker()) {\n <sd-select\n size=\"sm\"\n required\n hideInlineError\n valueField=\"format\"\n displayField=\"label\"\n disabledField=\"disabled\"\n [label]=\"'core.component.image-editor.format' | sdTranslate\"\n [items]=\"formatChoices()\"\n [clearable]=\"false\"\n [model]=\"format()\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-format' : null\"\n (sdChange)=\"onFormatChange($event)\" />\n }\n @if (formatUnsupported()) {\n <p class=\"notice notice--error\" role=\"alert\">\n {{ 'core.component.image-editor.error.format-unsupported' | sdTranslate: { format: formatLabel() } }}\n </p>\n }\n @if (lossy()) {\n <label class=\"prop\">\n <span class=\"prop-label prop-label--row\">\n {{ 'core.component.image-editor.quality' | sdTranslate }}\n <span class=\"prop-value\">{{ qualityPercent() }}%</span>\n </span>\n <input\n #qualityInput\n type=\"range\"\n min=\"1\"\n max=\"100\"\n step=\"1\"\n [value]=\"qualityPercent()\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-quality' : null\"\n (input)=\"onQualityInput(qualityInput.value)\" />\n </label>\n }\n @if (showBackground()) {\n <label class=\"prop prop--inline\">\n <span class=\"prop-label\">{{ 'core.component.image-editor.background' | sdTranslate }}</span>\n <input\n #backgroundInput\n type=\"color\"\n [value]=\"backgroundHex()\"\n [disabled]=\"!_interactive\"\n [attr.data-autoid]=\"_autoId ? _autoId + '-background' : null\"\n (input)=\"onBackgroundInput(backgroundInput.value)\" />\n </label>\n <p class=\"hint\">{{ 'core.component.image-editor.background-hint' | sdTranslate }}</p>\n }\n\n @if (exportError(); as exportFailure) {\n <p class=\"notice notice--error\" role=\"alert\" [attr.data-autoid]=\"_autoId ? _autoId + '-export-error' : null\">\n {{ exportFailure.message }}\n </p>\n }\n <dl class=\"meta\">\n <div class=\"meta-row\">\n <dt>{{ 'core.component.image-editor.meta-source' | sdTranslate }}</dt>\n <dd [attr.data-autoid]=\"_autoId ? _autoId + '-meta-source' : null\">{{ sourceSummary() || '\u2013' }}</dd>\n </div>\n <div class=\"meta-row\">\n <dt>{{ 'core.component.image-editor.meta-output' | sdTranslate }}</dt>\n <dd [attr.data-autoid]=\"_autoId ? _autoId + '-meta-output' : null\">{{ outputSummary() || '\u2013' }}</dd>\n </div>\n <div class=\"meta-row\">\n <dt>{{ 'core.component.image-editor.meta-size' | sdTranslate }}</dt>\n <dd [attr.data-autoid]=\"_autoId ? _autoId + '-meta-size' : null\">{{ _visible ? estimateLabel() : '\u2013' }}</dd>\n </div>\n </dl>\n </section>\n </aside>\n</div>\n", styles: [":host{--sd-ie-accent: var(--sd-image-editor-accent, var(--sd-primary, #005cbb));--sd-ie-accent-contrast: var(--sd-image-editor-accent-contrast, var(--sd-primary-contrast, #ffffff));--sd-ie-surface: var(--sd-image-editor-surface, var(--sd-surface, #ffffff));--sd-ie-muted-surface: var( --sd-image-editor-muted-surface, color-mix(in srgb, var(--sd-surface-muted, #e7e8ed) 45%, var(--sd-ie-surface)) );--sd-ie-stage-bg: var(--sd-image-editor-stage-bg, color-mix(in srgb, var(--sd-surface-muted, #e7e8ed) 80%, var(--sd-ie-surface)));--sd-ie-border: var(--sd-image-editor-border, var(--sd-border, #c4c6d0));--sd-ie-text: var(--sd-image-editor-text, var(--sd-text, #1a1b1f));--sd-ie-text-secondary: var(--sd-image-editor-text-secondary, var(--sd-text-secondary, #44474f));--sd-ie-error: var(--sd-image-editor-error, var(--sd-error, #ba1a1a));--sd-ie-warning-bg: var(--sd-image-editor-warning-bg, var(--sd-status-warning-bg, #fff4e5));--sd-ie-warning-fg: var(--sd-image-editor-warning-fg, var(--sd-status-warning-fg, #8a5400));--sd-ie-checker-a: var(--sd-image-editor-checker-light, #ffffff);--sd-ie-checker-b: var(--sd-image-editor-checker-dark, #e3e5ea);--sd-ie-checker-size: var(--sd-image-editor-checker-size, 16px);--sd-ie-shade: var(--sd-image-editor-shade, rgba(0, 0, 0, .55));--sd-ie-frame: var(--sd-image-editor-frame, white);--sd-ie-radius: var(--sd-image-editor-radius, var(--sd-radius-12, 12px));--sd-ie-panel-width: var(--sd-image-editor-panel-width, 288px);position:relative;display:flex;flex-direction:column;height:100%;min-height:520px;overflow:hidden;border:1px solid var(--sd-ie-border);border-radius:var(--sd-ie-radius);background:var(--sd-ie-surface);color:var(--sd-ie-text);font-size:var(--sd-font-size-14, 14px);line-height:var(--sd-line-height-20, 20px)}.toolbar{display:flex;flex-wrap:wrap;align-items:center;gap:var(--sd-space-4, 4px) var(--sd-space-12, 12px);padding:var(--sd-space-8, 8px) var(--sd-space-12, 12px);border-bottom:1px solid var(--sd-ie-border)}.toolbar-group{display:flex;align-items:center;gap:var(--sd-space-2, 2px)}.toolbar-group+.toolbar-group{padding-left:var(--sd-space-12, 12px);border-left:1px solid var(--sd-ie-border)}.toolbar-group--zoom{margin-left:auto}.zoom-value{min-width:48px;font-size:var(--sd-font-size-13, 13px);font-variant-numeric:tabular-nums;text-align:center;color:var(--sd-ie-text-secondary)}.flip-vertical ::ng-deep sd-icon{transform:rotate(90deg)}.body{flex:1 1 auto;display:grid;grid-template-columns:minmax(0,1fr) var(--sd-ie-panel-width);min-height:0}.stage{position:relative;min-width:0;min-height:320px;overflow:hidden;background:var(--sd-ie-stage-bg);cursor:grab;touch-action:none;-webkit-user-select:none;user-select:none}.stage:focus-visible{outline:var(--sd-focus-ring-width, 2px) solid var(--sd-focus-ring-color);outline-offset:calc(-1 * var(--sd-focus-ring-width, 2px))}.stage--panning{cursor:grabbing}.checker{position:absolute;pointer-events:none;background:repeating-conic-gradient(var(--sd-ie-checker-b) 0% 25%,var(--sd-ie-checker-a) 0% 50%) 0 0/var(--sd-ie-checker-size) var(--sd-ie-checker-size)}.preview{position:absolute;top:0;left:0;transform-origin:0 0;pointer-events:none}.preview--hidden{visibility:hidden}.crop{position:absolute;box-sizing:border-box;border:1px solid var(--sd-ie-frame);box-shadow:0 0 0 100vmax var(--sd-ie-shade);cursor:move;touch-action:none}.crop:focus-visible{outline:var(--sd-focus-ring-width, 2px) solid var(--sd-focus-ring-color);outline-offset:var(--sd-focus-ring-offset, 2px)}.crop-grid{position:absolute;inset:0;pointer-events:none;opacity:.55;background:linear-gradient(to right,transparent calc(33.333% - .5px),var(--sd-ie-frame) calc(33.333% - .5px) calc(33.333% + .5px),transparent calc(33.333% + .5px)),linear-gradient(to right,transparent calc(66.666% - .5px),var(--sd-ie-frame) calc(66.666% - .5px) calc(66.666% + .5px),transparent calc(66.666% + .5px)),linear-gradient(to bottom,transparent calc(33.333% - .5px),var(--sd-ie-frame) calc(33.333% - .5px) calc(33.333% + .5px),transparent calc(33.333% + .5px)),linear-gradient(to bottom,transparent calc(66.666% - .5px),var(--sd-ie-frame) calc(66.666% - .5px) calc(66.666% + .5px),transparent calc(66.666% + .5px))}.sd-image-editor--dragging .crop-grid{opacity:.85}.handle{--sd-ie-handle-size: 14px;--sd-ie-handle-hit: 28px;position:absolute;width:var(--sd-ie-handle-hit);height:var(--sd-ie-handle-hit);margin:calc(var(--sd-ie-handle-hit) / -2) 0 0 calc(var(--sd-ie-handle-hit) / -2);touch-action:none}.handle:after{content:\"\";position:absolute;top:50%;left:50%;width:var(--sd-ie-handle-size);height:var(--sd-ie-handle-size);transform:translate(-50%,-50%);box-sizing:border-box;border:2px solid var(--sd-ie-accent);border-radius:var(--sd-radius-2, 2px);background:var(--sd-ie-frame);box-shadow:var(--sd-shadow-xs, 0 1px 2px rgba(0, 0, 0, .3))}.handle[data-handle=n]:after,.handle[data-handle=s]:after{width:22px;height:8px}.handle[data-handle=e]:after,.handle[data-handle=w]:after{width:8px;height:22px}.handle[data-handle=nw]{top:0;left:0;cursor:nwse-resize}.handle[data-handle=n]{top:0;left:50%;cursor:ns-resize}.handle[data-handle=ne]{top:0;left:100%;cursor:nesw-resize}.handle[data-handle=e]{top:50%;left:100%;cursor:ew-resize}.handle[data-handle=se]{top:100%;left:100%;cursor:nwse-resize}.handle[data-handle=s]{top:100%;left:50%;cursor:ns-resize}.handle[data-handle=sw]{top:100%;left:0;cursor:nesw-resize}.handle[data-handle=w]{top:50%;left:0;cursor:ew-resize}@media(pointer:coarse){.handle{--sd-ie-handle-size: 18px;--sd-ie-handle-hit: 40px}}.state{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:var(--sd-space-6, 6px);padding:var(--sd-space-24, 24px);text-align:center;color:var(--sd-ie-text-secondary);cursor:default}.state-title{margin:0;font-weight:var(--sd-font-weight-semibold, 600);color:var(--sd-ie-text)}.state-text{max-width:420px;margin:0;font-size:var(--sd-font-size-13, 13px)}.state--error sd-icon,.state--error .state-title{color:var(--sd-ie-error)}.busy{position:absolute;inset:0;display:grid;place-items:center;background:color-mix(in srgb,var(--sd-ie-surface) 45%,transparent);cursor:progress}.spinner{width:28px;height:28px;border:3px solid color-mix(in srgb,var(--sd-ie-accent) 25%,transparent);border-top-color:var(--sd-ie-accent);border-radius:50%;animation:sd-image-editor-spin .8s linear infinite}@keyframes sd-image-editor-spin{to{transform:rotate(360deg)}}@media(prefers-reduced-motion:reduce){.spinner{animation-duration:2.4s}}.visually-hidden{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}.panel{min-width:0;overflow-y:auto;border-left:1px solid var(--sd-ie-border);background:var(--sd-ie-surface)}.section{display:flex;flex-direction:column;gap:var(--sd-space-8, 8px);padding:var(--sd-space-12, 12px) var(--sd-space-16, 16px)}.section+.section{border-top:1px solid var(--sd-ie-border)}.section-title{display:flex;align-items:center;gap:var(--sd-space-6, 6px);margin:0;font-size:var(--sd-font-size-13, 13px);font-weight:var(--sd-font-weight-semibold, 600);line-height:var(--sd-line-height-18, 18px);color:var(--sd-ie-text)}.section-title sd-icon{color:var(--sd-ie-text-secondary)}.chips{display:flex;flex-wrap:wrap;gap:var(--sd-space-6, 6px)}.chip{min-width:44px;height:28px;padding:0 var(--sd-space-10, 10px);border:1px solid var(--sd-ie-border);border-radius:var(--sd-radius-999, 999px);background:var(--sd-ie-surface);color:var(--sd-ie-text);font:inherit;font-size:var(--sd-font-size-13, 13px);cursor:pointer;transition:background-color var(--sd-duration-fast, .12s) ease,border-color var(--sd-duration-fast, .12s) ease}.chip:hover:not(:disabled){background:var(--sd-ie-muted-surface)}.chip:focus-visible{outline:var(--sd-focus-ring-width, 2px) solid var(--sd-focus-ring-color);outline-offset:var(--sd-focus-ring-offset, 2px)}.chip:disabled{cursor:default;opacity:.55}.chip--active{border-color:var(--sd-ie-accent);background:var(--sd-ie-accent);color:var(--sd-ie-accent-contrast)}.chip--active:hover:not(:disabled){background:var(--sd-ie-accent)}.fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--sd-space-8, 8px)}.fields sd-input-number,.section>sd-select{display:block;min-width:0}.section>sd-select ::ng-deep .mat-mdc-form-field-required-marker{display:none}.prop-label{display:flex;align-items:baseline;gap:var(--sd-space-6, 6px);margin:0;font-size:var(--sd-font-size-12, 12px);font-weight:var(--sd-font-weight-bold, 700);line-height:var(--sd-line-height-18, 18px);color:var(--sd-ie-text-secondary)}.prop-label--row{justify-content:space-between}.prop-value{font-weight:var(--sd-font-weight-regular, 400);font-variant-numeric:tabular-nums;color:var(--sd-ie-text)}.prop{display:flex;flex-direction:column;gap:var(--sd-space-4, 4px);min-width:0}.prop input[type=range]{width:100%;margin:0;accent-color:var(--sd-ie-accent)}.prop input[type=range]:focus-visible{outline:var(--sd-focus-ring-width, 2px) solid var(--sd-focus-ring-color);outline-offset:var(--sd-focus-ring-offset, 2px)}.prop--inline{flex-direction:row;align-items:center;justify-content:space-between}.prop--inline input[type=color]{width:40px;height:28px;padding:0 2px;border:1px solid var(--sd-ie-border);border-radius:var(--sd-radius-6, 6px);background:var(--sd-ie-surface);cursor:pointer}.prop--inline input[type=color]:focus-visible{outline:var(--sd-focus-ring-width, 2px) solid var(--sd-focus-ring-color);outline-offset:var(--sd-focus-ring-offset, 2px)}.option-row{display:flex;align-items:center;justify-content:space-between;gap:var(--sd-space-8, 8px);min-height:32px}.info{display:inline-grid;place-items:center;align-self:center;width:18px;height:18px;padding:0;border:0;border-radius:50%;background:transparent;color:var(--sd-ie-text-secondary);cursor:help}.info:hover{color:var(--sd-ie-text)}.info:focus-visible{outline:var(--sd-focus-ring-width, 2px) solid var(--sd-focus-ring-color);outline-offset:var(--sd-focus-ring-offset, 2px)}.lock{display:grid;place-items:center;width:32px;height:32px;padding:0;border:1px solid transparent;border-radius:var(--sd-radius-6, 6px);background:transparent;color:var(--sd-ie-text-secondary);cursor:pointer}.lock:hover:not(:disabled){background:var(--sd-ie-muted-surface)}.lock:focus-visible{outline:var(--sd-focus-ring-width, 2px) solid var(--sd-focus-ring-color);outline-offset:var(--sd-focus-ring-offset, 2px)}.lock:disabled{cursor:default;opacity:.55}.lock--on{color:var(--sd-ie-accent)}.hint{margin:0;font-size:var(--sd-font-size-12, 12px);line-height:var(--sd-line-height-16, 16px);color:var(--sd-ie-text-secondary)}.notice{margin:0;padding:var(--sd-space-6, 6px) var(--sd-space-8, 8px);border-radius:var(--sd-radius-6, 6px);background:var(--sd-ie-warning-bg);color:var(--sd-ie-warning-fg);font-size:var(--sd-font-size-12, 12px);line-height:var(--sd-line-height-16, 16px)}.notice--error{background:color-mix(in srgb,var(--sd-ie-error) 10%,var(--sd-ie-surface));color:var(--sd-ie-error)}.text-button{align-self:flex-start;padding:0;border:0;background:none;color:var(--sd-ie-accent);font:inherit;font-size:var(--sd-font-size-13, 13px);cursor:pointer}.text-button:hover:not(:disabled){text-decoration:underline}.text-button:focus-visible{outline:var(--sd-focus-ring-width, 2px) solid var(--sd-focus-ring-color);outline-offset:var(--sd-focus-ring-offset, 2px)}.meta{display:flex;flex-direction:column;gap:var(--sd-space-4, 4px);margin:var(--sd-space-4, 4px) 0 0;padding:var(--sd-space-8, 8px) var(--sd-space-10, 10px);border-radius:var(--sd-radius-8, 8px);background:var(--sd-ie-muted-surface)}.meta-row{display:flex;justify-content:space-between;gap:var(--sd-space-8, 8px);font-size:var(--sd-font-size-12, 12px);line-height:var(--sd-line-height-18, 18px)}.meta-row dt{flex:none;font-weight:var(--sd-font-weight-bold, 700);color:var(--sd-ie-text-secondary)}.meta-row dd{margin:0;min-width:0;text-align:right;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}:host(.sd-image-editor--compact){min-height:0}:host(.sd-image-editor--compact) .toolbar{column-gap:var(--sd-space-16, 16px)}:host(.sd-image-editor--compact) .toolbar-group+.toolbar-group{padding-left:0;border-left:0}:host(.sd-image-editor--compact) .toolbar-group--zoom{margin-left:0}:host(.sd-image-editor--compact) .body{display:flex;flex-direction:column;overflow-y:auto}:host(.sd-image-editor--compact) .stage{flex:none;height:clamp(240px,50vh,480px);min-height:0}:host(.sd-image-editor--compact) .panel{flex:none;overflow:visible;border-top:1px solid var(--sd-ie-border);border-left:0}\n"] }]
2067
+ }], ctorParameters: () => [], propDecorators: { source: [{ type: i0.Input, args: [{ isSignal: true, alias: "source", required: false }] }], option: [{ type: i0.Input, args: [{ isSignal: true, alias: "option", required: false }] }], failed: [{ type: i0.Output, args: ["failed"] }], stage: [{ type: i0.ViewChild, args: ['stage', { isSignal: true }] }], previewCanvas: [{ type: i0.ViewChild, args: ['previewCanvas', { isSignal: true }] }], cropBox: [{ type: i0.ViewChild, args: ['cropBox', { isSignal: true }] }] } });
2068
+ function positive(value) {
2069
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;
2070
+ }
2071
+ function round(value, digits) {
2072
+ const factor = 10 ** digits;
2073
+ return Math.round(value * factor) / factor;
2074
+ }
2075
+ function isEditableTarget(target) {
2076
+ if (!target || typeof target.tagName !== 'string')
2077
+ return false;
2078
+ const element = target;
2079
+ const tag = element.tagName;
2080
+ return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || element.isContentEditable;
2081
+ }
2082
+
2083
+ /**
2084
+ * Generated bundle index. Do not edit.
2085
+ */
2086
+
2087
+ export { SdImageEditor };
2088
+ //# sourceMappingURL=sdcorejs-angular-components-image-editor.mjs.map