-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.ts
More file actions
2451 lines (2095 loc) · 92.7 KB
/
controller.ts
File metadata and controls
2451 lines (2095 loc) · 92.7 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
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as _ from 'lodash';
// import {prisma_cloud_policies, prisma_cloud_alerts, artists, songs} from '../app/assets/datasets.js';
// NOTE: Scrolling: Can't seem have one element with both scrolling and fixed... Rather to have vertical scrolling on table body.
// Idea: Toggle on plugin GUI for horizontal or vertical scroll.
import {
baseFrameWithAutoLayout,
loadFontForTextNode,
transpose,
charactersPerArea,
dups,
smartLorem,
emailDomainFromString,
randomUserName,
} from '../shared/utils';
// FIXME: If some columns are deleted, things will stop working
// var meta_tables: {id: string, cols: number}[] = [];
let table_style = {
titleHeight: 48, // without subtitle
titleWithSubtitleHeight: 64,
rowHeight: 32,
headerHeight: 32,
columnWidth: 200,
paginationHeight: 48,
compact: {
rowHeight: 24,
},
cozy: {
rowHeight: 44,
},
spacious: {
rowHeight: 100,
},
};
const settings = {
'manual-update': false,
'show-actions-column': true, // Test // TMP
};
enum TABLE_PART {
'BodyCellFrame',
'HeaderCellFrame',
'BodyColumnFrame',
// "PaginationFrame",
'BodyCellInstance',
'HeaderCellInstance',
// "PaginationInstance",
}
const PRISMA_TABLE_COMPONENTS_INST_NAME = {
'Card / Header': 'Card / Header',
'Header - Text': 'Header - Text',
'Header - Checkbox': 'Header - Checkbox',
'Cell - Text': 'Cell - Text',
'Cell - Checkbox': 'Cell - Checkbox',
'Cell - Actions': 'Cell - Actions',
'Cell - Severity': 'Cell - Severity',
'Cell - Toggle': 'Cell - Toggle',
'Table - Background': 'Table - Background',
Pagination: 'Pagination',
'Table / Scroll - Vertical': 'Table / Scroll - Vertical',
'Table / Scroll - Horizontal': 'Table / Scroll - Horizontal',
'Table / Pinned Column': 'Table / Pinned Column',
// TMP
_row: '_row',
};
// Including names of component names such as 'Cell - Text'
let PRISMA_TABLE_COMPONENT_NAMES = new Set();
// Used to load all variants components from a "published" library
const TABLE_COMPONENT_SAMPLES = [
{
library: {name: 'Prisma Component Library'},
components: [
{name: PRISMA_TABLE_COMPONENTS_INST_NAME['Card / Header'], key: '061cacb1563153645cdd94fe1f0e5d9ec51c85bc'}, // Title for table
{name: PRISMA_TABLE_COMPONENTS_INST_NAME['Header - Text'], key: 'faa7a0e47753b0f79a71c29c61ee340e83b087c7'},
{
name: PRISMA_TABLE_COMPONENTS_INST_NAME['Header - Checkbox'],
key: 'd66c4bf33a2083e909bd4d074ec178060f35927f',
},
{name: PRISMA_TABLE_COMPONENTS_INST_NAME['Cell - Text'], key: '52f8db8c3eb06811177462ca81794c1e1b80b36d'},
{
name: PRISMA_TABLE_COMPONENTS_INST_NAME['Cell - Checkbox'],
key: 'f8df0a61c1015d39c58f188dd5baa5a88a9f3160',
},
{
name: PRISMA_TABLE_COMPONENTS_INST_NAME['Cell - Actions'],
key: '95a16fd43a583bec88fbe376f5cac1bc2471b09e',
},
{
name: PRISMA_TABLE_COMPONENTS_INST_NAME['Cell - Severity'],
key: '32336a641c8d8bf847a19b2582d7fcd0c53e6696',
},
{name: PRISMA_TABLE_COMPONENTS_INST_NAME['Cell - Toggle'], key: 'bc73a96bfe0005857390306323f2dbd91f62b536'},
{
name: PRISMA_TABLE_COMPONENTS_INST_NAME['Table - Background'],
key: 'f443506ec395fdb3b15b54e5c963273ce5b5d3a0',
},
{name: PRISMA_TABLE_COMPONENTS_INST_NAME.Pagination, key: 'a0dce3a552cfbe21ab347fd85677990281b6e4eb'},
{
name: PRISMA_TABLE_COMPONENTS_INST_NAME['Table / Scroll - Vertical'],
key: '1032d964742d34f6acaaa877da3b5cb6e4a67810',
},
{
name: PRISMA_TABLE_COMPONENTS_INST_NAME['Table / Scroll - Horizontal'],
key: '7b77b1357d1f9d2a4ff538dd3cc37e0494864537',
},
{
name: PRISMA_TABLE_COMPONENTS_INST_NAME['Table / Pinned Column'],
key: '4a7de3906ae123683bde968571e28e6a6fa41833',
},
],
},
{
library: {name: 'Prisma Component Library (Copy)'},
components: [
{name: PRISMA_TABLE_COMPONENTS_INST_NAME['Card / Header'], key: 'e0aef4c4a00e05cf585974908c58b66b8a235fc5'}, // Title for table
{name: PRISMA_TABLE_COMPONENTS_INST_NAME['Header - Text'], key: 'e15eb24664e5549b28ef8382813b8838fe9f4355'},
{
name: PRISMA_TABLE_COMPONENTS_INST_NAME['Header - Checkbox'],
key: '6bd448f4fae1eb8e2283ff6fb60f338b45751512',
},
{name: PRISMA_TABLE_COMPONENTS_INST_NAME['Cell - Text'], key: '943641d4d02f7ecb4f3d417fd07a43f92d5538f3'},
{
name: PRISMA_TABLE_COMPONENTS_INST_NAME['Cell - Checkbox'],
key: 'd4583b98a3cb254038985daa9b6d824be42d10b1',
},
{
name: PRISMA_TABLE_COMPONENTS_INST_NAME['Cell - Actions'],
key: 'b06683485c616d4d0cb1f93454f40c1ff22a3f95',
},
{
name: PRISMA_TABLE_COMPONENTS_INST_NAME['Cell - Severity'],
key: '1ab3dcf6c6327cc10a344e350e1b7c94c9b31b51',
},
{name: PRISMA_TABLE_COMPONENTS_INST_NAME['Cell - Toggle'], key: '4b5b6dc0fb56cb5d260b49b4e991740207fb2fd1'},
{
name: PRISMA_TABLE_COMPONENTS_INST_NAME['Table - Background'],
key: '101b57641c1a9a5f5fe9d20ed9de2dde69d08aba',
},
{name: PRISMA_TABLE_COMPONENTS_INST_NAME.Pagination, key: 'ae597ac63e31c3ba6e7fc4d3311d6537d9dce3d7'},
{
name: PRISMA_TABLE_COMPONENTS_INST_NAME['Table / Scroll - Vertical'],
key: 'c11e7023d16023dbdd2a091d9e5eb3c10c981792',
},
{
name: PRISMA_TABLE_COMPONENTS_INST_NAME['Table / Scroll - Horizontal'],
key: '0d4c7291abd5b8f4f0cad282144e17b8759c2436',
},
{
name: PRISMA_TABLE_COMPONENTS_INST_NAME['Table / Pinned Column'],
key: '4a7de3906ae123683bde968571e28e6a6fa41833',
},
// TMP
{
name: PRISMA_TABLE_COMPONENTS_INST_NAME._row,
key: '109e824f1f674ba7c04d05033cb4c12f8c8ca763',
},
],
},
];
interface tableCompInfo {
compName: string;
variantProperties?: object;
component: ComponentNode;
key: string;
}
// We only want to load all the components once
let _tableComponentsLoaded = false;
let allTableComponents: Array<tableCompInfo> = [];
loadAllTableComponents()
.then(() => {
console.log(
`### Welcome to Palo Alto Design System \n#### Table components ready; ${allTableComponents.length} variants loaded.`
);
assignStyles();
})
.then(() => {
// figma.showUI(__html__, {height: 320});
figma.showUI(__html__, {height: 500});
})
.catch((error) => {
console.error('error in loading Prisma Table cell components', error);
});
figma.ui.onmessage = (msg) => {
switch (msg.type) {
case 'update-settings':
updateSettings(msg);
break;
case 'create-table':
drawTableComp(msg.dataset);
break;
case 'create-table-w-mouse-states':
drawTableCompWithMouseStates(msg.dataset);
break;
case 'update-table':
console.log('update-table');
if (figma.currentPage.selection.length > 0) {
drawTableComp(msg.dataset);
}
case 'update-striped':
updateStriped(msg.striped);
break;
case 'select-row':
selectRow();
break;
case 'update-row-height':
const height = table_style[msg.height]['rowHeight'] as number;
const target = figma.currentPage.selection.concat()[0];
// updateRow(target);
updateRowHeight(target, height);
break;
case 'test':
test();
break;
case 'test1':
test1();
break;
case 'log':
log();
break;
case 'cancel':
break;
default:
break;
}
// figma.closePlugin();
};
function assignStyles() {
const _default = _.pick(
table_style,
Object.keys(table_style).filter((d) => {
return d !== 'compact' && d !== 'cozy' && d !== 'default' && d !== 'spacious';
})
);
table_style = {
...table_style,
...{
default: _default,
},
...{compact: {..._default, ...table_style.compact}},
...{cozy: {..._default, ...table_style.cozy}},
...{spacious: {..._default, ...table_style.spacious}},
};
}
// figma.showUI(__html__, {height: 320});
// We store which node we are interacting with
// TODO: store the whole array of current page selection
figma.on('selectionchange', () => {
console.log('...selection change...');
// We'll do nothing if the user wants manual upate
if (settings['manual-update']) return;
if (
figma.currentPage.getPluginData('selectedEl') !== ''
// && ( figma.currentPage.selection.length === 0 )
// (figma.currentPage.selection.length === 0 || figma.currentPage.selection[0].name !== 'pa-table-comp')
) {
// if the user just de-selected something, we may want to update the row
const sourceObj = JSON.parse(figma.currentPage.getPluginData('selectedEl'));
const source = figma.currentPage.findOne((n) => n.id === sourceObj.id);
if (figma.currentPage.selection.length > 0) {
const sel = figma.currentPage.selection[0];
if (sel.id === sourceObj.id) return;
}
if (sourceObj.type === 'FRAME' || sourceObj.type === 'INSTANCE') {
updateRow(source);
updateColumnComps(source);
updateColumnHeader(source);
updateColumn(source);
updateTableSize(source);
} else if (sourceObj.type === 'TEXT') {
updateColumnIcons(source as TextNode);
updateColumnTextFromHeader(source as TextNode);
updateColumnTextFromCell(source as TextNode);
}
updateTableColumns(sourceObj);
}
// Store the selection so we can use in the next change event
if (figma.currentPage.selection.length > 0) {
const el = figma.currentPage.selection[0];
// columns in the header and in the body have tableId so that we can handle
// deleted/re-ordered columns
const tableId = el.getPluginData('tableId');
const colId = el.getPluginData('assColId');
const obj = {
name: el.name,
type: el.type,
id: el.id,
tableId: tableId,
assColId: colId,
};
// 'selectedEl' is store on the current page
if (figma.currentPage.getPluginData('selectedEl')) {
const selectedElObj = figma.currentPage.getPluginData('selectedEl');
if (selectedElObj['id'] !== obj['id']) {
figma.currentPage.setPluginData('selectedEl', JSON.stringify(obj));
}
} else {
figma.currentPage.setPluginData('selectedEl', JSON.stringify(obj));
}
}
});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Settings
function updateSettings(msg: any) {
if (msg.setting === 'manual-update') {
settings['manual-update'] = msg.value;
}
console.log('update settings::', msg, 'now manual setting is:', settings['manual-update']);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Utilities
// Is the node a table part?
function tablePart(source: SceneNode): TABLE_PART {
if (!source || (source.type !== 'INSTANCE' && source.type !== 'FRAME')) return null;
const headerCelFrameReg = /(?<=col-)\d*/,
bodyCelFrameReg = /(?<=cell-row-)\d*/,
bodyColFrameReg = /(?<=col-)\d*/,
bodyCellInstReg = /Cell - [A-Za-z]*/,
headerCellInstReg = /Header - [A-Za-z]*/;
if (source.type === 'FRAME') {
if (source.parent && source.parent.name === 'pa-table-header') {
if (source.name.match(headerCelFrameReg)) {
return TABLE_PART.HeaderCellFrame;
} else {
return null;
}
} else if (source.name.match(bodyCelFrameReg)) {
return TABLE_PART.BodyCellFrame;
} else if (source.name.match(bodyColFrameReg)) {
return TABLE_PART.BodyColumnFrame;
} else {
return null;
}
} else if (source.type === 'INSTANCE') {
if (source.name.match(bodyCellInstReg)) {
return TABLE_PART.BodyCellInstance;
} else if (source.name.match(headerCellInstReg)) {
return TABLE_PART.HeaderCellInstance;
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Returns a frame node under the parent node; reuses one if it exists, otherwise
// creates a new one.
// This is applicable for a table frame constructed by this plugin:
// a table frame contains a collection of column frames, which contains a collection
// of cell frames.
function frameNodeOn({
parent,
colIndex,
rowIndex,
frameType = 'COLUMN',
height = table_style.rowHeight,
width = table_style.columnWidth,
}: {
parent: FrameNode;
colIndex: number;
rowIndex?: number;
frameType?: 'COLUMN' | 'CELL';
height?: number;
width?: number;
}): FrameNode {
if (frameType === 'COLUMN') {
const col = parent.children[colIndex];
const colName = 'col-' + colIndex;
if (col) {
col.name = colName;
const colEl = col as FrameNode;
colEl.children.forEach((c) => c.remove());
return colEl;
} else {
const colEl = baseFrameWithAutoLayout({
name: colName,
nodeType: 'FRAME',
direction: 'VERTICAL',
width: width,
padding: 0,
}) as FrameNode;
parent.appendChild(colEl);
return colEl;
}
} else if (frameType === 'CELL') {
const cell = parent.children[rowIndex];
// Something like 'cell-row-3-col-0'
const cellName = 'cell-row-' + rowIndex + '-col-' + colIndex;
if (cell) {
cell.name = cellName;
const cellEl = cell as FrameNode;
cellEl.children.forEach((c) => c.remove());
return cellEl;
} else {
// direction is VERTICAL so that the content of the instance node can wrap when resized
const cellEl = baseFrameWithAutoLayout({
name: cellName,
nodeType: 'FRAME',
direction: 'VERTICAL',
height: height,
width: width,
padding: 0,
}) as FrameNode;
parent.appendChild(cellEl);
return cellEl;
}
}
return null;
}
function updateStriped(striped: boolean) {
// First select the table body, pls
if (figma.currentPage.selection.length === 0) return;
// TODO. For now you have to select a table container frame. TODO: to select any child
const tableContainerEl = figma.currentPage.selection[0] as FrameNode;
if (tableContainerEl.name !== 'pa-table-comp') return;
const tableEl = tableContainerEl.findOne((d) => d.name === 'pa-table-container') as FrameNode;
if (!tableEl) return;
const tableBodyEl = tableEl.findOne((d) => d.name === 'pa-table-body') as FrameNode;
// TODO: Maybe we should get the color from the imported component named Default - Alt
const evenRowColor = striped ? {r: 244 / 255, g: 245 / 255, b: 245 / 255} : {r: 1, g: 1, b: 1};
if (tableBodyEl.name === 'pa-table-body') {
tableBodyEl.children.forEach((colEl) => {
const col = colEl as FrameNode;
col.children.forEach((cellEl) => {
const cell = cellEl as FrameNode;
const cellMatches = cell.name.match(/(?<=cell-row-)\d*/);
if (cellMatches.length > 0) {
const rowNum = cellMatches[0] as unknown;
const rowNum1 = rowNum as number;
// Swap the child
let srcInst = cell.children[0] as InstanceNode;
if (rowNum1 % 2 !== 0) {
// If this is an even row cell. Index is 0 based
// Repaint the backdrop color
cell.fills = [{type: 'SOLID', color: evenRowColor}];
const variantObj = srcInst.mainComponent['variantProperties'];
let destComp: ComponentNode;
if (srcInst.name === PRISMA_TABLE_COMPONENTS_INST_NAME['Cell - Text']) {
destComp = allTableComponents
.filter((d) => {
return d.compName === PRISMA_TABLE_COMPONENTS_INST_NAME['Cell - Text'];
})
.find((d) => {
return d.variantProperties['State'] === striped
? 'Default - Alt'
: 'Default' &&
d.variantProperties['Icon Left'] === variantObj['Icon Left'] &&
d.variantProperties['Icon Right'] === variantObj['Icon Right'] &&
d.variantProperties['Label'] === variantObj['Label'];
})['component'];
} else if (srcInst.name === PRISMA_TABLE_COMPONENTS_INST_NAME['Cell - Checkbox']) {
destComp = allTableComponents
.filter((d) => {
return d.compName === PRISMA_TABLE_COMPONENTS_INST_NAME['Cell - Checkbox'];
})
.find((d) => {
return d.variantProperties['State'] === striped
? 'Default - Alt'
: 'Default' && d.variantProperties['Type'] === variantObj['Type'];
})['component'];
}
srcInst.swapComponent(destComp);
}
// draw the line for a cell
const cellLine = srcInst.findChild((e) => e.name === 'bottom border');
cellLine.visible = !striped;
}
});
});
}
}
// Update row height for all the rows in this table
function updateRowHeight(target: SceneNode, height: number) {
// For now, make sure we are looking at a table
if (!target || target.type !== 'GROUP' || target.name !== 'pa-table-comp') return;
const tableContainerEl = target as GroupNode;
const tableEl = tableContainerEl.findOne((d) => d.name === 'pa-table-container') as FrameNode;
const tableBodyEl = tableEl.findOne((d) => d.name === 'pa-table-body') as FrameNode;
const cells = tableBodyEl.findAll((d) => d.type === 'FRAME' && d.name.includes('cell-row-')) as FrameNode[];
cells.forEach((cel) => {
const inst = (cel as FrameNode).children[0] as InstanceNode;
// Update target cell height
inst.resize(cel.width, height);
// Rig the auto-layout again after explicitly setting the instance node's height
inst.layoutAlign = 'STRETCH';
inst.layoutGrow = 1;
// Update the height for all the other cells in the same row
cel.resize(cel.width, height);
});
resizeColumnsHeight(tableBodyEl);
}
function resizeColumnsHeight(tableBodyEl: FrameNode) {
const colEls = tableBodyEl?.children;
// what is the column intrinsic height? And the tallest height of all columns?
const maxColHeight = colEls
?.map((col) => {
const _colHeight = (col as FrameNode)?.children.map((c) => c.height).reduce((h1, h2) => h1 + h2, 0);
return _colHeight;
})
.reduce((h1, h2) => (h1 > h2 ? h1 : h2));
colEls.forEach((col) => col.resize(col.width, maxColHeight));
}
// TODO: If a column has just been resized, we want to re-fill the text for all the cell-text
// instances in that column
function updateColumn(source: SceneNode) {
if (source === null) return;
// TMP. Currently only support when the column frame is resized
const reg = /(?<=col-)\d*/;
const matches = source.name.match(reg);
// if the user has just selected a column
if (matches !== null) {
const colEl = source as FrameNode;
colEl.children.forEach((el) => {
let inst = (el as FrameNode).children[0] as InstanceNode;
fillTableBodyCellWithText(inst, el.getPluginData('cellText'));
});
}
}
// target can be a frame cell or the instance node it contains
async function updateRow(source: SceneNode) {
// if it's a component instance
let cell, cellHeight;
if (tablePart(source) === TABLE_PART.BodyCellInstance) {
cell = source.parent;
} else if (tablePart(source) === TABLE_PART.BodyCellFrame) {
cell = source;
} else {
return;
}
cellHeight = source.height;
let row = rowForCell(cell);
row.forEach((cel) => {
const text = (cel as FrameNode).getPluginData('cellText');
const inst = (cel as FrameNode).children[0] as InstanceNode;
// Update target cell height
inst.resize(cel.width, cellHeight);
// Rig the auto-layout again after explicitly setting the instance node's height
inst.layoutAlign = 'STRETCH';
inst.layoutGrow = 1;
// Update the height for all the other cells in the same row
cel.resize(cel.width, cellHeight);
const thisInst = (cell as FrameNode).children[0] as InstanceNode;
const insto = (cel as FrameNode).children[0] as InstanceNode;
// Update the text
if (text !== '') {
console.log('___>>is about to update text....');
fillTableBodyCellWithText(inst, text);
}
// Update the mouse states to be the same as the target
updateCompMouseState(thisInst, insto);
});
}
// if the source inst comp is HOVER/SELECTED, then find the non-hover/selected version
// if the source inst comp is alt, then find both the default and even versions
// Update the target's mouse state according to the source's: this is mostly used when we want to update the whole row
// TODO: FIXME: Not working when striped is off
// TODO: FIXME: Not quite working on header checkbox
function updateCompMouseState(source: InstanceNode, destination: InstanceNode) {
// Find the source and the destination comp info
const srcCompInfo: object = source.mainComponent['variantProperties'];
const destCompInfo: object = destination.mainComponent['variantProperties'];
// What's the desired comp we want?
let expCompo: tableCompInfo;
if (destination.name === PRISMA_TABLE_COMPONENTS_INST_NAME['Cell - Text']) {
expCompo = allTableComponents
.filter((d) => d.compName === PRISMA_TABLE_COMPONENTS_INST_NAME['Cell - Text'])
.find((d) => {
const _criteriaCheckboxSrc = d.variantProperties['State'] === srcCompInfo['State'];
const _criteriaCellTextSrc =
d.variantProperties['Icon Left'] === destCompInfo['Icon Left'] &&
d.variantProperties['Icon Right'] === destCompInfo['Icon Right'] &&
d.variantProperties['Label'] === destCompInfo['Label'] &&
d.variantProperties['State'] === srcCompInfo['State'];
if (source.name === 'Cell - Text') {
return _criteriaCellTextSrc;
} else if (source.name === 'Cell - Checkbox') {
return _criteriaCheckboxSrc;
} else {
console.error('Error assessing criteria for updating row cells.');
return undefined;
}
});
} else if (destination.name === PRISMA_TABLE_COMPONENTS_INST_NAME['Cell - Checkbox']) {
expCompo = allTableComponents
.filter((d) => d.compName === PRISMA_TABLE_COMPONENTS_INST_NAME['Cell - Checkbox'])
.filter((d) => d.variantProperties['State'] === srcCompInfo['State'])
.find(
(d) => d.variantProperties['Type'] === (srcCompInfo['State'] === 'Selected' ? 'Selected' : 'Unselected')
);
}
if (expCompo) {
destination.swapComponent(expCompo['component']);
}
}
// Update the target's icon state (e.g., icon left/right/label) according to the source's while keeping the target's mouse state:
// This is mostly applicable when we want to update the whole column
function updateCompIconLabelVariant(source: InstanceNode, destination: InstanceNode) {
// Find the source and the destination comp info
const srcCompoInfo: object = source['variantProperties'];
const destCompInfo: object = destination['variantProperties'];
if (!srcCompoInfo || !destCompInfo) return;
// What's the desired comp we want?
const expCompo: ComponentNode = allTableComponents
.filter((d) => d.compName === PRISMA_TABLE_COMPONENTS_INST_NAME['Cell - Text'])
.find((d) => {
return (
d.variantProperties['Icon Left'] === srcCompoInfo['Icon Left'] &&
d.variantProperties['Icon Right'] === srcCompoInfo['Icon Right'] &&
d.variantProperties['Label'] === srcCompoInfo['Label'] &&
d.variantProperties['State'] === destCompInfo['State']
);
})['component'];
destination.swapComponent(expCompo);
}
// TODO: FIXME: Not working on header checkboxes
async function updateColumnComps(source: SceneNode) {
if (!source || (source.type !== 'INSTANCE' && source.type !== 'FRAME')) return;
if (
(source.type === 'INSTANCE' && source.name === PRISMA_TABLE_COMPONENTS_INST_NAME['Cell - Text']) ||
(source.type === 'FRAME' && source.name.includes('cell-row-'))
) {
// find all the instance for the column
let sourceInst: InstanceNode;
if (source.type === 'INSTANCE') {
sourceInst = source as InstanceNode;
} else if (source.type === 'FRAME') {
sourceInst = (source as FrameNode).children[0] as InstanceNode;
}
const colEl = sourceInst.parent.parent as FrameNode;
colEl.children.forEach((cellEl) => {
let targetInst = (cellEl as FrameNode).children[0] as InstanceNode;
updateCompIconLabelVariant(sourceInst, targetInst);
});
} else {
// console.log('It IS NOT SUPPORTED...');
}
}
async function updateColumnIcons(source: TextNode) {
// Don't update the text unless it's a left/right icon.
if (source.name !== 'exclamation-triangle' && source.name !== 'angle-right') return;
await figma.loadFontAsync({family: 'Font Awesome 5 Pro', style: 'Solid'});
const sourceInst = source.parent as InstanceNode;
const colEl = sourceInst.parent.parent as FrameNode;
const sourceIcon: TextNode = sourceInst.findChild((d) => d.name === source.name) as TextNode;
if (!sourceIcon) return;
colEl.children.forEach((el) => {
let targetInst = (el as FrameNode).children[0] as InstanceNode;
updateCompIconLabelVariant(sourceInst, targetInst);
// Prisma Library is using icon font for left/right icons
const targetIcon: TextNode = targetInst.findChild((d) => d.name === source.name) as TextNode;
if (targetIcon) {
loadFontForTextNode(targetIcon);
targetIcon.characters = sourceIcon.characters;
}
});
}
// TODO: lorem email by a domain name from a body text cell
async function updateColumnTextFromHeader(source: TextNode) {
// first scenario: user just changed header: Email
if (source.name === 'Label') {
// see if we need to do "smart lorem"
const headerText = source.characters?.toLowerCase();
const sourceInst = source.parent as InstanceNode;
if (sourceInst.name == '_Header') {
// if the parent container of the text is named '_Header' (Prisma Component Library convention), we assume it's a header, then try to find the corresponding column and apply lorem text to each cell
const headerCellEl = sourceInst.parent?.parent;
if (!headerCellEl) return;
const reg = /(?<=col-)\d*/;
const matches = headerCellEl.name.match(reg);
if (matches !== null) {
const colIndex = matches[0];
// _apply lorem ipsum
const headerEl = headerCellEl.parent;
const tableEl = headerEl?.parent; //.name should be 'pa-table-container'
const tableBodyEl = tableEl.findChild((d) => d.name === 'pa-table-body') as FrameNode;
const bodyColEl = tableBodyEl.findChild((d) => d.name === 'col-' + colIndex) as FrameNode;
bodyColEl.children.forEach((cellEl) => {
const cellInst = (cellEl as FrameNode)?.children[0] as InstanceNode;
// const text = cellEl.getPluginData('cellText');
if (cellInst) {
const text = smartLorem(headerText);
fillTableBodyCellWithText(cellInst, text);
cellEl.setPluginData('cellText', text);
}
});
}
}
}
// second scenario: user just changed body: att.com
}
async function updateColumnTextFromCell(source: TextNode) {
// see if it's a cell and the text is an email
const emailDm = emailDomainFromString(source.characters);
if (emailDm) {
// TODO: refactor to a separate function?
if (source.name === 'Label' && source?.parent?.name === 'Cell - Text') {
if (tablePart(source?.parent?.parent?.parent as SceneNode) == TABLE_PART.BodyColumnFrame) {
const colEl = source?.parent?.parent?.parent as FrameNode;
colEl.children.forEach((cellEl) => {
const cellInst = (cellEl as FrameNode)?.children[0] as InstanceNode;
if (cellInst) {
const text = randomUserName() + emailDm;
fillTableBodyCellWithText(cellInst, text);
cellEl.setPluginData('cellText', text);
}
});
}
}
}
}
function updateColumnHeader(source: any) {
if (!source) return;
const reg = /(?<=col-)\d*/;
const matches = source.name.match(reg);
// if the user has just selected a column
if (matches !== null) {
const parentName = source.parent.name;
const colIndex = matches[0];
const w = (source as FrameNode).width;
if (parentName !== 'pa-table-body' && parentName !== 'pa-table-header') return;
// resize the corresponding header
if (parentName === 'pa-table-body') {
const headerContainer = source.parent.parent.findChild((d) => d.name === 'pa-table-header') as FrameNode;
const columnHeaderContainer = headerContainer.findChild((d) => d.name === 'col-' + colIndex);
columnHeaderContainer.resize(w, table_style.headerHeight);
} else if (parentName === 'pa-table-header') {
const boydColumnContainer = source.parent.parent.findChild((d) => d.name === 'pa-table-body') as FrameNode;
const columnContainer = boydColumnContainer.findChild((d) => d.name === 'col-' + colIndex);
columnContainer.resize(w, columnContainer.height);
}
}
}
// Update table size including the background
// TODO: Currently only updates when the title inst has been resized.
function updateTableSize(source: SceneNode) {
console.log('>>> update table size.... for ', source);
if (source?.type === 'INSTANCE' && source?.name === 'Card / Header') {
const _titleInst = source as InstanceNode;
const _tableTitle = source?.parent as FrameNode;
const _tableEl = _tableTitle?.parent as FrameNode;
const tableContainer = _tableEl?.parent as FrameNode;
const _tableBackground = tableContainer?.findOne((d) => d.name === 'Table - Background');
const _tableOverlay = tableContainer?.findOne((d) => d.name === 'pa-table-overlay');
// update size
_tableTitle.resize(_titleInst.width, _titleInst.height);
let _tableHeight = 0,
_tableWidth = _tableEl?.width;
_tableEl?.children?.forEach((d) => {
_tableHeight += d.height;
});
_tableEl?.resize(_tableWidth, _tableHeight);
_tableBackground?.resize(_tableWidth, _tableHeight);
_tableOverlay?.resize(_tableWidth, _tableHeight);
} else if (source?.type === 'FRAME' && source?.name.match(/cell-row-\d-col-\d/)?.length > 0) {
// if it's a column frame
const _tableBodyEl = (source as FrameNode).parent.parent as FrameNode;
resizeColumnsHeight(_tableBodyEl);
}
}
function updateTableColumns(sourceObj: any) {
const source = figma.currentPage.findOne((n) => n.id === sourceObj.id);
// if the column has just been deleted
if (source === null) {
if (sourceObj.colId === '') return; // This was not a column
const colEl = figma.getNodeById(sourceObj.assColId) as FrameNode;
colEl?.remove();
return;
} else {
// is this a new column by user duplicating it in Figma designer?
if (sourceObj.tableId) {
const tableEl = figma.getNodeById(sourceObj.tableId) as FrameNode;
const headerEl = tableEl.findChild((o) => o.name === 'pa-table-header') as FrameNode;
const bodyEl = tableEl.findChild((o) => o.name === 'pa-table-body') as FrameNode;
let bodyColInHeader = [];
headerEl &&
headerEl.children.forEach((o, _) => {
bodyColInHeader.push(o.getPluginData('assColId'));
});
const bodyColInBody = bodyEl.children.map((d) => d.id);
// TMP. For now, we just consider one dup:
const dupIds = dups(bodyColInHeader);
if (dupIds.length > 0) {
const dupId = dupIds[0];
const dupBodyIndicesInHeader = bodyColInHeader
.map((d, i) => {
if (d === dupId) {
return i;
} else return null;
})
.filter((d) => d !== null);
const colIndicesInBody = bodyColInBody
.map((d, i) => {
if (d === dupId) {
return i;
} else return null;
})
.filter((d) => d !== null);
if (dupBodyIndicesInHeader.length > colIndicesInBody.length) {
// We need to duplicate a column in the body
let a = new Set(dupBodyIndicesInHeader);
let b = new Set(colIndicesInBody);
let difference = new Set([...a].filter((x) => !b.has(x)));
let j = Array.from(difference)[0]; // this is where we need to insert the new col into body col
const newCol = (figma.getNodeById(dupId) as FrameNode).clone();
bodyEl.insertChild(j, newCol);
// // We also need to rename the new columns so that their "indices" are the largest
// const dupIndex = colIndicesInBody[0]; // We now have 2 co-{dupIndex} in both header and body
// const newIndex = headerEl.children.length - 1;
// const dupHeaderCol = headerEl.children.find( el => el.name == 'col-' + dupIndex);
// dupHeaderCol.name = 'col-' + newIndex;
// const dupBodyCol = bodyEl.children.find( el => el.name == 'col-' + dupIndex);
// dupBodyCol.name = 'col-' + newIndex;
}
}
// bodyEl &&
// bodyEl.children.forEach((o, i) => {
// console.log('body #', i, ':', o.id);
// });
// 1. find which id is duplicate
// 2. find the counterpart (body<->header) to the existing id for where the id is
// 3. there should be an additional id for the duplicate. we should clone the id
// and insert it there
// console.log('columnEl???', colEl, 'tableEl?', tableEl, '; header?', headerEl, '; body?', bodyEl);
// if (colEl) {
// // const k = colEl.clone();
// // find where the duplicate occurs
// // insert the clone into that position
// // figma.currentPage.selection = [k];
// // figma.viewport.scrollAndZoomIntoView([k]);
// }
}
}
}
/* ** Return all the cells in the same row as the cell specified */
function rowForCell(cell: SceneNode): SceneNode[] {
const reg = /\d+/;
const rowMatches = cell.name.match(reg);
if (rowMatches.length > 0) {
let result = [];
const rowIndex = rowMatches[0];
const tableEl = cell.parent.parent;
tableEl.children.forEach((colNode, j) => {
const colEl = colNode as DefaultFrameMixin;
// cell-row-0-col-0
const celEl = colEl.findChild((n) => n.type === 'FRAME' && n.name === 'cell-row-' + rowIndex + '-col-' + j);
result.push(celEl);
});
return result;
}
return null;
}
// Select all the cells in the row where the user needs to select a cell on this row first.
function selectRow() {
const sel = figma.currentPage.selection.concat()[0];
let cell;
if (sel.type === 'INSTANCE') {
cell = sel.parent;
} else if (sel.type === 'FRAME') {
cell = sel;
}
let _row = rowForCell(cell);
if (_row) figma.currentPage.selection = _row;
}
// Quick and dirty way to see if the selection is a table
function isTable(selection: readonly SceneNode[]): boolean {
return selection.length === 1 && selection[0].name === 'pa-table-container';
}
// Draw table including pagination and title.
function drawTableComp(data) {
console.log('>>>draw table with data:::', data);
const tableElWidth = 1440 - 32 * 2;
Promise.all([
drawTableTitle(data),
drawTableHeader(data),
drawTableBody2({data: data, width: tableElWidth}),
// drawTableBodyFixedColumns(data),
]).then(
([
title,
header,
body,
// fixedbody
]) => {
const bkg = allTableComponents
.find((d) => d.compName === PRISMA_TABLE_COMPONENTS_INST_NAME['Table - Background'])
['component'].createInstance() as InstanceNode;
const tableContainerEl = figma.createFrame();
tableContainerEl.name = 'pa-table-container';
tableContainerEl.layoutMode = 'VERTICAL';
tableContainerEl.layoutGrow = 1;
tableContainerEl.clipsContent = false;