@umituz/web-canvas 1.0.6 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +33 -0
  2. package/dist/CanvasConfig-HFgH7irb.d.mts +310 -0
  3. package/dist/CanvasConfig-HFgH7irb.d.ts +310 -0
  4. package/dist/application/index.d.mts +78 -0
  5. package/dist/application/index.d.ts +78 -0
  6. package/dist/application/index.js +1146 -0
  7. package/dist/application/index.mjs +11 -0
  8. package/dist/chunk-DNKRSL6D.mjs +358 -0
  9. package/dist/chunk-HJ24NSQA.mjs +777 -0
  10. package/dist/chunk-MC6PNV2F.mjs +34 -0
  11. package/dist/chunk-TZGTTYTZ.mjs +0 -0
  12. package/dist/chunk-UOGTEMIJ.mjs +712 -0
  13. package/dist/chunk-Z6IB4BQV.mjs +31 -0
  14. package/dist/domain/config/index.d.mts +87 -0
  15. package/dist/domain/config/index.d.ts +87 -0
  16. package/dist/domain/config/index.js +92 -0
  17. package/dist/domain/config/index.mjs +15 -0
  18. package/dist/domain/index.d.mts +45 -0
  19. package/dist/domain/index.d.ts +45 -0
  20. package/dist/domain/index.js +137 -0
  21. package/dist/domain/index.mjs +55 -0
  22. package/dist/index.d.mts +7 -0
  23. package/dist/index.d.ts +7 -0
  24. package/dist/index.js +1927 -0
  25. package/dist/index.mjs +40 -0
  26. package/dist/infrastructure/index.d.mts +198 -0
  27. package/dist/infrastructure/index.d.ts +198 -0
  28. package/dist/infrastructure/index.js +765 -0
  29. package/dist/infrastructure/index.mjs +13 -0
  30. package/dist/presentation/index.d.mts +145 -0
  31. package/dist/presentation/index.d.ts +145 -0
  32. package/dist/presentation/index.js +1911 -0
  33. package/dist/presentation/index.mjs +16 -0
  34. package/dist/report.types-DWDnprBx.d.mts +76 -0
  35. package/dist/report.types-DWDnprBx.d.ts +76 -0
  36. package/package.json +8 -2
  37. package/src/domain/types/freehand.types.ts +42 -0
  38. package/src/domain/types/index.ts +1 -0
  39. package/src/index.ts +10 -0
  40. package/src/presentation/hooks/useFreehandCanvas.ts +244 -0
  41. package/src/presentation/index.ts +1 -0
@@ -0,0 +1,1911 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/presentation/index.ts
31
+ var presentation_exports = {};
32
+ __export(presentation_exports, {
33
+ useCanvasExport: () => useCanvasExport,
34
+ useFreehandCanvas: () => useFreehandCanvas,
35
+ useReportExport: () => useReportExport,
36
+ useScreenshotStudio: () => useScreenshotStudio
37
+ });
38
+ module.exports = __toCommonJS(presentation_exports);
39
+
40
+ // src/presentation/hooks/useScreenshotStudio.ts
41
+ var import_react = require("react");
42
+
43
+ // src/domain/config/ScreenshotStudioConfig.ts
44
+ var DEFAULT_SCREENSHOT_STUDIO_CONFIG = {
45
+ canvas: {
46
+ defaultFormat: "png",
47
+ defaultQuality: 0.9,
48
+ scale: 2,
49
+ useCORS: true
50
+ },
51
+ device: {
52
+ devices: ["iphone-15-pro"],
53
+ defaultDevice: "iphone-15-pro",
54
+ showFrame: true,
55
+ frameColor: "#1f2937",
56
+ frameThickness: 8
57
+ },
58
+ export: {
59
+ includeMetadata: true,
60
+ folderStructure: "by-language",
61
+ defaultFormat: "png"
62
+ },
63
+ ai: {
64
+ enabled: true,
65
+ provider: "gemini"
66
+ },
67
+ languages: ["en-US", "tr-TR", "de-DE", "fr-FR", "es-ES", "ja-JP"],
68
+ defaultLanguage: "en-US"
69
+ };
70
+
71
+ // src/domain/config/CanvasConfig.ts
72
+ var DEFAULT_CANVAS_CONFIG = {
73
+ defaultFormat: "png",
74
+ defaultQuality: 0.9,
75
+ maxDimension: 4096,
76
+ scale: 2,
77
+ backgroundColor: "#ffffff",
78
+ useCORS: true
79
+ };
80
+
81
+ // src/infrastructure/renderers/CanvasRenderer.ts
82
+ var CanvasRenderer = class {
83
+ constructor(config = DEFAULT_CANVAS_CONFIG) {
84
+ this.config = { ...DEFAULT_CANVAS_CONFIG, ...config };
85
+ this.imageCache = /* @__PURE__ */ new Map();
86
+ }
87
+ /**
88
+ * Create a new canvas element
89
+ */
90
+ createCanvas(dimensions) {
91
+ const canvas = document.createElement("canvas");
92
+ canvas.width = dimensions.width;
93
+ canvas.height = dimensions.height;
94
+ return canvas;
95
+ }
96
+ /**
97
+ * Get canvas 2D context
98
+ */
99
+ getContext(canvas) {
100
+ return canvas.getContext("2d");
101
+ }
102
+ /**
103
+ * Apply context configuration
104
+ */
105
+ configureContext(ctx, config) {
106
+ if (config.fillStyle !== void 0) {
107
+ ctx.fillStyle = config.fillStyle;
108
+ }
109
+ if (config.strokeStyle !== void 0) {
110
+ ctx.strokeStyle = config.strokeStyle;
111
+ }
112
+ if (config.lineWidth !== void 0) {
113
+ ctx.lineWidth = config.lineWidth;
114
+ }
115
+ if (config.lineCap !== void 0) {
116
+ ctx.lineCap = config.lineCap;
117
+ }
118
+ if (config.lineJoin !== void 0) {
119
+ ctx.lineJoin = config.lineJoin;
120
+ }
121
+ if (config.globalAlpha !== void 0) {
122
+ ctx.globalAlpha = config.globalAlpha;
123
+ }
124
+ if (config.font !== void 0) {
125
+ ctx.font = config.font;
126
+ }
127
+ if (config.textAlign !== void 0) {
128
+ ctx.textAlign = config.textAlign;
129
+ }
130
+ if (config.textBaseline !== void 0) {
131
+ ctx.textBaseline = config.textBaseline;
132
+ }
133
+ }
134
+ /**
135
+ * Clear canvas
136
+ */
137
+ clearCanvas(ctx, dimensions) {
138
+ ctx.clearRect(0, 0, dimensions.width, dimensions.height);
139
+ }
140
+ /**
141
+ * Fill rectangle
142
+ */
143
+ fillRect(ctx, x, y, width, height, color) {
144
+ if (color) {
145
+ ctx.fillStyle = color;
146
+ }
147
+ ctx.fillRect(x, y, width, height);
148
+ }
149
+ /**
150
+ * Stroke rectangle
151
+ */
152
+ strokeRect(ctx, x, y, width, height, color, lineWidth) {
153
+ if (color) {
154
+ ctx.strokeStyle = color;
155
+ }
156
+ if (lineWidth !== void 0) {
157
+ ctx.lineWidth = lineWidth;
158
+ }
159
+ ctx.strokeRect(x, y, width, height);
160
+ }
161
+ /**
162
+ * Draw text
163
+ */
164
+ drawText(ctx, text, x, y, config) {
165
+ if (config) {
166
+ this.configureContext(ctx, config);
167
+ }
168
+ ctx.fillText(text, x, y);
169
+ }
170
+ /**
171
+ * Draw image
172
+ */
173
+ async drawImage(ctx, imageSource, x, y, width, height) {
174
+ let img;
175
+ if (typeof imageSource === "string") {
176
+ img = await this.loadImage(imageSource);
177
+ } else {
178
+ img = imageSource;
179
+ }
180
+ if (width && height) {
181
+ ctx.drawImage(img, x, y, width, height);
182
+ } else {
183
+ ctx.drawImage(img, x, y);
184
+ }
185
+ }
186
+ /**
187
+ * Load image from URL with caching
188
+ */
189
+ loadImage(url) {
190
+ if (this.imageCache.has(url)) {
191
+ return Promise.resolve(this.imageCache.get(url));
192
+ }
193
+ return new Promise((resolve, reject) => {
194
+ const img = new Image();
195
+ if (this.config.useCORS) {
196
+ img.crossOrigin = "anonymous";
197
+ }
198
+ img.onload = () => {
199
+ this.imageCache.set(url, img);
200
+ resolve(img);
201
+ };
202
+ img.onerror = () => reject(new Error(`Failed to load image: ${url}`));
203
+ img.src = url;
204
+ });
205
+ }
206
+ /**
207
+ * Clear image cache to free memory
208
+ */
209
+ clearImageCache() {
210
+ this.imageCache.clear();
211
+ }
212
+ /**
213
+ * Get cache size for monitoring
214
+ */
215
+ getCacheSize() {
216
+ return this.imageCache.size;
217
+ }
218
+ /**
219
+ * Create gradient
220
+ */
221
+ createLinearGradient(ctx, x1, y1, x2, y2, colorStops) {
222
+ const gradient = ctx.createLinearGradient(x1, y1, x2, y2);
223
+ colorStops.forEach(({ offset, color }) => {
224
+ gradient.addColorStop(offset, color);
225
+ });
226
+ return gradient;
227
+ }
228
+ /**
229
+ * Export canvas to blob
230
+ */
231
+ async exportToBlob(canvas, options = {}) {
232
+ const format = options.format || this.config.defaultFormat;
233
+ const quality = options.quality || this.config.defaultQuality;
234
+ const scale = options.scale || this.config.scale;
235
+ const scaledCanvas = (scale || 1) !== 1 ? this.scaleCanvas(canvas, scale || 1) : canvas;
236
+ const mimeType = `image/${format || "png"}`;
237
+ const blob = await new Promise((resolve) => {
238
+ scaledCanvas.toBlob(
239
+ (result) => resolve(result),
240
+ mimeType,
241
+ quality
242
+ );
243
+ });
244
+ if (!blob) {
245
+ throw new Error("Failed to export canvas to blob");
246
+ }
247
+ const url = URL.createObjectURL(blob);
248
+ return {
249
+ blob,
250
+ url,
251
+ dimensions: {
252
+ width: scaledCanvas.width,
253
+ height: scaledCanvas.height
254
+ },
255
+ format: format || "png",
256
+ size: blob.size
257
+ };
258
+ }
259
+ /**
260
+ * Export canvas to data URL
261
+ */
262
+ exportToDataURL(canvas, format, quality) {
263
+ const mimeType = format || `image/${this.config.defaultFormat}`;
264
+ const q = quality || this.config.defaultQuality;
265
+ return canvas.toDataURL(mimeType, q);
266
+ }
267
+ /**
268
+ * Scale canvas
269
+ */
270
+ scaleCanvas(canvas, scale) {
271
+ const scaled = document.createElement("canvas");
272
+ scaled.width = canvas.width * scale;
273
+ scaled.height = canvas.height * scale;
274
+ const ctx = scaled.getContext("2d");
275
+ if (ctx) {
276
+ ctx.imageSmoothingEnabled = true;
277
+ ctx.imageSmoothingQuality = "high";
278
+ ctx.drawImage(canvas, 0, 0, scaled.width, scaled.height);
279
+ }
280
+ return scaled;
281
+ }
282
+ /**
283
+ * Clone canvas
284
+ */
285
+ cloneCanvas(canvas) {
286
+ const clone = document.createElement("canvas");
287
+ clone.width = canvas.width;
288
+ clone.height = canvas.height;
289
+ const ctx = clone.getContext("2d");
290
+ if (ctx) {
291
+ ctx.drawImage(canvas, 0, 0);
292
+ }
293
+ return clone;
294
+ }
295
+ };
296
+
297
+ // src/infrastructure/renderers/PatternRenderer.ts
298
+ var PatternRenderer = class {
299
+ constructor() {
300
+ this.patternCanvasCache = /* @__PURE__ */ new Map();
301
+ this.MAX_CACHE_SIZE = 10;
302
+ }
303
+ /**
304
+ * Render pattern on canvas
305
+ */
306
+ renderPattern(ctx, pattern, dimensions, color = "#000000") {
307
+ if (pattern === "none") return;
308
+ ctx.save();
309
+ ctx.globalAlpha = 0.1;
310
+ switch (pattern) {
311
+ case "dots":
312
+ this.renderDotPattern(ctx, dimensions, color);
313
+ break;
314
+ case "grid":
315
+ this.renderGridPattern(ctx, dimensions, color);
316
+ break;
317
+ case "lines":
318
+ this.renderLinePattern(ctx, dimensions, color);
319
+ break;
320
+ case "waves":
321
+ this.renderWavePattern(ctx, dimensions, color);
322
+ break;
323
+ case "checkers":
324
+ this.renderCheckerPattern(ctx, dimensions, color);
325
+ break;
326
+ }
327
+ ctx.restore();
328
+ }
329
+ /**
330
+ * Clear pattern cache to free memory
331
+ */
332
+ clearCache() {
333
+ this.patternCanvasCache.clear();
334
+ }
335
+ /**
336
+ * Render dot pattern - optimized with batch rendering
337
+ */
338
+ renderDotPattern(ctx, dimensions, color) {
339
+ ctx.fillStyle = color;
340
+ const spacing = 30;
341
+ const radius = 2;
342
+ ctx.beginPath();
343
+ for (let x = spacing; x < dimensions.width; x += spacing) {
344
+ for (let y = spacing; y < dimensions.height; y += spacing) {
345
+ ctx.moveTo(x + radius, y);
346
+ ctx.arc(x, y, radius, 0, Math.PI * 2);
347
+ }
348
+ }
349
+ ctx.fill();
350
+ }
351
+ /**
352
+ * Render grid pattern - optimized with single path
353
+ */
354
+ renderGridPattern(ctx, dimensions, color) {
355
+ ctx.strokeStyle = color;
356
+ ctx.lineWidth = 1;
357
+ const spacing = 30;
358
+ ctx.beginPath();
359
+ for (let x = 0; x <= dimensions.width; x += spacing) {
360
+ ctx.moveTo(x, 0);
361
+ ctx.lineTo(x, dimensions.height);
362
+ }
363
+ for (let y = 0; y <= dimensions.height; y += spacing) {
364
+ ctx.moveTo(0, y);
365
+ ctx.lineTo(dimensions.width, y);
366
+ }
367
+ ctx.stroke();
368
+ }
369
+ /**
370
+ * Render line pattern - optimized with single path
371
+ */
372
+ renderLinePattern(ctx, dimensions, color) {
373
+ ctx.strokeStyle = color;
374
+ ctx.lineWidth = 2;
375
+ const spacing = 20;
376
+ ctx.beginPath();
377
+ for (let y = spacing; y < dimensions.height; y += spacing) {
378
+ ctx.moveTo(0, y);
379
+ ctx.lineTo(dimensions.width, y);
380
+ }
381
+ ctx.stroke();
382
+ }
383
+ /**
384
+ * Render wave pattern - optimized with pre-calculated values
385
+ */
386
+ renderWavePattern(ctx, dimensions, color) {
387
+ ctx.strokeStyle = color;
388
+ ctx.lineWidth = 2;
389
+ const amplitude = 10;
390
+ const frequency = 0.1;
391
+ const spacing = 40;
392
+ const step = 5;
393
+ for (let y = spacing; y < dimensions.height; y += spacing) {
394
+ ctx.beginPath();
395
+ const startX = 0;
396
+ const startY = y + Math.sin(startX * frequency) * amplitude;
397
+ ctx.moveTo(startX, startY);
398
+ for (let x = step; x <= dimensions.width; x += step) {
399
+ const waveY = y + Math.sin(x * frequency) * amplitude;
400
+ ctx.lineTo(x, waveY);
401
+ }
402
+ ctx.stroke();
403
+ }
404
+ }
405
+ /**
406
+ * Render checker pattern
407
+ */
408
+ renderCheckerPattern(ctx, dimensions, color) {
409
+ ctx.fillStyle = color;
410
+ const size = 20;
411
+ for (let x = 0; x < dimensions.width; x += size * 2) {
412
+ for (let y = 0; y < dimensions.height; y += size * 2) {
413
+ ctx.fillRect(x, y, size, size);
414
+ ctx.fillRect(x + size, y + size, size, size);
415
+ }
416
+ }
417
+ }
418
+ };
419
+
420
+ // src/domain/config/DeviceConfig.ts
421
+ var DEVICE_DIMENSIONS = {
422
+ "iphone-15-pro": { width: 1290, height: 2796 },
423
+ "iphone-15": { width: 1179, height: 2556 },
424
+ "iphone-se": { width: 1080, height: 2340 },
425
+ "ipad-pro": { width: 2048, height: 2732 },
426
+ "ipad": { width: 1620, height: 2160 },
427
+ "android-phone": { width: 1440, height: 3120 },
428
+ "android-tablet": { width: 2e3, height: 2200 },
429
+ "desktop": { width: 1920, height: 1080 }
430
+ };
431
+ var DEFAULT_DEVICE_CONFIG = {
432
+ devices: Object.keys(DEVICE_DIMENSIONS),
433
+ defaultDevice: "iphone-15-pro",
434
+ showFrame: true,
435
+ frameColor: "#1f2937",
436
+ frameThickness: 8
437
+ };
438
+
439
+ // src/infrastructure/services/DeviceConfigService.ts
440
+ var DeviceConfigService = class _DeviceConfigService {
441
+ constructor() {
442
+ this.phonesCache = null;
443
+ this.tabletsCache = null;
444
+ this.allDevicesCache = null;
445
+ this.devices = /* @__PURE__ */ new Map();
446
+ this.initializeDevices();
447
+ }
448
+ static getInstance() {
449
+ if (!_DeviceConfigService.instance) {
450
+ _DeviceConfigService.instance = new _DeviceConfigService();
451
+ }
452
+ return _DeviceConfigService.instance;
453
+ }
454
+ initializeDevices() {
455
+ const deviceConfigs = [
456
+ {
457
+ name: "iPhone 15 Pro",
458
+ dimensions: { width: 1290, height: 2796, scale: 3 },
459
+ isPhone: true,
460
+ hasNotch: true,
461
+ cornerRadius: 20,
462
+ frameThickness: 8
463
+ },
464
+ {
465
+ name: "iPhone 15",
466
+ dimensions: { width: 1179, height: 2556, scale: 3 },
467
+ isPhone: true,
468
+ hasNotch: true,
469
+ cornerRadius: 20,
470
+ frameThickness: 8
471
+ },
472
+ {
473
+ name: "iPhone SE",
474
+ dimensions: { width: 1080, height: 2340, scale: 3 },
475
+ isPhone: true,
476
+ hasNotch: false,
477
+ cornerRadius: 16,
478
+ frameThickness: 6
479
+ },
480
+ {
481
+ name: "iPad Pro",
482
+ dimensions: { width: 2048, height: 2732, scale: 2 },
483
+ isTablet: true,
484
+ hasNotch: false,
485
+ cornerRadius: 24,
486
+ frameThickness: 10
487
+ },
488
+ {
489
+ name: "iPad",
490
+ dimensions: { width: 1620, height: 2160, scale: 2 },
491
+ isTablet: true,
492
+ hasNotch: false,
493
+ cornerRadius: 20,
494
+ frameThickness: 10
495
+ },
496
+ {
497
+ name: "Android Phone",
498
+ dimensions: { width: 1440, height: 3120, scale: 3 },
499
+ isPhone: true,
500
+ hasNotch: false,
501
+ cornerRadius: 24,
502
+ frameThickness: 8
503
+ },
504
+ {
505
+ name: "Android Tablet",
506
+ dimensions: { width: 2e3, height: 2200, scale: 2 },
507
+ isTablet: true,
508
+ hasNotch: false,
509
+ cornerRadius: 24,
510
+ frameThickness: 10
511
+ },
512
+ {
513
+ name: "Desktop",
514
+ dimensions: { width: 1920, height: 1080, scale: 1 },
515
+ isPhone: false,
516
+ isTablet: false,
517
+ hasNotch: false,
518
+ cornerRadius: 0,
519
+ frameThickness: 0
520
+ }
521
+ ];
522
+ Object.entries(DEVICE_DIMENSIONS).forEach(([type, dimensions]) => {
523
+ const deviceType = type;
524
+ const config = deviceConfigs.find((_, index) => {
525
+ const types = Object.keys(DEVICE_DIMENSIONS);
526
+ return types[index] === type;
527
+ });
528
+ if (config) {
529
+ this.devices.set(deviceType, {
530
+ type: deviceType,
531
+ ...config,
532
+ dimensions
533
+ });
534
+ }
535
+ });
536
+ }
537
+ getDeviceConfig(deviceType) {
538
+ return this.devices.get(deviceType);
539
+ }
540
+ getAllDevices() {
541
+ if (!this.allDevicesCache) {
542
+ this.allDevicesCache = Array.from(this.devices.values());
543
+ }
544
+ return this.allDevicesCache;
545
+ }
546
+ getPhones() {
547
+ if (!this.phonesCache) {
548
+ this.phonesCache = this.getAllDevices().filter((d) => d.isPhone);
549
+ }
550
+ return this.phonesCache;
551
+ }
552
+ getTablets() {
553
+ if (!this.tabletsCache) {
554
+ this.tabletsCache = this.getAllDevices().filter((d) => d.isTablet);
555
+ }
556
+ return this.tabletsCache;
557
+ }
558
+ isPhone(deviceType) {
559
+ const config = this.getDeviceConfig(deviceType);
560
+ return config?.isPhone || false;
561
+ }
562
+ isTablet(deviceType) {
563
+ const config = this.getDeviceConfig(deviceType);
564
+ return config?.isTablet || false;
565
+ }
566
+ hasNotch(deviceType) {
567
+ const config = this.getDeviceConfig(deviceType);
568
+ return config?.hasNotch || false;
569
+ }
570
+ };
571
+
572
+ // src/infrastructure/renderers/ScreenshotRenderer.ts
573
+ var ScreenshotRenderer = class {
574
+ constructor() {
575
+ this.renderCache = /* @__PURE__ */ new Map();
576
+ this.MAX_CACHE_SIZE = 5;
577
+ this.canvasRenderer = new CanvasRenderer();
578
+ this.patternRenderer = new PatternRenderer();
579
+ this.deviceConfigService = DeviceConfigService.getInstance();
580
+ }
581
+ /**
582
+ * Clear render cache to free memory
583
+ */
584
+ clearCache() {
585
+ this.renderCache.clear();
586
+ this.canvasRenderer.clearImageCache?.();
587
+ this.patternRenderer.clearCache?.();
588
+ }
589
+ /**
590
+ * Render device frame
591
+ */
592
+ renderDeviceFrame(ctx, dimensions, deviceType, frameStyle, frameColor) {
593
+ const deviceConfig = this.deviceConfigService.getDeviceConfig(deviceType);
594
+ if (!deviceConfig) return;
595
+ if (frameStyle === "none") return;
596
+ const isPhone = this.deviceConfigService.isPhone(deviceType);
597
+ const isTablet = this.deviceConfigService.isTablet(deviceType);
598
+ if (!isPhone && !isTablet) return;
599
+ const frameThickness = deviceConfig.frameThickness || 8;
600
+ if (frameStyle === "realistic") {
601
+ this.renderRealisticFrame(ctx, dimensions, frameColor, frameThickness);
602
+ if (isPhone && this.deviceConfigService.hasNotch(deviceType)) {
603
+ this.renderNotch(ctx, dimensions);
604
+ }
605
+ } else if (frameStyle === "minimal") {
606
+ this.renderMinimalFrame(ctx, dimensions, frameColor, frameThickness);
607
+ }
608
+ }
609
+ /**
610
+ * Render realistic device frame
611
+ */
612
+ renderRealisticFrame(ctx, dimensions, color, thickness) {
613
+ ctx.strokeStyle = color;
614
+ ctx.lineWidth = thickness;
615
+ ctx.strokeRect(
616
+ thickness / 2,
617
+ thickness / 2,
618
+ dimensions.width - thickness,
619
+ dimensions.height - thickness
620
+ );
621
+ }
622
+ /**
623
+ * Render minimal device frame
624
+ */
625
+ renderMinimalFrame(ctx, dimensions, color, thickness) {
626
+ ctx.strokeStyle = color;
627
+ ctx.lineWidth = thickness;
628
+ ctx.strokeRect(0, 0, dimensions.width, dimensions.height);
629
+ }
630
+ /**
631
+ * Render device notch
632
+ */
633
+ renderNotch(ctx, dimensions) {
634
+ ctx.fillStyle = "#1f2937";
635
+ ctx.beginPath();
636
+ ctx.arc(dimensions.width / 2, 20, 10, 0, Math.PI * 2);
637
+ ctx.fill();
638
+ }
639
+ /**
640
+ * Render background - optimized
641
+ */
642
+ renderBackground(ctx, design, dimensions) {
643
+ if (design.backgroundGradientEnd) {
644
+ const gradient = this.canvasRenderer.createLinearGradient(
645
+ ctx,
646
+ 0,
647
+ 0,
648
+ dimensions.width,
649
+ dimensions.height,
650
+ [
651
+ { offset: 0, color: design.backgroundColor },
652
+ { offset: 1, color: design.backgroundGradientEnd }
653
+ ]
654
+ );
655
+ ctx.fillStyle = gradient;
656
+ } else {
657
+ ctx.fillStyle = design.backgroundColor;
658
+ }
659
+ ctx.fillRect(0, 0, dimensions.width, dimensions.height);
660
+ if (design.backgroundPattern && design.backgroundPattern !== "none") {
661
+ this.patternRenderer.renderPattern(
662
+ ctx,
663
+ design.backgroundPattern,
664
+ dimensions
665
+ );
666
+ }
667
+ }
668
+ /**
669
+ * Render text content
670
+ */
671
+ renderTextContent(ctx, content, design, dimensions) {
672
+ const titleConfig = {
673
+ fillStyle: design.textColor,
674
+ font: `bold ${design.titleFontSize}px ${design.fontFamily}`,
675
+ textAlign: design.textAlign
676
+ };
677
+ const subtitleConfig = {
678
+ fillStyle: design.textColor,
679
+ font: `${design.subtitleFontSize}px ${design.fontFamily}`,
680
+ textAlign: design.textAlign
681
+ };
682
+ const titleY = design.layout === "text-bottom" ? dimensions.height - 150 : 100 + (design.offsetY || 0);
683
+ this.canvasRenderer.drawText(
684
+ ctx,
685
+ this.formatText(content.title, design.textCase),
686
+ dimensions.width / 2,
687
+ titleY,
688
+ titleConfig
689
+ );
690
+ const subtitleY = titleY + design.titleFontSize + (design.gap || 20);
691
+ this.canvasRenderer.drawText(
692
+ ctx,
693
+ this.formatText(content.subtitle, design.textCase),
694
+ dimensions.width / 2,
695
+ subtitleY,
696
+ subtitleConfig
697
+ );
698
+ }
699
+ /**
700
+ * Format text case
701
+ */
702
+ formatText(text, textCase = "none") {
703
+ switch (textCase) {
704
+ case "uppercase":
705
+ return text.toUpperCase();
706
+ case "lowercase":
707
+ return text.toLowerCase();
708
+ default:
709
+ return text;
710
+ }
711
+ }
712
+ /**
713
+ * Render screenshot image
714
+ */
715
+ async renderScreenshotImage(ctx, imageUrl, design, dimensions) {
716
+ if (!imageUrl) return;
717
+ const deviceConfig = this.deviceConfigService.getDeviceConfig(
718
+ design.deviceType
719
+ );
720
+ if (!deviceConfig) return;
721
+ const frameThickness = deviceConfig.frameThickness || 8;
722
+ const padding = 60 + frameThickness;
723
+ const screenshotWidth = dimensions.width - padding * 2;
724
+ const screenshotHeight = dimensions.height - padding * 2;
725
+ try {
726
+ await this.canvasRenderer.drawImage(
727
+ ctx,
728
+ imageUrl,
729
+ padding,
730
+ padding,
731
+ screenshotWidth,
732
+ screenshotHeight
733
+ );
734
+ } catch (error) {
735
+ console.error("Failed to render screenshot image:", error);
736
+ }
737
+ }
738
+ /**
739
+ * Render complete screenshot
740
+ */
741
+ async renderDesignedScreenshot(content, design) {
742
+ const deviceConfig = this.deviceConfigService.getDeviceConfig(design.deviceType);
743
+ if (!deviceConfig) {
744
+ throw new Error(`Device config not found: ${design.deviceType}`);
745
+ }
746
+ const dimensions = deviceConfig.dimensions;
747
+ const canvas = this.canvasRenderer.createCanvas(dimensions);
748
+ const ctx = canvas.getContext("2d");
749
+ if (!ctx) {
750
+ throw new Error("Failed to get canvas context");
751
+ }
752
+ this.renderBackground(ctx, design, dimensions);
753
+ if (content.screenshot) {
754
+ await this.renderScreenshotImage(ctx, content.screenshot, design, dimensions);
755
+ }
756
+ this.renderTextContent(ctx, content, design, dimensions);
757
+ this.renderDeviceFrame(
758
+ ctx,
759
+ dimensions,
760
+ design.deviceType,
761
+ design.frameStyle,
762
+ design.deviceColor
763
+ );
764
+ return canvas;
765
+ }
766
+ /**
767
+ * Render placeholder content
768
+ */
769
+ renderPlaceholderContent(ctx, dimensions, deviceType) {
770
+ this.canvasRenderer.fillRect(ctx, 0, 0, dimensions.width, dimensions.height, "#ffffff");
771
+ this.canvasRenderer.fillRect(ctx, 0, 0, dimensions.width, 60, "#f3f4f6");
772
+ this.canvasRenderer.fillRect(
773
+ ctx,
774
+ 0,
775
+ dimensions.height - 80,
776
+ dimensions.width,
777
+ 80,
778
+ "#f3f4f6"
779
+ );
780
+ ctx.fillStyle = "#e5e7eb";
781
+ for (let i = 0; i < 5; i++) {
782
+ const y = 80 + i * 120;
783
+ const height = Math.min(100, dimensions.height - y - 100);
784
+ if (y < dimensions.height - 100) {
785
+ this.canvasRenderer.fillRect(ctx, 20, y, dimensions.width - 40, height);
786
+ }
787
+ }
788
+ const deviceConfig = this.deviceConfigService.getDeviceConfig(deviceType);
789
+ if (deviceConfig) {
790
+ this.renderDeviceFrame(
791
+ ctx,
792
+ dimensions,
793
+ deviceType,
794
+ "realistic",
795
+ "#1f2937"
796
+ );
797
+ }
798
+ }
799
+ };
800
+
801
+ // src/application/services/ScreenshotStudioService.ts
802
+ var ScreenshotStudioService = class {
803
+ constructor(config) {
804
+ this.config = {
805
+ ...DEFAULT_SCREENSHOT_STUDIO_CONFIG,
806
+ ...config
807
+ };
808
+ this.renderer = new ScreenshotRenderer();
809
+ }
810
+ /**
811
+ * Generate screenshot
812
+ */
813
+ async generateScreenshot(options) {
814
+ const deviceConfig = this.config.device?.devices.find(
815
+ (d) => d === options.deviceType
816
+ );
817
+ if (!deviceConfig) {
818
+ throw new Error(`Device configuration not found for ${options.deviceType}`);
819
+ }
820
+ const canvas = this.renderer["canvasRenderer"].createCanvas(
821
+ options.customDimensions || { width: 1290, height: 2796 }
822
+ );
823
+ const ctx = canvas.getContext("2d");
824
+ if (!ctx) {
825
+ throw new Error("Failed to get canvas context");
826
+ }
827
+ this.renderer["renderPlaceholderContent"](
828
+ ctx,
829
+ { width: canvas.width, height: canvas.height },
830
+ options.deviceType
831
+ );
832
+ const blob = await this.renderer["canvasRenderer"].exportToBlob(canvas, {
833
+ format: options.format || this.config.export?.defaultFormat || "png",
834
+ quality: options.quality || this.config.canvas?.defaultQuality || 0.9
835
+ });
836
+ return {
837
+ id: this.generateId(),
838
+ deviceType: options.deviceType,
839
+ dimensions: { width: canvas.width, height: canvas.height },
840
+ format: options.format || this.config.export?.defaultFormat || "png",
841
+ timestamp: /* @__PURE__ */ new Date(),
842
+ fileSize: blob.blob.size,
843
+ url: blob.url
844
+ };
845
+ }
846
+ /**
847
+ * Generate batch screenshots
848
+ */
849
+ async generateBatchScreenshots(deviceTypes) {
850
+ const BATCH_SIZE = 3;
851
+ const results = [];
852
+ for (let i = 0; i < deviceTypes.length; i += BATCH_SIZE) {
853
+ const batch = deviceTypes.slice(i, i + BATCH_SIZE);
854
+ const batchPromises = batch.map(
855
+ (deviceType) => this.generateScreenshot({ deviceType })
856
+ );
857
+ const batchResults = await Promise.all(batchPromises);
858
+ results.push(...batchResults);
859
+ }
860
+ return results;
861
+ }
862
+ /**
863
+ * Generate designed screenshot
864
+ */
865
+ async generateDesignedScreenshot(content, design) {
866
+ const canvas = await this.renderer.renderDesignedScreenshot(content, design);
867
+ const blob = await this.renderer["canvasRenderer"].exportToBlob(canvas, {
868
+ format: "png"
869
+ });
870
+ return {
871
+ id: this.generateId(),
872
+ deviceType: design.deviceType,
873
+ dimensions: { width: canvas.width, height: canvas.height },
874
+ format: "png",
875
+ timestamp: /* @__PURE__ */ new Date(),
876
+ fileSize: blob.blob.size,
877
+ url: blob.url
878
+ };
879
+ }
880
+ /**
881
+ * Export project as ZIP
882
+ */
883
+ async exportProjectAsZip(project) {
884
+ const JSZip = (await import("jszip")).default;
885
+ const zip = new JSZip();
886
+ const folder = zip.folder(project.currentLanguage);
887
+ if (!folder) {
888
+ throw new Error("Failed to create folder in ZIP");
889
+ }
890
+ if (this.config.export?.includeMetadata) {
891
+ const metadataText = `APP NAME: ${project.appMetadata.appName}
892
+ SUBTITLE: ${project.appMetadata.subtitle}
893
+ DESCRIPTION:
894
+ ${project.appMetadata.description}
895
+
896
+ KEYWORDS: ${project.appMetadata.keywords}
897
+ WHATS NEW:
898
+ ${project.appMetadata.whatsNew}`;
899
+ folder.file("aso_metadata.txt", metadataText);
900
+ }
901
+ const screenshotPromises = project.screens.map(
902
+ (screen, index) => this.generateDesignedScreenshot(screen, project.design).then((screenshot) => ({ screenshot, index }))
903
+ );
904
+ const screenshots = await Promise.all(screenshotPromises);
905
+ screenshots.forEach(({ screenshot, index }) => {
906
+ const base64Data = screenshot.url.split(",")[1];
907
+ folder.file(
908
+ `screen_${index + 1}_${project.design.deviceType}.png`,
909
+ base64Data,
910
+ { base64: true }
911
+ );
912
+ });
913
+ return await zip.generateAsync({ type: "blob" });
914
+ }
915
+ /**
916
+ * Create project
917
+ */
918
+ createProject(name) {
919
+ return {
920
+ id: this.generateId(),
921
+ name,
922
+ design: this.getDefaultDesign(),
923
+ screens: [this.getDefaultScreen()],
924
+ currentLanguage: this.config.defaultLanguage || "en-US",
925
+ selectedScreenId: "1",
926
+ appMetadata: {
927
+ appName: "My App",
928
+ subtitle: "App Description",
929
+ promotionalText: "Promotional text",
930
+ keywords: "keyword1, keyword2",
931
+ description: "App description",
932
+ whatsNew: "What is new in this version"
933
+ },
934
+ appIcon: null,
935
+ createdAt: /* @__PURE__ */ new Date(),
936
+ updatedAt: /* @__PURE__ */ new Date()
937
+ };
938
+ }
939
+ /**
940
+ * Get default design
941
+ */
942
+ getDefaultDesign() {
943
+ return {
944
+ backgroundColor: "#6366f1",
945
+ backgroundGradientEnd: "#a855f7",
946
+ backgroundImage: null,
947
+ backgroundBlur: 0,
948
+ backgroundOverlayOpacity: 0,
949
+ backgroundPattern: "none",
950
+ textColor: "#ffffff",
951
+ highlightColor: "#fbbf24",
952
+ textAlign: "center",
953
+ deviceColor: "#1f2937",
954
+ deviceType: this.config.device?.defaultDevice || "iphone-15-pro",
955
+ frameStyle: "realistic",
956
+ layout: "text-top",
957
+ scale: 0.85,
958
+ fontFamily: "Inter",
959
+ titleFontSize: 60,
960
+ subtitleFontSize: 24,
961
+ titleFontWeight: "900",
962
+ subtitleFontWeight: "500",
963
+ textCase: "uppercase",
964
+ lineHeight: 0.9,
965
+ letterSpacing: -1,
966
+ rotation: 0,
967
+ rotationX: 0,
968
+ rotationY: 0,
969
+ rotationZ: 0,
970
+ offsetY: 0,
971
+ shadowIntensity: 0.5,
972
+ padding: 40,
973
+ gap: 20,
974
+ isPanoramic: false
975
+ };
976
+ }
977
+ /**
978
+ * Get default screen
979
+ */
980
+ getDefaultScreen() {
981
+ return {
982
+ id: "1",
983
+ title: "MY *APP*",
984
+ subtitle: "Your app description here",
985
+ screenshot: null,
986
+ translations: {
987
+ "en-US": { title: "MY *APP*", subtitle: "Your app description here" }
988
+ },
989
+ imageFit: "cover",
990
+ imageZoom: 1,
991
+ imageAnchorX: 50,
992
+ imageAnchorY: 50
993
+ };
994
+ }
995
+ /**
996
+ * Generate unique ID - optimized version
997
+ */
998
+ generateId() {
999
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
1000
+ return crypto.randomUUID();
1001
+ }
1002
+ return `${Date.now().toString(36)}-${Math.random().toString(36).substring(2, 9)}`;
1003
+ }
1004
+ };
1005
+
1006
+ // src/presentation/hooks/useScreenshotStudio.ts
1007
+ var DEFAULT_SCREENS = [
1008
+ {
1009
+ id: "1",
1010
+ title: "APPGROWTHFACTORY *MODERN*",
1011
+ subtitle: "Create content with AI power",
1012
+ screenshot: null,
1013
+ translations: {
1014
+ "en-US": {
1015
+ title: "APPGROWTHFACTORY *MODERN*",
1016
+ subtitle: "Create content with AI power"
1017
+ },
1018
+ "tr-TR": {
1019
+ title: "APPGROWTHFACTORY *MODERN*",
1020
+ subtitle: "Yapay zeka g\xFCc\xFCyle i\xE7erik \xFCret"
1021
+ }
1022
+ },
1023
+ imageFit: "cover",
1024
+ imageZoom: 1,
1025
+ imageAnchorX: 50,
1026
+ imageAnchorY: 50
1027
+ },
1028
+ {
1029
+ id: "2",
1030
+ title: "CONNECT *GLOBAL*",
1031
+ subtitle: "Post to all platforms instantly",
1032
+ screenshot: null,
1033
+ translations: {
1034
+ "en-US": {
1035
+ title: "CONNECT *GLOBAL*",
1036
+ subtitle: "Post to all platforms instantly"
1037
+ },
1038
+ "tr-TR": {
1039
+ title: "BA\u011ELAN *K\xDCRESEL*",
1040
+ subtitle: "T\xFCm platformlara an\u0131nda g\xF6nder"
1041
+ }
1042
+ },
1043
+ imageFit: "cover",
1044
+ imageZoom: 1,
1045
+ imageAnchorX: 50,
1046
+ imageAnchorY: 50
1047
+ }
1048
+ ];
1049
+ var DEFAULT_DESIGN = {
1050
+ backgroundColor: "#6366f1",
1051
+ backgroundGradientEnd: "#a855f7",
1052
+ backgroundImage: null,
1053
+ backgroundBlur: 0,
1054
+ backgroundOverlayOpacity: 0,
1055
+ backgroundPattern: "none",
1056
+ textColor: "#ffffff",
1057
+ highlightColor: "#fbbf24",
1058
+ textAlign: "center",
1059
+ deviceColor: "#1f2937",
1060
+ deviceType: "iphone-15-pro",
1061
+ frameStyle: "realistic",
1062
+ layout: "text-top",
1063
+ scale: 0.85,
1064
+ fontFamily: "Inter",
1065
+ titleFontSize: 60,
1066
+ subtitleFontSize: 24,
1067
+ titleFontWeight: "900",
1068
+ subtitleFontWeight: "500",
1069
+ textCase: "uppercase",
1070
+ lineHeight: 0.9,
1071
+ letterSpacing: -1,
1072
+ rotation: 0,
1073
+ rotationX: 0,
1074
+ rotationY: 0,
1075
+ rotationZ: 0,
1076
+ offsetY: 0,
1077
+ shadowIntensity: 0.5,
1078
+ padding: 40,
1079
+ gap: 20,
1080
+ isPanoramic: false
1081
+ };
1082
+ var DEFAULT_APP_METADATA = {
1083
+ appName: "Growdo",
1084
+ subtitle: "AI Content Generator",
1085
+ promotionalText: "Unlock your creative potential",
1086
+ keywords: "ai, content, marketing, automation, generator",
1087
+ description: "The ultimate tool for AI-powered marketing content.",
1088
+ whatsNew: "New Design Studio integration!"
1089
+ };
1090
+ function useScreenshotStudio(options = {}) {
1091
+ const {
1092
+ config = {},
1093
+ onShowToast = () => {
1094
+ }
1095
+ } = options;
1096
+ const fullConfig = {
1097
+ ...DEFAULT_SCREENSHOT_STUDIO_CONFIG,
1098
+ ...config
1099
+ };
1100
+ const serviceRef = (0, import_react.useRef)(null);
1101
+ if (!serviceRef.current) {
1102
+ serviceRef.current = new ScreenshotStudioService(fullConfig);
1103
+ }
1104
+ (0, import_react.useEffect)(() => {
1105
+ return () => {
1106
+ if (serviceRef.current) {
1107
+ }
1108
+ };
1109
+ }, []);
1110
+ const [screens, setScreens] = (0, import_react.useState)(DEFAULT_SCREENS);
1111
+ const [design, setDesign] = (0, import_react.useState)(DEFAULT_DESIGN);
1112
+ const [currentLanguage, setCurrentLanguage] = (0, import_react.useState)(
1113
+ fullConfig.defaultLanguage || "en-US"
1114
+ );
1115
+ const [selectedScreenId, setSelectedScreenId] = (0, import_react.useState)("1");
1116
+ const [isProcessing, setIsProcessing] = (0, import_react.useState)(false);
1117
+ const [isAnalyzing, setIsAnalyzing] = (0, import_react.useState)(false);
1118
+ const [appMetadata, setAppMetadata] = (0, import_react.useState)(
1119
+ DEFAULT_APP_METADATA
1120
+ );
1121
+ const [appIcon, setAppIcon] = (0, import_react.useState)(null);
1122
+ const [projectId, setProjectId] = (0, import_react.useState)(null);
1123
+ const activeScreen = screens.find((s) => s.id === selectedScreenId) || screens[0];
1124
+ const updateDesign = (0, import_react.useCallback)((updates) => {
1125
+ setDesign((prev) => ({ ...prev, ...updates }));
1126
+ }, []);
1127
+ const updateActiveScreen = (0, import_react.useCallback)(
1128
+ (updates) => {
1129
+ setScreens(
1130
+ (prev) => prev.map((screen) => {
1131
+ if (screen.id !== selectedScreenId) return screen;
1132
+ const updatedScreen = { ...screen, ...updates };
1133
+ if (updates.title || updates.subtitle) {
1134
+ updatedScreen.translations = {
1135
+ ...updatedScreen.translations,
1136
+ [currentLanguage]: {
1137
+ title: updatedScreen.title,
1138
+ subtitle: updatedScreen.subtitle
1139
+ }
1140
+ };
1141
+ }
1142
+ return updatedScreen;
1143
+ })
1144
+ );
1145
+ },
1146
+ [selectedScreenId, currentLanguage]
1147
+ );
1148
+ const changeLanguage = (0, import_react.useCallback)(
1149
+ (newLanguage) => {
1150
+ setCurrentLanguage(newLanguage);
1151
+ setScreens(
1152
+ (prev) => prev.map((screen) => {
1153
+ const translation = screen.translations[newLanguage] || screen.translations["en-US"] || { title: screen.title, subtitle: screen.subtitle };
1154
+ return {
1155
+ ...screen,
1156
+ title: translation.title,
1157
+ subtitle: translation.subtitle
1158
+ };
1159
+ })
1160
+ );
1161
+ onShowToast("Language Changed", `Switched to ${newLanguage}`);
1162
+ },
1163
+ [onShowToast]
1164
+ );
1165
+ const addScreen = (0, import_react.useCallback)(() => {
1166
+ const newScreen = {
1167
+ id: Date.now().toString(),
1168
+ title: "NEW *POST*",
1169
+ subtitle: "Engage your audience",
1170
+ screenshot: null,
1171
+ translations: {
1172
+ [currentLanguage]: {
1173
+ title: "NEW *POST*",
1174
+ subtitle: "Engage your audience"
1175
+ }
1176
+ },
1177
+ imageFit: "cover",
1178
+ imageZoom: 1,
1179
+ imageAnchorX: 50,
1180
+ imageAnchorY: 50
1181
+ };
1182
+ setScreens((prev) => [...prev, newScreen]);
1183
+ setSelectedScreenId(newScreen.id);
1184
+ onShowToast("Success", "New screen added");
1185
+ }, [currentLanguage, onShowToast]);
1186
+ const removeScreen = (0, import_react.useCallback)(
1187
+ (screenId) => {
1188
+ if (screens.length <= 1) return;
1189
+ setScreens((prev) => {
1190
+ const newScreens = prev.filter((s) => s.id !== screenId);
1191
+ if (selectedScreenId === screenId) {
1192
+ setSelectedScreenId(newScreens[0].id);
1193
+ }
1194
+ return newScreens;
1195
+ });
1196
+ onShowToast("Info", "Screen removed");
1197
+ },
1198
+ [screens.length, selectedScreenId, onShowToast]
1199
+ );
1200
+ const duplicateScreen = (0, import_react.useCallback)(
1201
+ (screenId) => {
1202
+ const screenToDuplicate = screens.find((s) => s.id === screenId);
1203
+ if (!screenToDuplicate) return;
1204
+ const newScreen = {
1205
+ ...screenToDuplicate,
1206
+ id: Date.now().toString(),
1207
+ title: `${screenToDuplicate.title} (Copy)`,
1208
+ translations: { ...screenToDuplicate.translations }
1209
+ };
1210
+ setScreens((prev) => {
1211
+ const index = prev.findIndex((s) => s.id === screenId);
1212
+ const newScreens = [...prev];
1213
+ newScreens.splice(index + 1, 0, newScreen);
1214
+ return newScreens;
1215
+ });
1216
+ setSelectedScreenId(newScreen.id);
1217
+ onShowToast("Success", "Screen duplicated");
1218
+ },
1219
+ [screens, onShowToast]
1220
+ );
1221
+ const applyTemplate = (0, import_react.useCallback)(
1222
+ (template) => {
1223
+ setDesign((prev) => ({ ...prev, ...template.design }));
1224
+ onShowToast("Template Applied", template.name);
1225
+ },
1226
+ [onShowToast]
1227
+ );
1228
+ const generateDesignedScreenshot = (0, import_react.useCallback)(
1229
+ async (screenId) => {
1230
+ if (!serviceRef.current) return;
1231
+ const screen = screens.find((s) => s.id === screenId);
1232
+ if (!screen) return;
1233
+ setIsProcessing(true);
1234
+ try {
1235
+ const result = await serviceRef.current.generateDesignedScreenshot(
1236
+ screen,
1237
+ design
1238
+ );
1239
+ onShowToast("Success", "Screenshot generated");
1240
+ return { url: result.url, id: result.id };
1241
+ } catch {
1242
+ onShowToast("Error", "Screenshot generation failed");
1243
+ } finally {
1244
+ setIsProcessing(false);
1245
+ }
1246
+ },
1247
+ [screens, design, onShowToast]
1248
+ );
1249
+ const exportAllScreensAsZip = (0, import_react.useCallback)(
1250
+ async (format = "png") => {
1251
+ if (!serviceRef.current) return;
1252
+ setIsProcessing(true);
1253
+ let url = null;
1254
+ try {
1255
+ const project = {
1256
+ id: projectId || "default-project",
1257
+ name: "Export Project",
1258
+ design,
1259
+ screens,
1260
+ currentLanguage,
1261
+ selectedScreenId,
1262
+ appMetadata,
1263
+ appIcon,
1264
+ createdAt: /* @__PURE__ */ new Date(),
1265
+ updatedAt: /* @__PURE__ */ new Date()
1266
+ };
1267
+ const blob = await serviceRef.current.exportProjectAsZip(project);
1268
+ url = URL.createObjectURL(blob);
1269
+ const link = document.createElement("a");
1270
+ link.href = url;
1271
+ link.download = `Studio_${currentLanguage}_${Date.now()}.zip`;
1272
+ link.click();
1273
+ onShowToast(
1274
+ "Success",
1275
+ `Exported ${screens.length} screens in ZIP archive.`
1276
+ );
1277
+ } catch {
1278
+ onShowToast("Error", "ZIP export failed");
1279
+ } finally {
1280
+ setIsProcessing(false);
1281
+ if (url) {
1282
+ setTimeout(() => {
1283
+ try {
1284
+ URL.revokeObjectURL(url);
1285
+ } catch (e) {
1286
+ }
1287
+ }, 100);
1288
+ }
1289
+ }
1290
+ },
1291
+ [
1292
+ screens,
1293
+ design,
1294
+ currentLanguage,
1295
+ appMetadata,
1296
+ appIcon,
1297
+ projectId,
1298
+ selectedScreenId,
1299
+ onShowToast
1300
+ ]
1301
+ );
1302
+ const _getProjectState = (0, import_react.useCallback)(() => {
1303
+ return {
1304
+ id: projectId || "appgrowthfactory_main_project",
1305
+ name: "Default Project",
1306
+ design,
1307
+ screens,
1308
+ currentLanguage,
1309
+ selectedScreenId,
1310
+ appMetadata,
1311
+ appIcon,
1312
+ createdAt: /* @__PURE__ */ new Date(),
1313
+ updatedAt: /* @__PURE__ */ new Date()
1314
+ };
1315
+ }, [
1316
+ design,
1317
+ screens,
1318
+ currentLanguage,
1319
+ selectedScreenId,
1320
+ appMetadata,
1321
+ appIcon,
1322
+ projectId
1323
+ ]);
1324
+ const _loadProjectState = (0, import_react.useCallback)(
1325
+ (state) => {
1326
+ if (!state) return;
1327
+ if (state.screens) setScreens(state.screens);
1328
+ if (state.design) setDesign(state.design);
1329
+ if (state.currentLanguage) setCurrentLanguage(state.currentLanguage);
1330
+ if (state.selectedScreenId && state.screens?.find((s) => s.id === state.selectedScreenId)) {
1331
+ setSelectedScreenId(state.selectedScreenId);
1332
+ }
1333
+ if (state.appMetadata) setAppMetadata(state.appMetadata);
1334
+ if (state.appIcon !== void 0) setAppIcon(state.appIcon);
1335
+ },
1336
+ []
1337
+ );
1338
+ return {
1339
+ screens,
1340
+ design,
1341
+ currentLanguage,
1342
+ selectedScreenId,
1343
+ activeScreen,
1344
+ isProcessing,
1345
+ isAnalyzing,
1346
+ appMetadata,
1347
+ appIcon,
1348
+ projectId,
1349
+ updateDesign,
1350
+ updateActiveScreen,
1351
+ setSelectedScreenId,
1352
+ changeLanguage,
1353
+ applyTemplate,
1354
+ addScreen,
1355
+ removeScreen,
1356
+ duplicateScreen,
1357
+ generateDesignedScreenshot,
1358
+ exportAllScreensAsZip,
1359
+ setAppMetadata,
1360
+ setAppIcon,
1361
+ setProjectId,
1362
+ _getProjectState,
1363
+ _loadProjectState
1364
+ };
1365
+ }
1366
+
1367
+ // src/presentation/hooks/useCanvasExport.ts
1368
+ var import_react2 = require("react");
1369
+ function useCanvasExport(options = {}) {
1370
+ const { config = DEFAULT_CANVAS_CONFIG } = options;
1371
+ const [isExporting, setIsExporting] = (0, import_react2.useState)(false);
1372
+ const [progress, setProgress] = (0, import_react2.useState)(0);
1373
+ const [error, setError] = (0, import_react2.useState)(null);
1374
+ const rendererRef = (0, import_react2.useRef)(null);
1375
+ const urlCleanupRef = (0, import_react2.useRef)([]);
1376
+ if (!rendererRef.current) {
1377
+ rendererRef.current = new CanvasRenderer(config);
1378
+ }
1379
+ (0, import_react2.useEffect)(() => {
1380
+ return () => {
1381
+ urlCleanupRef.current.forEach((url) => {
1382
+ try {
1383
+ URL.revokeObjectURL(url);
1384
+ } catch (e) {
1385
+ }
1386
+ });
1387
+ urlCleanupRef.current = [];
1388
+ };
1389
+ }, []);
1390
+ const exportToBlob = (0, import_react2.useCallback)(
1391
+ async (canvas, options2) => {
1392
+ if (!rendererRef.current) return null;
1393
+ setIsExporting(true);
1394
+ setProgress(0);
1395
+ setError(null);
1396
+ try {
1397
+ const result = await rendererRef.current.exportToBlob(canvas, options2);
1398
+ setProgress(100);
1399
+ if (result?.url) {
1400
+ urlCleanupRef.current.push(result.url);
1401
+ }
1402
+ return result;
1403
+ } catch (err) {
1404
+ const errorMessage = err instanceof Error ? err.message : "Export failed";
1405
+ setError(errorMessage);
1406
+ return null;
1407
+ } finally {
1408
+ setIsExporting(false);
1409
+ }
1410
+ },
1411
+ []
1412
+ );
1413
+ const exportToDataURL = (0, import_react2.useCallback)(
1414
+ (canvas, format, quality) => {
1415
+ if (!rendererRef.current) return null;
1416
+ try {
1417
+ return rendererRef.current.exportToDataURL(canvas, format, quality);
1418
+ } catch (err) {
1419
+ const errorMessage = err instanceof Error ? err.message : "Export failed";
1420
+ setError(errorMessage);
1421
+ return null;
1422
+ }
1423
+ },
1424
+ []
1425
+ );
1426
+ const downloadCanvas = (0, import_react2.useCallback)(
1427
+ async (canvas, filename, options2) => {
1428
+ setIsExporting(true);
1429
+ setProgress(0);
1430
+ setError(null);
1431
+ try {
1432
+ const result = await exportToBlob(canvas, options2);
1433
+ if (!result) {
1434
+ throw new Error("Export failed");
1435
+ }
1436
+ setProgress(50);
1437
+ const link = document.createElement("a");
1438
+ link.href = result.url;
1439
+ link.download = filename;
1440
+ link.click();
1441
+ setProgress(100);
1442
+ setTimeout(() => {
1443
+ URL.revokeObjectURL(result.url);
1444
+ const index = urlCleanupRef.current.indexOf(result.url);
1445
+ if (index > -1) {
1446
+ urlCleanupRef.current.splice(index, 1);
1447
+ }
1448
+ }, 100);
1449
+ } catch (err) {
1450
+ const errorMessage = err instanceof Error ? err.message : "Download failed";
1451
+ setError(errorMessage);
1452
+ } finally {
1453
+ setIsExporting(false);
1454
+ }
1455
+ },
1456
+ [exportToBlob]
1457
+ );
1458
+ const cloneCanvas = (0, import_react2.useCallback)(
1459
+ (canvas) => {
1460
+ if (!rendererRef.current) return null;
1461
+ try {
1462
+ return rendererRef.current.cloneCanvas(canvas);
1463
+ } catch (err) {
1464
+ const errorMessage = err instanceof Error ? err.message : "Clone failed";
1465
+ setError(errorMessage);
1466
+ return null;
1467
+ }
1468
+ },
1469
+ []
1470
+ );
1471
+ return {
1472
+ isExporting,
1473
+ progress,
1474
+ error,
1475
+ exportToBlob,
1476
+ exportToDataURL,
1477
+ downloadCanvas,
1478
+ cloneCanvas
1479
+ };
1480
+ }
1481
+
1482
+ // src/presentation/hooks/useReportExport.ts
1483
+ var import_react3 = require("react");
1484
+
1485
+ // src/application/services/ReportService.ts
1486
+ var ReportService = class _ReportService {
1487
+ static getInstance() {
1488
+ if (!_ReportService.instance) {
1489
+ _ReportService.instance = new _ReportService();
1490
+ }
1491
+ return _ReportService.instance;
1492
+ }
1493
+ /**
1494
+ * Export DOM element to PDF
1495
+ */
1496
+ async exportToPDF(elementId, options = {}) {
1497
+ const html2canvas = (await import("html2canvas")).default;
1498
+ const jsPDF = (await import("jspdf")).default;
1499
+ const element = document.getElementById(elementId);
1500
+ if (!element) {
1501
+ throw new Error("Report element not found");
1502
+ }
1503
+ const canvas = await html2canvas(element, {
1504
+ scale: options.scale || 2,
1505
+ useCORS: options.useCORS !== false,
1506
+ backgroundColor: options.backgroundColor || "#ffffff"
1507
+ });
1508
+ const imgData = canvas.toDataURL("image/png");
1509
+ const pdf = new jsPDF("p", "mm", "a4");
1510
+ const imgWidth = 210;
1511
+ const imgHeight = canvas.height * imgWidth / canvas.width;
1512
+ pdf.addImage(imgData, "PNG", 0, 0, imgWidth, imgHeight);
1513
+ pdf.save(options.filename || "report.pdf");
1514
+ }
1515
+ /**
1516
+ * Export canvas to PDF
1517
+ */
1518
+ async exportCanvasToPDF(canvas, options = {}) {
1519
+ const jsPDF = (await import("jspdf")).default;
1520
+ const imgData = canvas.toDataURL("image/png");
1521
+ const pdf = new jsPDF("p", "mm", "a4");
1522
+ const imgWidth = 210;
1523
+ const imgHeight = canvas.height * imgWidth / canvas.width;
1524
+ pdf.addImage(imgData, "PNG", 0, 0, imgWidth, imgHeight);
1525
+ pdf.save(options.filename || "canvas-export.pdf");
1526
+ }
1527
+ /**
1528
+ * Export data to Excel
1529
+ */
1530
+ async exportToExcel(data, options = {}) {
1531
+ const XLSX = await import("xlsx");
1532
+ const wb = XLSX.utils.book_new();
1533
+ const apps = data.items.filter((i) => i.type === "app").map((i) => ({ Name: i.name, ...i.metrics, ...i.details }));
1534
+ const campaigns = data.items.filter((i) => i.type === "campaign").map((i) => ({ Name: i.name, ...i.metrics, ...i.details }));
1535
+ const posts = data.items.filter((i) => i.type === "post").map((i) => ({ Name: i.name, ...i.metrics, ...i.details }));
1536
+ if (apps.length > 0) {
1537
+ XLSX.utils.book_append_sheet(
1538
+ wb,
1539
+ XLSX.utils.json_to_sheet(apps),
1540
+ options.sheetName || "Apps"
1541
+ );
1542
+ }
1543
+ if (campaigns.length > 0) {
1544
+ XLSX.utils.book_append_sheet(
1545
+ wb,
1546
+ XLSX.utils.json_to_sheet(campaigns),
1547
+ "Campaigns"
1548
+ );
1549
+ }
1550
+ if (posts.length > 0) {
1551
+ XLSX.utils.book_append_sheet(
1552
+ wb,
1553
+ XLSX.utils.json_to_sheet(posts),
1554
+ "Posts"
1555
+ );
1556
+ }
1557
+ if (options.includeSummary !== false) {
1558
+ const summary = [
1559
+ { Metric: "Total Reach", Value: data.summary.totalReach },
1560
+ {
1561
+ Metric: "Total Engagement",
1562
+ Value: data.summary.totalEngagement
1563
+ },
1564
+ {
1565
+ Metric: "Average Score",
1566
+ Value: data.summary.averageScore
1567
+ },
1568
+ {
1569
+ Metric: "Export Date",
1570
+ Value: (/* @__PURE__ */ new Date()).toLocaleDateString()
1571
+ }
1572
+ ];
1573
+ XLSX.utils.book_append_sheet(
1574
+ wb,
1575
+ XLSX.utils.json_to_sheet(summary),
1576
+ "Summary"
1577
+ );
1578
+ }
1579
+ XLSX.writeFile(wb, options.filename || "report.xlsx");
1580
+ }
1581
+ /**
1582
+ * Export data to CSV
1583
+ */
1584
+ exportToCSV(data, filename = "report.csv", delimiter = ",") {
1585
+ const headers = ["Type", "Name", "Metrics"];
1586
+ const rows = data.items.map((item) => [
1587
+ item.type,
1588
+ item.name,
1589
+ JSON.stringify(item.metrics)
1590
+ ]);
1591
+ const csvContent = [headers, ...rows].map((row) => row.map((cell) => `"${cell}"`).join(delimiter)).join("\n");
1592
+ const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
1593
+ const url = URL.createObjectURL(blob);
1594
+ const link = document.createElement("a");
1595
+ link.href = url;
1596
+ link.download = filename;
1597
+ link.click();
1598
+ URL.revokeObjectURL(url);
1599
+ }
1600
+ /**
1601
+ * Export multiple elements to PDF
1602
+ */
1603
+ async exportMultipleToPDF(elementIds, options = {}) {
1604
+ const html2canvas = (await import("html2canvas")).default;
1605
+ const jsPDF = (await import("jspdf")).default;
1606
+ const pdf = new jsPDF("p", "mm", "a4");
1607
+ for (let i = 0; i < elementIds.length; i++) {
1608
+ const element = document.getElementById(elementIds[i]);
1609
+ if (!element) continue;
1610
+ const canvas = await html2canvas(element, {
1611
+ scale: options.scale || 2,
1612
+ useCORS: options.useCORS !== false,
1613
+ backgroundColor: options.backgroundColor || "#ffffff"
1614
+ });
1615
+ const imgData = canvas.toDataURL("image/png");
1616
+ const imgWidth = 210;
1617
+ const imgHeight = canvas.height * imgWidth / canvas.width;
1618
+ if (i > 0) {
1619
+ pdf.addPage();
1620
+ }
1621
+ pdf.addImage(imgData, "PNG", 0, 0, imgWidth, imgHeight);
1622
+ }
1623
+ pdf.save(options.filename || "multi-page-report.pdf");
1624
+ }
1625
+ };
1626
+
1627
+ // src/presentation/hooks/useReportExport.ts
1628
+ function useReportExport() {
1629
+ const [isExporting, setIsExporting] = (0, import_react3.useState)(false);
1630
+ const [error, setError] = (0, import_react3.useState)(null);
1631
+ const reportServiceRef = (0, import_react3.useRef)(null);
1632
+ if (!reportServiceRef.current) {
1633
+ reportServiceRef.current = ReportService.getInstance();
1634
+ }
1635
+ const exportToPDF = (0, import_react3.useCallback)(
1636
+ async (elementId, options) => {
1637
+ if (!reportServiceRef.current) {
1638
+ throw new Error("ReportService not initialized");
1639
+ }
1640
+ setIsExporting(true);
1641
+ setError(null);
1642
+ try {
1643
+ await reportServiceRef.current.exportToPDF(elementId, options);
1644
+ } catch (err) {
1645
+ const errorMessage = err instanceof Error ? err.message : "PDF export failed";
1646
+ setError(errorMessage);
1647
+ throw err;
1648
+ } finally {
1649
+ setIsExporting(false);
1650
+ }
1651
+ },
1652
+ []
1653
+ );
1654
+ const exportCanvasToPDF = (0, import_react3.useCallback)(
1655
+ async (canvas, options) => {
1656
+ if (!reportServiceRef.current) {
1657
+ throw new Error("ReportService not initialized");
1658
+ }
1659
+ setIsExporting(true);
1660
+ setError(null);
1661
+ try {
1662
+ await reportServiceRef.current.exportCanvasToPDF(canvas, options);
1663
+ } catch (err) {
1664
+ const errorMessage = err instanceof Error ? err.message : "Canvas PDF export failed";
1665
+ setError(errorMessage);
1666
+ throw err;
1667
+ } finally {
1668
+ setIsExporting(false);
1669
+ }
1670
+ },
1671
+ []
1672
+ );
1673
+ const exportMultipleToPDF = (0, import_react3.useCallback)(
1674
+ async (elementIds, options) => {
1675
+ if (!reportServiceRef.current) {
1676
+ throw new Error("ReportService not initialized");
1677
+ }
1678
+ setIsExporting(true);
1679
+ setError(null);
1680
+ try {
1681
+ await reportServiceRef.current.exportMultipleToPDF(elementIds, options);
1682
+ } catch (err) {
1683
+ const errorMessage = err instanceof Error ? err.message : "Multi-page PDF export failed";
1684
+ setError(errorMessage);
1685
+ throw err;
1686
+ } finally {
1687
+ setIsExporting(false);
1688
+ }
1689
+ },
1690
+ []
1691
+ );
1692
+ const exportToExcel = (0, import_react3.useCallback)(
1693
+ async (data, options) => {
1694
+ if (!reportServiceRef.current) {
1695
+ throw new Error("ReportService not initialized");
1696
+ }
1697
+ setIsExporting(true);
1698
+ setError(null);
1699
+ try {
1700
+ await reportServiceRef.current.exportToExcel(data, options);
1701
+ } catch (err) {
1702
+ const errorMessage = err instanceof Error ? err.message : "Excel export failed";
1703
+ setError(errorMessage);
1704
+ throw err;
1705
+ } finally {
1706
+ setIsExporting(false);
1707
+ }
1708
+ },
1709
+ []
1710
+ );
1711
+ const exportToCSV = (0, import_react3.useCallback)(
1712
+ (data, filename, delimiter) => {
1713
+ if (!reportServiceRef.current) {
1714
+ throw new Error("ReportService not initialized");
1715
+ }
1716
+ try {
1717
+ reportServiceRef.current.exportToCSV(data, filename, delimiter);
1718
+ } catch (err) {
1719
+ const errorMessage = err instanceof Error ? err.message : "CSV export failed";
1720
+ setError(errorMessage);
1721
+ throw err;
1722
+ }
1723
+ },
1724
+ []
1725
+ );
1726
+ return {
1727
+ isExporting,
1728
+ error,
1729
+ exportToPDF,
1730
+ exportCanvasToPDF,
1731
+ exportMultipleToPDF,
1732
+ exportToExcel,
1733
+ exportToCSV
1734
+ };
1735
+ }
1736
+
1737
+ // src/presentation/hooks/useFreehandCanvas.ts
1738
+ var import_react4 = require("react");
1739
+ var DEFAULT_BRUSH_SIZE = 3;
1740
+ var DEFAULT_COLOR = "#1a1a1a";
1741
+ function widthFor(stroke, point) {
1742
+ if (!stroke.dynamic) return stroke.size;
1743
+ return stroke.size * (0.5 + Math.min(1, Math.max(0, point.pressure)));
1744
+ }
1745
+ function useFreehandCanvas(options = {}) {
1746
+ const { brushSize = DEFAULT_BRUSH_SIZE, color = DEFAULT_COLOR, pressureEnabled = true } = options;
1747
+ const optionsRef = (0, import_react4.useRef)({ brushSize, color, pressureEnabled, onStrokeEnd: options.onStrokeEnd });
1748
+ optionsRef.current = { brushSize, color, pressureEnabled, onStrokeEnd: options.onStrokeEnd };
1749
+ const canvasRef = (0, import_react4.useRef)(null);
1750
+ const strokesRef = (0, import_react4.useRef)([]);
1751
+ const activeStrokeRef = (0, import_react4.useRef)(null);
1752
+ const dprRef = (0, import_react4.useRef)(1);
1753
+ const [strokeCount, setStrokeCount] = (0, import_react4.useState)(0);
1754
+ const redraw = (0, import_react4.useCallback)(() => {
1755
+ const canvas = canvasRef.current;
1756
+ const ctx = canvas?.getContext("2d");
1757
+ if (!canvas || !ctx) return;
1758
+ const dpr = dprRef.current;
1759
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
1760
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
1761
+ ctx.scale(dpr, dpr);
1762
+ const all = activeStrokeRef.current ? [...strokesRef.current, activeStrokeRef.current] : strokesRef.current;
1763
+ ctx.lineCap = "round";
1764
+ ctx.lineJoin = "round";
1765
+ for (const stroke of all) {
1766
+ ctx.strokeStyle = stroke.color;
1767
+ ctx.fillStyle = stroke.color;
1768
+ if (stroke.points.length === 1) {
1769
+ const point = stroke.points[0];
1770
+ ctx.beginPath();
1771
+ ctx.arc(point.x, point.y, widthFor(stroke, point) / 2, 0, Math.PI * 2);
1772
+ ctx.fill();
1773
+ continue;
1774
+ }
1775
+ for (let i = 1; i < stroke.points.length; i += 1) {
1776
+ const from = stroke.points[i - 1];
1777
+ const to = stroke.points[i];
1778
+ ctx.beginPath();
1779
+ ctx.lineWidth = (widthFor(stroke, from) + widthFor(stroke, to)) / 2;
1780
+ ctx.moveTo(from.x, from.y);
1781
+ ctx.lineTo(to.x, to.y);
1782
+ ctx.stroke();
1783
+ }
1784
+ }
1785
+ }, []);
1786
+ const syncDimensions = (0, import_react4.useCallback)(() => {
1787
+ const canvas = canvasRef.current;
1788
+ if (!canvas) return false;
1789
+ const dpr = window.devicePixelRatio || 1;
1790
+ const width = Math.max(1, Math.round(canvas.clientWidth * dpr));
1791
+ const height = Math.max(1, Math.round(canvas.clientHeight * dpr));
1792
+ if (canvas.width === width && canvas.height === height && dprRef.current === dpr) return false;
1793
+ canvas.width = width;
1794
+ canvas.height = height;
1795
+ dprRef.current = dpr;
1796
+ return true;
1797
+ }, []);
1798
+ (0, import_react4.useEffect)(() => {
1799
+ const canvas = canvasRef.current;
1800
+ if (!canvas) return;
1801
+ const el = canvas;
1802
+ el.style.touchAction = "none";
1803
+ syncDimensions();
1804
+ redraw();
1805
+ const observer = new ResizeObserver(() => {
1806
+ if (syncDimensions()) redraw();
1807
+ });
1808
+ observer.observe(canvas);
1809
+ function pointFrom(event) {
1810
+ const rect = el.getBoundingClientRect();
1811
+ return {
1812
+ x: event.clientX - rect.left,
1813
+ y: event.clientY - rect.top,
1814
+ pressure: event.pressure > 0 ? event.pressure : 0.5
1815
+ };
1816
+ }
1817
+ function drawSegment(stroke, from, to) {
1818
+ const ctx = el.getContext("2d");
1819
+ if (!ctx) return;
1820
+ ctx.lineCap = "round";
1821
+ ctx.lineJoin = "round";
1822
+ ctx.strokeStyle = stroke.color;
1823
+ ctx.lineWidth = (widthFor(stroke, from) + widthFor(stroke, to)) / 2;
1824
+ ctx.beginPath();
1825
+ ctx.moveTo(from.x, from.y);
1826
+ ctx.lineTo(to.x, to.y);
1827
+ ctx.stroke();
1828
+ }
1829
+ function drawDot(stroke, point) {
1830
+ const ctx = el.getContext("2d");
1831
+ if (!ctx) return;
1832
+ ctx.fillStyle = stroke.color;
1833
+ ctx.beginPath();
1834
+ ctx.arc(point.x, point.y, widthFor(stroke, point) / 2, 0, Math.PI * 2);
1835
+ ctx.fill();
1836
+ }
1837
+ function onPointerDown(event) {
1838
+ if (event.button !== 0 && event.pointerType === "mouse") return;
1839
+ event.preventDefault();
1840
+ el.setPointerCapture(event.pointerId);
1841
+ const { brushSize: size, color: ink, pressureEnabled: dynamic } = optionsRef.current;
1842
+ const stroke = {
1843
+ size,
1844
+ color: ink,
1845
+ dynamic: dynamic && event.pointerType === "pen",
1846
+ points: [pointFrom(event)]
1847
+ };
1848
+ activeStrokeRef.current = stroke;
1849
+ drawDot(stroke, stroke.points[0]);
1850
+ }
1851
+ function onPointerMove(event) {
1852
+ const stroke = activeStrokeRef.current;
1853
+ if (!stroke) return;
1854
+ event.preventDefault();
1855
+ const point = pointFrom(event);
1856
+ const previous = stroke.points[stroke.points.length - 1];
1857
+ stroke.points.push(point);
1858
+ drawSegment(stroke, previous, point);
1859
+ }
1860
+ function commit(event) {
1861
+ const stroke = activeStrokeRef.current;
1862
+ if (!stroke) return;
1863
+ activeStrokeRef.current = null;
1864
+ if (el.hasPointerCapture(event.pointerId)) {
1865
+ el.releasePointerCapture(event.pointerId);
1866
+ }
1867
+ strokesRef.current = [...strokesRef.current, stroke];
1868
+ setStrokeCount(strokesRef.current.length);
1869
+ optionsRef.current.onStrokeEnd?.(stroke);
1870
+ }
1871
+ el.addEventListener("pointerdown", onPointerDown);
1872
+ el.addEventListener("pointermove", onPointerMove);
1873
+ el.addEventListener("pointerup", commit);
1874
+ el.addEventListener("pointercancel", commit);
1875
+ return () => {
1876
+ observer.disconnect();
1877
+ el.removeEventListener("pointerdown", onPointerDown);
1878
+ el.removeEventListener("pointermove", onPointerMove);
1879
+ el.removeEventListener("pointerup", commit);
1880
+ el.removeEventListener("pointercancel", commit);
1881
+ };
1882
+ }, [redraw, syncDimensions]);
1883
+ const undo = (0, import_react4.useCallback)(() => {
1884
+ if (strokesRef.current.length === 0) return;
1885
+ strokesRef.current = strokesRef.current.slice(0, -1);
1886
+ setStrokeCount(strokesRef.current.length);
1887
+ redraw();
1888
+ }, [redraw]);
1889
+ const clear = (0, import_react4.useCallback)(() => {
1890
+ if (strokesRef.current.length === 0) return;
1891
+ strokesRef.current = [];
1892
+ setStrokeCount(0);
1893
+ redraw();
1894
+ }, [redraw]);
1895
+ const getStrokes = (0, import_react4.useCallback)(() => strokesRef.current.map((stroke) => ({ ...stroke, points: stroke.points.map((point) => ({ ...point })) })), []);
1896
+ return {
1897
+ canvasRef,
1898
+ undo,
1899
+ clear,
1900
+ strokeCount,
1901
+ isEmpty: strokeCount === 0,
1902
+ getStrokes
1903
+ };
1904
+ }
1905
+ // Annotate the CommonJS export names for ESM import in node:
1906
+ 0 && (module.exports = {
1907
+ useCanvasExport,
1908
+ useFreehandCanvas,
1909
+ useReportExport,
1910
+ useScreenshotStudio
1911
+ });