@umituz/web-canvas 1.0.5 → 1.0.7

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