-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.ts
More file actions
925 lines (772 loc) · 31.1 KB
/
code.ts
File metadata and controls
925 lines (772 loc) · 31.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
// Type declaration for TextEncoder (used in Figma plugin environment)
interface TextEncoder {
encode(input?: string): Uint8Array;
}
interface TextEncoderConstructor {
new(): TextEncoder;
}
declare const TextEncoder: TextEncoderConstructor;
figma.showUI(__html__, { width: 320, height: 480 });
const CHIP_CORNER_RADIUS = 0;
const CHIP_PADDING_LR = 0;
const CHIP_PADDING_TB = 0;
const CHIP_FONT_SIZE = 10;
const IMAGE_TO_CHIP_GAP = 8;
const CHIP_TO_CHIP_GAP = 8;
const GRID_SPACING = 20;
const GRID_COLS = 6;
const MAX_FILENAME_CHARS = 24;
const TABLE_ITEM_SPACING = 0;
const CELL_STROKE_COLOR = { r: 0.9, g: 0.9, b: 0.9 };
const PLACEHOLDER_SIZE = 50;
const FILENAME_COL_WIDTH = 170;
const DIMENSIONS_COL_WIDTH = 80;
const IMAGE_COL_WIDTH = 100;
const PLACEHOLDER_COL_WIDTH = 100;
const ROW_HEIGHT = 60;
interface FileData {
name: string;
type: string;
data: string;
size: number;
}
interface ProcessedRow {
row: FrameNode;
width: number;
height: number;
}
const base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
function base64ToUint8Array(base64: string): Uint8Array {
const len = base64.length;
const bytes = new Uint8Array(Math.floor(len * 3 / 4));
let i = 0;
let j = 0;
while (i < len) {
const c1 = base64.charAt(i++);
const c2 = base64.charAt(i++);
const c3 = base64.charAt(i++);
const c4 = base64.charAt(i++);
const char1 = base64Chars.indexOf(c1);
const char2 = base64Chars.indexOf(c2);
const char3 = base64Chars.indexOf(c3);
const char4 = base64Chars.indexOf(c4);
if (char1 === -1 || char2 === -1) break;
const b1 = (char1 << 2) | (char2 >> 4);
bytes[j++] = b1;
if (char3 !== -1) {
const b2 = ((char2 & 0x0F) << 4) | (char3 >> 2);
bytes[j++] = b2;
}
if (char4 !== -1) {
const b3 = ((char3 & 0x03) << 6) | char4;
bytes[j++] = b3;
}
}
return bytes.subarray(0, j);
}
function stringToUint8Array(text: string): Uint8Array {
if (typeof TextEncoder !== 'undefined') {
return new TextEncoder().encode(text);
}
const bytes = new Uint8Array(text.length);
for (let i = 0; i < text.length; i++) {
bytes[i] = text.charCodeAt(i) & 0xFF;
}
return bytes;
}
function dataURLtoUint8Array(dataURL: string): Uint8Array {
const commaIndex = dataURL.indexOf(',');
if (commaIndex === -1) return new Uint8Array();
const header = dataURL.slice(0, commaIndex);
const data = dataURL.slice(commaIndex + 1);
if (header.includes(';base64')) {
return base64ToUint8Array(data);
}
try {
return stringToUint8Array(decodeURIComponent(data));
} catch {
return stringToUint8Array(data);
}
}
function getImageDimensions(bytes: Uint8Array, type: string): { width: number; height: number } {
if (bytes.length < 12) {
return { width: 100, height: 100 };
}
if (type === 'image/png') {
try {
if (bytes.length < 24) {
console.error('PNG file too small:', bytes.length);
return { width: 100, height: 100 };
}
console.log('First 8 bytes of PNG:', Array.from(bytes.slice(0, 8)).map(b => b.toString(16)));
// Read width and height from IHDR chunk (bytes 16-23)
// PNG uses big-endian byte order
const width = (bytes[16] << 24) | (bytes[17] << 16) | (bytes[18] << 8) | bytes[19];
const height = (bytes[20] << 24) | (bytes[21] << 16) | (bytes[22] << 8) | bytes[23];
console.log('PNG dimensions from bytes:', width, height);
return { width, height };
} catch (e) {
console.error('Error parsing PNG dimensions:', e);
return { width: 100, height: 100 };
}
}
if (type === 'image/jpeg' || type === 'image/jpg') {
try {
if (bytes[0] !== 0xFF || bytes[1] !== 0xD8) return { width: 100, height: 100 };
let offset = 2;
while (offset < bytes.length - 9) {
// Check for valid marker
if (bytes[offset] !== 0xFF) {
offset++;
continue;
}
const marker = bytes[offset + 1];
offset += 2;
// SOF markers (Start of Frame) contain dimensions
if ((marker >= 0xC0 && marker <= 0xC3) || (marker >= 0xC5 && marker <= 0xC7) ||
(marker >= 0xC9 && marker <= 0xCB) || (marker >= 0xCD && marker <= 0xCF)) {
// Skip segment length (2 bytes) and precision (1 byte)
const height = (bytes[offset + 3] << 8) | bytes[offset + 4];
const width = (bytes[offset + 5] << 8) | bytes[offset + 6];
console.log('JPEG dimensions from SOF marker:', width, height);
return { width, height };
}
// Skip to next segment
if (offset >= bytes.length - 1) break;
const segmentLength = (bytes[offset] << 8) | bytes[offset + 1];
offset += segmentLength;
}
} catch (e) {
console.error('Error parsing JPEG dimensions:', e);
return { width: 100, height: 100 };
}
return { width: 100, height: 100 };
}
if (type === 'image/gif') {
try {
const view = new DataView(bytes.buffer);
const width = view.getUint16(6, true);
const height = view.getUint16(8, true);
return { width, height };
} catch {
return { width: 100, height: 100 };
}
}
if (type === 'image/webp') {
try {
const view = new DataView(bytes.buffer);
const riff = view.getUint32(0, false);
const webp = view.getUint32(4, false);
if (riff !== 0x52494646 || webp !== 0x57454250) return { width: 100, height: 100 };
const vp8 = view.getUint32(12, false);
if (vp8 === 0x56503820) {
if (bytes.length < 30) return { width: 100, height: 100 };
const view2 = new DataView(bytes.buffer, 26, 4);
const width = (view2.getUint8(1) | (view2.getUint8(0) << 8)) + 1;
const height = (view2.getUint8(3) | (view2.getUint8(2) << 8)) + 1;
return { width, height };
}
} catch {
return { width: 100, height: 100 };
}
return { width: 100, height: 100 };
}
if (type === 'image/svg+xml' || type === 'image/svg') {
try {
let text = '';
for (let k = 0; k < bytes.length && k < 10000; k++) {
text += String.fromCharCode(bytes[k]);
}
const widthMatch = text.match(/width=["']?(\d+(?:\.\d+)?)(px)?["']?/);
const heightMatch = text.match(/height=["']?(\d+(?:\.\d+)?)(px)?["']?/);
const viewBoxMatch = text.match(/viewBox=["']?([^"']+)["']?/);
if (viewBoxMatch) {
const parts = viewBoxMatch[1].split(/[\s,]+/);
if (parts.length >= 4) {
return { width: parseFloat(parts[2]) || 100, height: parseFloat(parts[3]) || 100 };
}
}
const width = widthMatch ? parseFloat(widthMatch[1]) : 100;
const height = heightMatch ? parseFloat(heightMatch[1]) : 100;
return { width, height };
} catch {
return { width: 100, height: 100 };
}
}
return { width: 100, height: 100 };
}
function truncateFilename(filename: string, maxChars: number = MAX_FILENAME_CHARS): string {
if (filename.length <= maxChars) return filename;
const lastDotIndex = filename.lastIndexOf('.');
if (lastDotIndex > 8) {
const ext = filename.substring(lastDotIndex);
const availableChars = maxChars - ext.length - 3;
if (availableChars > 5) {
return filename.substring(0, availableChars) + '...' + ext;
}
}
return filename.substring(0, maxChars - 3) + '...';
}
function formatDimensions(width: number, height: number): string {
return `${Math.round(width)}x${Math.round(height)}`;
}
async function createTextNode(
characters: string,
fontSize: number = CHIP_FONT_SIZE,
color: { r: number; g: number; b: number } = { r: 0, g: 0, b: 0 }
): Promise<TextNode> {
await figma.loadFontAsync({ family: 'Inter', style: 'Regular' });
const textNode = figma.createText();
textNode.characters = characters;
textNode.fontSize = fontSize;
textNode.fontName = { family: 'Inter', style: 'Regular' };
textNode.fills = [{ type: 'SOLID', color }];
textNode.lineHeight = { value: 16.8, unit: 'PIXELS' };
textNode.textAlignHorizontal = 'CENTER';
textNode.textAlignVertical = 'CENTER';
return textNode;
}
function createChipAutoLayout(textNode: TextNode): FrameNode {
const chip = figma.createFrame();
chip.fills = [{ type: 'SOLID', color: { r: 1, g: 1, b: 1 } }];
chip.cornerRadius = CHIP_CORNER_RADIUS;
chip.clipsContent = true;
chip.layoutMode = 'HORIZONTAL';
chip.paddingLeft = 12;
chip.paddingRight = 12;
chip.paddingTop = CHIP_PADDING_TB;
chip.paddingBottom = CHIP_PADDING_TB;
chip.itemSpacing = 0;
chip.primaryAxisSizingMode = 'AUTO';
chip.counterAxisSizingMode = 'AUTO';
chip.primaryAxisAlignItems = 'MIN';
chip.counterAxisAlignItems = 'CENTER';
chip.appendChild(textNode);
return chip;
}
async function createMetadataChips(
imageWidth: number,
fileName: string,
dimensions: string
): Promise<{ nameChip: FrameNode; dimChip: FrameNode }> {
const nameText = await createTextNode(fileName, CHIP_FONT_SIZE, { r: 0, g: 0, b: 0 });
const dimText = await createTextNode(dimensions, CHIP_FONT_SIZE, { r: 0, g: 0, b: 0 });
const nameChip = createChipAutoLayout(nameText);
const dimChip = createChipAutoLayout(dimText);
figma.currentPage.appendChild(nameChip);
figma.currentPage.appendChild(dimChip);
return { nameChip, dimChip };
}
async function createHeaderRow(): Promise<FrameNode> {
const filenameText = await createTextNode("Filename");
const dimensionsText = await createTextNode("Dimensions");
const imageText = await createTextNode("Image");
const placeholderText = await createTextNode("Placeholder");
const filenameCell = figma.createFrame();
filenameCell.fills = [{ type: 'SOLID', color: { r: 1, g: 1, b: 1 } }];
filenameCell.strokes = [{ type: 'SOLID', color: CELL_STROKE_COLOR }];
filenameCell.layoutMode = 'HORIZONTAL';
filenameCell.paddingLeft = 12;
filenameCell.paddingRight = 12;
filenameCell.paddingTop = 0;
filenameCell.paddingBottom = 0;
filenameCell.primaryAxisSizingMode = 'FIXED';
filenameCell.counterAxisSizingMode = 'FIXED';
filenameCell.resize(FILENAME_COL_WIDTH, ROW_HEIGHT);
filenameCell.primaryAxisAlignItems = 'MIN';
filenameCell.counterAxisAlignItems = 'CENTER';
filenameCell.appendChild(filenameText);
const dimensionsCell = figma.createFrame();
dimensionsCell.fills = [{ type: 'SOLID', color: { r: 1, g: 1, b: 1 } }];
dimensionsCell.strokes = [{ type: 'SOLID', color: CELL_STROKE_COLOR }];
dimensionsCell.layoutMode = 'HORIZONTAL';
dimensionsCell.paddingLeft = 12;
dimensionsCell.paddingRight = 12;
dimensionsCell.paddingTop = 0;
dimensionsCell.paddingBottom = 0;
dimensionsCell.primaryAxisSizingMode = 'FIXED';
dimensionsCell.counterAxisSizingMode = 'FIXED';
dimensionsCell.resize(DIMENSIONS_COL_WIDTH, ROW_HEIGHT);
dimensionsCell.primaryAxisAlignItems = 'MIN';
dimensionsCell.counterAxisAlignItems = 'CENTER';
dimensionsCell.appendChild(dimensionsText);
const imageCell = figma.createFrame();
imageCell.fills = [{ type: 'SOLID', color: { r: 1, g: 1, b: 1 } }];
imageCell.strokes = [{ type: 'SOLID', color: CELL_STROKE_COLOR }];
imageCell.layoutMode = 'HORIZONTAL';
imageCell.paddingLeft = 0;
imageCell.paddingRight = 0;
imageCell.paddingTop = 0;
imageCell.paddingBottom = 0;
imageCell.primaryAxisSizingMode = 'FIXED';
imageCell.counterAxisSizingMode = 'FIXED';
imageCell.resize(IMAGE_COL_WIDTH, ROW_HEIGHT);
imageCell.primaryAxisAlignItems = 'CENTER';
imageCell.counterAxisAlignItems = 'CENTER';
imageCell.appendChild(imageText);
const placeholderCell = figma.createFrame();
placeholderCell.fills = [{ type: 'SOLID', color: { r: 1, g: 1, b: 1 } }];
placeholderCell.strokes = [{ type: 'SOLID', color: CELL_STROKE_COLOR }];
placeholderCell.layoutMode = 'HORIZONTAL';
placeholderCell.paddingLeft = 0;
placeholderCell.paddingRight = 0;
placeholderCell.paddingTop = 0;
placeholderCell.paddingBottom = 0;
placeholderCell.primaryAxisSizingMode = 'FIXED';
placeholderCell.counterAxisSizingMode = 'FIXED';
placeholderCell.resize(PLACEHOLDER_COL_WIDTH, ROW_HEIGHT);
placeholderCell.primaryAxisAlignItems = 'CENTER';
placeholderCell.counterAxisAlignItems = 'CENTER';
placeholderCell.appendChild(placeholderText);
const headerRow = figma.createFrame();
headerRow.layoutMode = 'HORIZONTAL';
headerRow.itemSpacing = 0;
headerRow.primaryAxisSizingMode = 'AUTO';
headerRow.counterAxisSizingMode = 'AUTO';
headerRow.primaryAxisAlignItems = 'CENTER';
headerRow.counterAxisAlignItems = 'CENTER';
headerRow.fills = [];
headerRow.strokes = [];
headerRow.appendChild(filenameCell);
headerRow.appendChild(dimensionsCell);
headerRow.appendChild(imageCell);
headerRow.appendChild(placeholderCell);
return headerRow;
}
function base64ToString(base64: string): string {
const bytes = base64ToUint8Array(base64);
let result = '';
for (let i = 0; i < bytes.length; i++) {
result += String.fromCharCode(bytes[i]);
}
return result;
}
function bytesToAsciiString(bytes: Uint8Array, limit?: number): string {
const max = typeof limit === 'number' ? Math.min(bytes.length, limit) : bytes.length;
let result = '';
for (let i = 0; i < max; i++) {
result += String.fromCharCode(bytes[i]);
}
return result;
}
function extractSvgTextIfPresent(bytes: Uint8Array): string | null {
const text = bytesToAsciiString(bytes);
const lower = text.toLowerCase();
// Must contain an actual <svg tag — comments, HTML, and XML declarations alone don't count
if (!lower.includes('<svg')) {
return null;
}
return text;
}
function looksLikeSvgMarkup(text: string): boolean {
// Only match if there's an actual <svg tag
return /<\s*svg\b/i.test(text);
}
function looksLikeText(bytes: Uint8Array): boolean {
const sample = Math.min(bytes.length, 512);
if (sample === 0) return false;
let printable = 0;
for (let i = 0; i < sample; i++) {
const c = bytes[i];
if (c === 9 || c === 10 || c === 13 || (c >= 32 && c <= 126)) {
printable++;
}
}
return printable / sample > 0.8;
}
function tryCreateSvgNodeFromBytes(bytes: Uint8Array, forceWrap: boolean = false): SceneNode | null {
try {
const text = bytesToAsciiString(bytes);
const lower = text.toLowerCase();
// If it's already a complete SVG, use it as-is (don't wrap)
if (lower.includes('<svg')) {
return figma.createNodeFromSvg(text);
}
// For fragments (symbol, defs only), wrap them
if (lower.includes('<symbol') || lower.includes('<defs') || looksLikeSvgMarkup(text) || (forceWrap && !lower.includes('<svg'))) {
const wrapped = `<svg xmlns="http://www.w3.org/2000/svg">${text}</svg>`;
return figma.createNodeFromSvg(wrapped);
}
} catch {
return null;
}
return null;
}
function detectFileType(bytes: Uint8Array): string {
if (bytes.length < 4) return 'unknown';
console.log('First 4 bytes:', Array.from(bytes.slice(0, 4)).map(b => '0x' + b.toString(16)));
if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) {
return 'image/png';
}
if (bytes[0] === 0xFF && bytes[1] === 0xD8 && bytes[2] === 0xFF) {
return 'image/jpeg';
}
if (bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38) {
return 'image/gif';
}
if (bytes.length >= 12 && bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46) {
if (bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) {
return 'image/webp';
}
}
// Heuristic for SVG: must contain an actual <svg tag
try {
const text = bytesToAsciiString(bytes, 8192).toLowerCase();
if (text.includes('<svg')) {
return 'image/svg+xml';
}
} catch {
// Ignore text parsing errors and fall through to unknown.
}
return 'unknown';
}
async function createAnnotatedImage(fileData: FileData): Promise<ProcessedRow> {
try {
console.log('Creating image:', fileData.name, 'type:', fileData.type, 'data length:', fileData.data.length);
let imageWidth = 100;
let imageHeight = 100;
let imageNode: SceneNode;
const imageBytes = dataURLtoUint8Array(fileData.data);
// Detect actual file type from magic bytes FIRST (most reliable)
const actualFileType = detectFileType(imageBytes);
console.log('Detected file type from magic bytes:', actualFileType);
// Handle GIF files - they should have been converted to PNG by the UI
// But if one gets through, try to process it as a raster image
if (actualFileType === 'image/gif') {
console.warn('GIF file detected - attempting to process as raster image');
// Continue processing - will likely fail but we get a better error message
}
// Override the claimed type if we detected something different
if (actualFileType !== 'unknown' && actualFileType !== fileData.type) {
console.log(`File type mismatch! Claimed: ${fileData.type}, Detected: ${actualFileType}`);
fileData.type = actualFileType;
}
// Only check for text/SVG content if the file type is unknown or already SVG
const isSvg = fileData.type === 'image/svg+xml' || fileData.type === 'image/svg';
const svgTextFromBytes = isSvg ? extractSvgTextIfPresent(imageBytes) : null;
const textLike = !actualFileType || actualFileType === 'unknown' ? looksLikeText(imageBytes) : false;
const svgNodeFromBytes = (isSvg || textLike) ? tryCreateSvgNodeFromBytes(imageBytes, true) : null;
console.log('Text-like bytes:', textLike, 'svgText:', !!svgTextFromBytes, 'svgNode:', !!svgNodeFromBytes);
if (isSvg) {
// Always extract SVG source text for dimension parsing
const base64Data = fileData.data.includes(',') ? fileData.data.split(',')[1] : '';
const svgSourceText = svgTextFromBytes || base64ToString(base64Data);
if (svgNodeFromBytes) {
imageNode = svgNodeFromBytes;
} else {
imageNode = figma.createNodeFromSvg(svgSourceText);
}
// Get node dimensions first
imageWidth = (imageNode as FrameNode).width || 0;
imageHeight = (imageNode as FrameNode).height || 0;
// For sprite SVGs (no intrinsic size), parse viewBox and width/height attributes
if ((!imageWidth || !imageHeight) && svgSourceText) {
// Try viewBox first (covers most SVGs)
const vbMatch = svgSourceText.match(/viewBox\s*=\s*["']([^"']+)["']/i);
if (vbMatch) {
const parts = vbMatch[1].trim().split(/[\s,]+/);
if (parts.length >= 4) {
if (!imageWidth) imageWidth = parseFloat(parts[2]) || 0;
if (!imageHeight) imageHeight = parseFloat(parts[3]) || 0;
}
}
// Try explicit width/height attributes
const widthMatch = svgSourceText.match(/\bwidth\s*=\s*["']?([\d.]+)/i);
if (widthMatch && !imageWidth) imageWidth = parseFloat(widthMatch[1]) || 0;
const heightMatch = svgSourceText.match(/\bheight\s*=\s*["']?([\d.]+)/i);
if (heightMatch && !imageHeight) imageHeight = parseFloat(heightMatch[1]) || 0;
}
// Final fallback
imageWidth = imageWidth || 100;
imageHeight = imageHeight || 100;
console.log('SVG imported as node, dimensions:', imageWidth, 'x', imageHeight);
} else {
// Raster image (PNG, JPEG, WebP - GIFs should have been converted to PNG by UI)
let image: Image;
try {
image = figma.createImage(imageBytes);
} catch (createErr) {
console.error('figma.createImage() failed for', fileData.name, createErr);
// Provide helpful error messages based on detected type
let helpMessage = 'Unable to create image in Figma.';
if (actualFileType === 'unknown') {
helpMessage = `Figma could not decode the file "${fileData.name}". The file format may be corrupted or unsupported. ` +
`Supported formats are: PNG, JPEG, SVG, and WebP. Try re-saving the file.`;
} else if (actualFileType !== fileData.type) {
helpMessage = `File type mismatch: Claimed to be ${fileData.type} but detected as ${actualFileType}. ` +
`Try uploading it again, or convert it to PNG manually.`;
}
throw new Error(helpMessage);
}
console.log('Image created, hash:', image.hash);
const dimensions = getImageDimensions(imageBytes, fileData.type);
console.log('Dimensions:', dimensions);
imageWidth = Math.max(dimensions.width || 100, 10);
imageHeight = Math.max(dimensions.height || 100, 10);
const imageFrame = figma.createFrame();
imageFrame.resize(imageWidth, imageHeight);
imageFrame.fills = [{ type: 'IMAGE', scaleMode: 'FIT', imageHash: image.hash }];
imageFrame.strokes = [];
imageNode = imageFrame;
}
const dimensionsText = formatDimensions(imageWidth, imageHeight);
const { nameChip, dimChip } = await createMetadataChips(imageWidth, fileData.name, dimensionsText);
// Add strokes to chips
nameChip.strokes = [{ type: 'SOLID', color: CELL_STROKE_COLOR }];
dimChip.strokes = [{ type: 'SOLID', color: CELL_STROKE_COLOR }];
// Set fixed sizes
nameChip.primaryAxisSizingMode = 'FIXED';
nameChip.counterAxisSizingMode = 'FIXED';
nameChip.resize(FILENAME_COL_WIDTH, ROW_HEIGHT);
dimChip.primaryAxisSizingMode = 'FIXED';
dimChip.counterAxisSizingMode = 'FIXED';
dimChip.resize(DIMENSIONS_COL_WIDTH, ROW_HEIGHT);
// Create image cell (same structure as chips)
const imageCell = figma.createFrame();
imageCell.fills = [{ type: 'SOLID', color: { r: 1, g: 1, b: 1 } }];
imageCell.strokes = [{ type: 'SOLID', color: CELL_STROKE_COLOR }];
imageCell.layoutMode = 'HORIZONTAL';
imageCell.paddingLeft = 0;
imageCell.paddingRight = 0;
imageCell.paddingTop = 0;
imageCell.paddingBottom = 0;
imageCell.primaryAxisSizingMode = 'FIXED';
imageCell.counterAxisSizingMode = 'FIXED';
imageCell.resize(IMAGE_COL_WIDTH, ROW_HEIGHT);
imageCell.primaryAxisAlignItems = 'CENTER';
imageCell.counterAxisAlignItems = 'CENTER';
imageCell.clipsContent = true;
// Scale the image to fit within the cell while maintaining aspect ratio
const cellPadding = 10; // Add some padding inside the cell
const maxWidth = IMAGE_COL_WIDTH - (cellPadding * 2);
const maxHeight = ROW_HEIGHT - (cellPadding * 2);
const scale = Math.min(maxWidth / imageWidth, maxHeight / imageHeight, 1);
if ('resize' in imageNode) {
(imageNode as FrameNode).resize(imageWidth * scale, imageHeight * scale);
}
imageCell.appendChild(imageNode);
// Create placeholder cell (same structure as chips)
const blackFrame = figma.createFrame();
blackFrame.fills = [{ type: 'SOLID', color: { r: 1, g: 1, b: 1 } }];
blackFrame.strokes = [{ type: 'SOLID', color: CELL_STROKE_COLOR }];
blackFrame.layoutMode = 'HORIZONTAL';
blackFrame.paddingLeft = 0;
blackFrame.paddingRight = 0;
blackFrame.paddingTop = 0;
blackFrame.paddingBottom = 0;
blackFrame.primaryAxisSizingMode = 'FIXED';
blackFrame.counterAxisSizingMode = 'FIXED';
blackFrame.resize(PLACEHOLDER_COL_WIDTH, ROW_HEIGHT);
blackFrame.primaryAxisAlignItems = 'CENTER';
blackFrame.counterAxisAlignItems = 'CENTER';
// Create row
const row = figma.createFrame();
row.layoutMode = 'HORIZONTAL';
row.itemSpacing = 0;
row.primaryAxisSizingMode = 'AUTO';
row.counterAxisSizingMode = 'FIXED';
row.resize(row.width, ROW_HEIGHT);
row.primaryAxisAlignItems = 'CENTER';
row.counterAxisAlignItems = 'CENTER';
row.fills = [];
row.strokes = [];
row.appendChild(nameChip);
row.appendChild(dimChip);
row.appendChild(imageCell);
row.appendChild(blackFrame);
// Store original filename for export functionality
row.setPluginData('originalFilename', fileData.name);
row.setPluginData('rowType', 'iconTableRow');
console.log('Row created:', fileData.name, 'width:', row.width, 'height:', row.height);
return { row, width: row.width, height: row.height };
} catch (error) {
console.error('Error creating annotated image:', fileData.name, error);
throw new Error(`Failed to process image: ${fileData.name}`);
}
}
async function importImages(files: FileData[]): Promise<void> {
const processedImages: ProcessedRow[] = [];
const errors: string[] = [];
try {
for (let i = 0; i < files.length; i++) {
const file = files[i];
try {
const result = await createAnnotatedImage(file);
processedImages.push(result);
} catch (error) {
console.error(`Error processing file ${file.name}:`, error);
errors.push(file.name);
}
}
if (processedImages.length > 0) {
const table = figma.createFrame();
table.layoutMode = 'VERTICAL';
table.itemSpacing = 0;
table.primaryAxisSizingMode = 'AUTO';
table.counterAxisSizingMode = 'AUTO';
table.fills = [];
table.strokes = [];
table.name = 'Icon Table';
const headerRow = await createHeaderRow();
table.appendChild(headerRow);
processedImages.forEach(pr => table.appendChild(pr.row));
figma.currentPage.appendChild(table);
table.x = figma.viewport.center.x - table.width / 2;
table.y = figma.viewport.center.y - table.height / 2;
figma.currentPage.selection = [table];
if (processedImages.length === 1) {
figma.viewport.zoom = 0.5;
} else {
figma.viewport.scrollAndZoomIntoView([table]);
}
}
} catch (error) {
console.error('Error during import:', error);
}
}
// Helper function to convert Uint8Array to base64 string
function bytesToBase64(bytes: Uint8Array): string {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
let result = '';
let i = 0;
while (i < bytes.length) {
const b1 = bytes[i++];
const b2 = bytes[i++];
const b3 = bytes[i++];
result += chars[(b1 >> 2) & 63];
result += chars[((b1 & 3) << 4) | ((b2 !== undefined ? b2 : 0) >> 4)];
result += b2 !== undefined ? chars[((b2 & 15) << 2) | ((b3 !== undefined ? b3 : 0) >> 6)] : '=';
result += b3 !== undefined ? chars[b3 & 63] : '=';
}
return result;
}
// Export selected rows functionality
async function exportSelectedRows(): Promise<void> {
// Use same relaxed filtering as checkSelection
const selection = figma.currentPage.selection.filter(node => {
if (node.type !== 'FRAME') return false;
const hasRowMarker = node.getPluginData('rowType') === 'iconTableRow';
const hasRowStructure = node.children.length >= 4;
return hasRowMarker || hasRowStructure;
}) as FrameNode[];
if (selection.length === 0) {
figma.ui.postMessage({
type: 'export-error',
message: 'Please select one or more table rows'
});
return;
}
const exports: Array<{ filename: string; imageData: string; placeholderData: string }> = [];
for (let i = 0; i < selection.length; i++) {
const row = selection[i];
// Progress update
figma.ui.postMessage({
type: 'export-progress',
current: i + 1,
total: selection.length,
message: `Processing row ${i + 1} of ${selection.length}...`
});
try {
// Validate row structure
if (row.children.length < 4) {
throw new Error(`Row ${i + 1}: Invalid structure (expected at least 4 cells)`);
}
// Get filename - try pluginData first, then extract from first cell
let filename = row.getPluginData('originalFilename');
if (!filename) {
// Fallback: extract from filename cell (first child)
const filenameCell = row.children[0] as FrameNode;
if (filenameCell && filenameCell.children.length > 0) {
const textNode = filenameCell.children.find(child => child.type === 'TEXT') as TextNode;
if (textNode && textNode.characters) {
filename = textNode.characters;
console.log(`Row ${i + 1}: Extracted filename from cell: ${filename}`);
}
}
}
if (!filename) {
// Last resort: use generic name
filename = `image-${i + 1}.png`;
console.log(`Row ${i + 1}: Using generic filename: ${filename}`);
}
// Get cells (Image is 3rd, Placeholder is 4th)
const imageCell = row.children[2] as FrameNode;
const placeholderCell = row.children[3] as FrameNode;
// Get the actual content inside the cells (not the cell container itself)
const imageContent = imageCell.children.length > 0 ? imageCell.children[0] : imageCell;
const placeholderContent = placeholderCell.children.length > 0 ? placeholderCell.children[0] : placeholderCell;
// Check dimensions of the actual content match
if (Math.abs(imageContent.width - placeholderContent.width) > 0.5 ||
Math.abs(imageContent.height - placeholderContent.height) > 0.5) {
throw new Error(
`Row ${i + 1} (${filename}): Dimension mismatch - ` +
`Image content (${Math.round(imageContent.width)}x${Math.round(imageContent.height)}) ≠ ` +
`Placeholder content (${Math.round(placeholderContent.width)}x${Math.round(placeholderContent.height)})`
);
}
// Export the content inside the cells (not the cell containers)
const [imageBytes, placeholderBytes] = await Promise.all([
imageContent.exportAsync({ format: 'PNG' }),
placeholderContent.exportAsync({ format: 'PNG' })
]);
// Convert to base64
exports.push({
filename,
imageData: `data:image/png;base64,${bytesToBase64(imageBytes)}`,
placeholderData: `data:image/png;base64,${bytesToBase64(placeholderBytes)}`
});
} catch (error) {
figma.ui.postMessage({
type: 'export-error',
message: error instanceof Error ? error.message : 'Unknown error during export'
});
return;
}
}
// Success - send exports to UI
figma.ui.postMessage({
type: 'export-complete',
exports,
summary: `Successfully exported ${exports.length} row(s)`
});
}
// Check selection and notify UI
function checkSelection() {
console.log('Checking selection, current selection:', figma.currentPage.selection.length, 'items');
const validRows = figma.currentPage.selection.filter(node => {
// Check if it's a frame with 4+ children (table row structure)
if (node.type !== 'FRAME') return false;
// Try to identify as a table row by structure or plugin data
const hasRowMarker = node.getPluginData('rowType') === 'iconTableRow';
const hasRowStructure = node.children.length >= 4;
console.log(`Node ${node.name}: type=${node.type}, children=${node.children.length}, rowMarker=${hasRowMarker}`);
return hasRowMarker || hasRowStructure;
});
console.log(`Found ${validRows.length} valid rows`);
figma.ui.postMessage({
type: 'selection-change',
hasSelection: validRows.length > 0,
count: validRows.length
});
}
// Listen for selection changes
figma.on('selectionchange', checkSelection);
// Initial check when plugin opens
figma.once('run', () => {
checkSelection();
});
figma.ui.onmessage = async (msg: { type: string; files?: FileData[]; message?: string }) => {
if (msg.type === 'import-images' && msg.files) {
await importImages(msg.files);
figma.closePlugin();
}
if (msg.type === 'export-rows') {
await exportSelectedRows();
}
if (msg.type === 'cancel') {
figma.closePlugin();
}
if (msg.type === 'close') {
figma.closePlugin();
}
};