@umituz/web-canvas 1.0.5 → 1.0.6

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