-
-
Notifications
You must be signed in to change notification settings - Fork 162
/
Copy pathmain.js
1366 lines (1155 loc) · 48.8 KB
/
main.js
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
//constant variables to be used throughout
const {Artboard, Text, Group, RepeatGrid, SymbolInstance, Color, BitmapFill, LinearGradientFill, RadialGradientFill, Shadow} = require("scenegraph");
const uxp = require("uxp");
const application = require("application");
//const cfURLPrefix = "http://192.168.0.199/canvasflip_latest";
const cfURLPrefix = "https://www.canvasflip.com";
//global variables predefined
let pluginFolder = null;
let localStorageFolder = null;
let localStorageFile = null;
let localStorage = null;
let dialog = null;
let $ = null;
let projects = [];
let selectedArtboards = [];
let syncData = null;
let syncBackData = null;
let newProjectCreated = 0;
//load all resources upfront like localstorage files
async function loadResources() {
pluginFolder = await uxp.storage.localFileSystem.getPluginFolder();
//load local storage file
localStorageFolder = await uxp.storage.localFileSystem.getDataFolder();
localStorageFile = (await localStorageFolder.getEntries()).filter(entry => entry.name.indexOf("scribble_plugin_data.json") >= 0);
if (localStorageFile.length > 0) {
localStorageFile = localStorageFile[0];
//read scribble_plugin_data.json
localStorage = await localStorageFile.read();
localStorage = JSON.parse(localStorage);
} else {
//create scribble_plugin_data.json and write
localStorage = {
data: {
user: {
id: 0,
name: "",
token: ""
},
selected_project: 0,
is_sync_all: 0
}
};
localStorageFile = await localStorageFolder.createEntry("scribble_plugin_data.json", {
overwrite: true
});
await localStorageFile.write(JSON.stringify(localStorage));
}
}
loadResources();
async function syncArtboardsHandlerFunction(selection, documentRoot) {
$ = selection => document.querySelector(selection);
await loadDialog();
if (localStorage != null && localStorage.data.user.token.length == 0 || localStorage.data.user.id == 0) {
//open login dialog
openLoginDialog(selection, documentRoot, "sync");
} else {
//open sync dialog
openSyncDialog(selection, documentRoot);
}
return dialog.showModal().then(async result => {
//code after close
if (syncData != null) {
let response = {
project_uuid: "",
page_uuid: ""
};
for (var i = 0; i < syncData.length; i++) {
var artboard = syncData[i].artboard;
var data = syncData[i].data;
//generate thumbnail image
//let scale = parseFloat(250 / item.globalBounds.width).toFixed(2);
let thumbBase64 = await specs.layerToBase64(artboard, 1);
//iterate through all text layers and hide it before taking screenshot image
specs.showHideArtboardTextLayers(artboard, null, data.layers, false);
//generate full image
let base64 = await specs.layerToBase64(artboard, 1);
//iterate through all text layers and show it
specs.showHideArtboardTextLayers(artboard, null, data.layers, true);
var syncArtboardsData = {
filename: artboard.name + ".png",
height: artboard.globalBounds.height,
width: artboard.globalBounds.width,
projectId: localStorage.data.selected_project,
isSyncAll: localStorage.data.is_sync_all,
userId: localStorage.data.user.id,
token: localStorage.data.user.token,
specs: data,
weight: data.weight
};
response = await api.syncArtboard(syncArtboardsData, base64, thumbBase64);
}
//load complete dialog
let loginCSS = (await pluginFolder.getEntry("html/common.css"));
loginCSS = await loginCSS.read();
document.body.innerHTML = "<style>" + loginCSS + "</style>" +
"<dialog id='dialog'></dialog>";
dialog = $("#dialog");
let syncCompleteHTML = (await pluginFolder.getEntry("html/sync-complete.html"));
syncCompleteHTML = await syncCompleteHTML.read();
$("#dialog").innerHTML = syncCompleteHTML;
//render header logo image
let syncCompletedIMG = (await pluginFolder.getEntry("images/sync_completed.png"));
syncCompletedIMG = await syncCompletedIMG.read({format: uxp.storage.formats.binary});
$("#syncCompletedIMG").src = "data:image/png;base64," + utils.binaryToBase64(syncCompletedIMG);
//render header logo image
let logoIMG = (await pluginFolder.getEntry("images/logo_header.png"));
logoIMG = await logoIMG.read({format: uxp.storage.formats.binary});
$("#logoHeader").src = "data:image/png;base64," + utils.binaryToBase64(logoIMG);
//show link
var link = "";
if (syncData.length > 1) {
link += "/vi/share/?project=" + response.project_uuid;
} else {
link += "/vi/scribble/?page=" + response.page_uuid;
}
$("#syncCompleteText").value = cfURLPrefix + link;
$("#goToPreviewLink").setAttribute("href", cfURLPrefix + link);
$("#close").addEventListener("click", () => {
dialog.close();
});
//empty syncData and show complete dialog
syncData = null;
return dialog.showModal().then(result => {
});
}
});
}
async function syncBackArtboardsHandlerFunction(selection, documentRoot) {
$ = selection => document.querySelector(selection);
await loadDialog();
if (localStorage != null && localStorage.data.user.token.length == 0 || localStorage.data.user.id == 0) {
//open login dialog
openLoginDialog(selection, documentRoot, "sync-back");
} else {
//open sync dialog
openSyncBackDialog(selection, documentRoot);
}
return dialog.showModal().then(async result => {
//code after close
if (syncBackData != null) {
for (var i = 0; i < syncBackData.artboards.length; i++) {
let layers = [];
//iterate all artboards
selectedArtboards.forEach(function (item) {
if (item instanceof Artboard) {
if (syncBackData.artboards[i].name == item.name) {
let specs = new Specs();
layers = specs.setArtboard(item, null, syncBackData.artboards[i].scribble);
}
}
});
//iterate all children and change text
for (var j = 0; j < layers.length; j++) {
layers[j].child.text = layers[j].content;
}
}
//load complete dialog
let loginCSS = (await pluginFolder.getEntry("html/common.css"));
loginCSS = await loginCSS.read();
document.body.innerHTML = "<style>" + loginCSS + "</style>" +
"<dialog id='dialog'></dialog>";
dialog = $("#dialog");
let syncCompleteHTML = (await pluginFolder.getEntry("html/sync-back-complete.html"));
syncCompleteHTML = await syncCompleteHTML.read();
$("#dialog").innerHTML = syncCompleteHTML;
//render sync completed icon
let syncCompletedIMG = (await pluginFolder.getEntry("images/sync_completed.png"));
syncCompletedIMG = await syncCompletedIMG.read({format: uxp.storage.formats.binary});
$("#syncCompletedIMG").src = "data:image/png;base64," + utils.binaryToBase64(syncCompletedIMG);
//render header logo image
let logoIMG = (await pluginFolder.getEntry("images/logo_header.png"));
logoIMG = await logoIMG.read({format: uxp.storage.formats.binary});
$("#logoHeader").src = "data:image/png;base64," + utils.binaryToBase64(logoIMG);
//show link
var link = "";
if (syncBackData.artboards.length > 1) {
link += "/vi/share/?project=" + syncBackData.project_uuid;
} else {
link += "/vi/scribble/?page=" + syncBackData.page_uuid;
}
$("#syncCompleteText").value = cfURLPrefix + link;
$("#goToPreviewLink").setAttribute("href", cfURLPrefix + link);
$("#close").addEventListener("click", () => {
dialog.close();
});
//empty syncBackData and show complete dialog
syncBackData = null;
return dialog.showModal().then(result => {
});
}
});
}
async function loadDialog() {
let loginCSS = (await pluginFolder.getEntry("html/common.css"));
loginCSS = await loginCSS.read();
document.body.innerHTML = "<style>" + loginCSS + "</style>" +
"<dialog id='dialog'></dialog>";
dialog = $("#dialog");
}
//open login dialog
async function openLoginDialog(selection, documentRoot, action) {
//read login html
let loginHTML = (await pluginFolder.getEntry("html/login.html"));
loginHTML = await loginHTML.read();
$("#dialog").innerHTML = loginHTML;
//render header logo image
let logoIMG = (await pluginFolder.getEntry("images/logo_header.png"));
logoIMG = await logoIMG.read({format: uxp.storage.formats.binary});
$("#logoHeader").src = "data:image/png;base64," + utils.binaryToBase64(logoIMG);
let [close, loginBtn, email, password, error] = ["#close", "#loginBtn", "#emailID", "#password", "#error"].map(s => $(s));
//Login button Click
loginBtn.addEventListener("click", async () => {
//login
let data = await api.login(email.value, password.value);
data = JSON.parse(data);
if (data != "error" && data.result == "success") {
async function writePluginData(data) {
//read scribble_plugin_data.json and populate user data
localStorage.data.user.id = data.id;
localStorage.data.user.name = data.name;
localStorage.data.user.token = data.token;
//save data to file
await localStorageFile.write(JSON.stringify(localStorage));
try {
if (action == "sync") {
await openSyncDialog(selection, documentRoot);
} else {
await openSyncBackDialog(selection, documentRoot);
}
} catch (e) {
console.log("Exception occurred: " + e);
}
}
writePluginData(data);
} else {
error.style.opacity = 1;
}
});
close.addEventListener("click", () => {
dialog.close();
});
}
//open Create Project dialog
async function openCreateProjectDialog(selection, documentRoot) {
//read login html
let createProjectHTML = (await pluginFolder.getEntry("html/create-project.html"));
createProjectHTML = await createProjectHTML.read();
$("#dialog").innerHTML = createProjectHTML;
//render header logo image
let logoIMG = (await pluginFolder.getEntry("images/logo_header.png"));
logoIMG = await logoIMG.read({format: uxp.storage.formats.binary});
$("#logoHeader").src = "data:image/png;base64," + utils.binaryToBase64(logoIMG);
let [close, createProjectBtn, projectName, error, backToSync] = ["#close", "#createProjectBtn", "#projectName", "#error", "#backToSync"].map(s => $(s));
//Login button Click
createProjectBtn.addEventListener("click", async () => {
let data = await api.createProject(localStorage.data.user.id, localStorage.data.user.token, projectName.value);
data = JSON.parse(data);
if (data != "error" && data.result == "success") {
//Set global variable newProjectCreated to 1 for set new project in selection
newProjectCreated = 1;
// openSyncDialog will take one new parameter newProjectCreated
await openSyncDialog(selection, documentRoot);
} else {
error.style.opacity = 1;
}
});
//Back to sync
backToSync.addEventListener("click", async function () {
await openSyncDialog(selection, documentRoot);
});
close.addEventListener("click", () => {
dialog.close();
});
}
//open sync dialog
async function openSyncDialog(selection, documentRoot) {
//read sync html
let syncHTML = (await pluginFolder.getEntry("html/sync.html"));
syncHTML = await syncHTML.read();
$("#dialog").innerHTML = syncHTML;
//render header logo image
let logoIMG = (await pluginFolder.getEntry("images/logo_header.png"));
logoIMG = await logoIMG.read({format: uxp.storage.formats.binary});
$("#logoHeader").src = "data:image/png;base64," + utils.binaryToBase64(logoIMG);
let [close, logoutBtn, syncBtn, selectProject, selectProjectLoading, syncAll, syncSelected, error, createProject] = ["#close", "#logoutBtn", "#syncBtn", "#selectProject", "#selectProjectLoading", "#syncAll", "#syncSelected", "#error", "#createProject"].map(s => $(s));
//set checkboxes
if (localStorage.data.is_sync_all) {
syncAll.checked = true;
syncSelected.checked = false;
} else {
syncAll.checked = false;
syncSelected.checked = true;
}
syncAll.addEventListener("click", () => {
localStorage.data.is_sync_all = 1;
syncAll.checked = true;
syncSelected.checked = false;
});
syncSelected.addEventListener("click", () => {
localStorage.data.is_sync_all = 0;
syncAll.checked = false;
syncSelected.checked = true;
});
selectProject.addEventListener("change", () => {
localStorage.data.selected_project = selectProject.value;
});
logoutBtn.addEventListener("click", async () => {
localStorage.data.user.id = 0;
localStorage.data.user.name = "";
localStorage.data.user.token = "";
//save updated data to file
await localStorageFile.write(JSON.stringify(localStorage));
try {
await openLoginDialog(selection, documentRoot, "sync");
} catch (e) {
console.log("Exception occurred: " + e);
}
});
syncBtn.addEventListener("click", async () => {
if (localStorage.data.selected_project > 0) {
var artboardWeight = 1000,
artboardsCount = 0;
if (localStorage.data.is_sync_all) {
selectedArtboards = documentRoot.children;
} else {
selectedArtboards = selection.items;
}
//iterate all artboards
syncData = [];
selectedArtboards.forEach(async function (item) {
if (item instanceof Artboard) {
//artboard found
artboardsCount++;
//get specs
let data = specs.getArtboard(item, null, null);
data.weight = artboardWeight;
syncData.push({
artboard: item,
data: data
});
//increment artboardWeight
artboardWeight = artboardWeight + 1;
}
});
if (artboardsCount == 0) {
syncData = null;
error.style.opacity = 1;
} else {
//save updated data to file
await localStorageFile.write(JSON.stringify(localStorage));
await dialog.close();
}
} else {
error.style.opacity = 1;
}
});
createProject.addEventListener("click", async () => {
try {
// Open Create Project Dialog
await openCreateProjectDialog(selection, documentRoot);
} catch (e) {
console.log("Exception occurred: " + e);
}
});
close.addEventListener("click", () => {
dialog.close();
});
await loadProjects(selectProject, selectProjectLoading);
}
async function loadProjects(selectProject, selectProjectLoading) {
//populate projects afetr open dialog
let data = await api.getProjects(localStorage.data.user.id, localStorage.data.user.token);
data = JSON.parse(data);
if (data != "error" && data.result == "success") {
projects = data.projects;
if (projects.length > 0) {
let projectOptions = "";
let selectedIndex = 0;
for (let i = 0; i < projects.length; i++) {
if (projects[i].id == localStorage.data.selected_project) {
//select this project by default
selectedIndex = i;
}
projectOptions += "<option value='" + projects[i].id + "'>" + projects[i].title + "</option>";
}
// Set selectedIndex to 0 if called from newProjectCreated
if (newProjectCreated == 1) {
selectedIndex = 0;
}
selectProject.innerHTML = projectOptions;
selectProject.style.display = "block";
selectProjectLoading.style.display = "none";
selectProject.selectedIndex = selectedIndex;
if (selectedIndex == 0) {
//no project is localStorage
localStorage.data.selected_project = projects.length > 0 ? projects[0].id : 0;
}
} else {
selectProjectLoading.text("No projects yet!")
}
}
}
//open sync dialog
async function openSyncBackDialog(selection, documentRoot) {
//read sync html
let syncBackHTML = (await pluginFolder.getEntry("html/sync-back.html"));
syncBackHTML = await syncBackHTML.read();
$("#dialog").innerHTML = syncBackHTML;
//render header logo image
let logoIMG = (await pluginFolder.getEntry("images/logo_header.png"));
logoIMG = await logoIMG.read({format: uxp.storage.formats.binary});
$("#logoHeader").src = "data:image/png;base64," + utils.binaryToBase64(logoIMG);
let [close, logoutBtn, syncBtn, selectProject, selectProjectLoading, syncAll, syncSelected, error] = ["#close", "#logoutBtn", "#syncBtn", "#selectProject", "#selectProjectLoading", "#syncAll", "#syncSelected", "#error"].map(s => $(s));
//set checkboxes
if (localStorage.data.is_sync_all) {
syncAll.checked = true;
syncSelected.checked = false;
} else {
syncAll.checked = false;
syncSelected.checked = true;
}
syncAll.addEventListener("click", () => {
localStorage.data.is_sync_all = 1;
syncAll.checked = true;
syncSelected.checked = false;
});
syncSelected.addEventListener("click", () => {
localStorage.data.is_sync_all = 0;
syncAll.checked = false;
syncSelected.checked = true;
});
selectProject.addEventListener("change", () => {
localStorage.data.selected_project = selectProject.value;
});
logoutBtn.addEventListener("click", async () => {
localStorage.data.user.id = 0;
localStorage.data.user.name = "";
localStorage.data.user.token = "";
//save updated data to file
await localStorageFile.write(JSON.stringify(localStorage));
try {
await openLoginDialog(selection, documentRoot, "sync-back");
} catch (e) {
console.log("Exception occurred: " + e);
}
});
syncBtn.addEventListener("click", async () => {
if (localStorage.data.selected_project > 0) {
var artboardsCount = 0,
artboardNames = [];
if (localStorage.data.is_sync_all) {
selectedArtboards = documentRoot.children;
} else {
selectedArtboards = selection.items;
}
//iterate all artboards
selectedArtboards.forEach(function (item) {
if (item instanceof Artboard) {
//artboard found
artboardsCount++;
artboardNames.push(item.name);
}
});
let syncBackArtboardsData = {
artboards: artboardNames,
project_id: localStorage.data.selected_project,
user_id: localStorage.data.user.id,
user_token: localStorage.data.user.token,
is_sync_all: localStorage.data.is_sync_all
}
syncBackData = await api.syncBackArtboards(syncBackArtboardsData);
if (artboardsCount == 0) {
syncBackData = null;
error.style.opacity = 1;
} else {
//save updated data to file
await localStorageFile.write(JSON.stringify(localStorage));
await dialog.close();
}
} else {
error.style.opacity = 1;
}
});
close.addEventListener("click", () => {
dialog.close();
});
await loadProjects(selectProject, selectProjectLoading);
}
module.exports = {
commands: {
syncArtboards: syncArtboardsHandlerFunction,
syncBackArtboards: syncBackArtboardsHandlerFunction
}
};
class Specs {
constructor() {
}
async layerToBase64(layer, scale) {
try {
let tempFolder = await uxp.storage.localFileSystem.getTemporaryFolder();
let tempFile = await tempFolder.createEntry(Math.random().toString(36).substr(7) + ".png", {
overwrite: true
});
let promise = new Promise(function (resolve, reject) {
application.createRenditions([{
node: layer,
outputFile: tempFile,
type: application.RenditionType.PNG,
scale: scale
}]).then(async function (files) {
let buffer = await files[0].outputFile.read({format: uxp.storage.formats.binary});
let binaryData = "";
let bytes = new Uint8Array(buffer);
let byteLength = bytes.byteLength;
for (var i = 0; i < byteLength; i++) {
binaryData += String.fromCharCode(bytes[i]);
}
resolve(window.btoa(binaryData));
}).catch(function (error) {
reject(error);
});
});
return await promise;
} catch (e) {
console.log("Exception occurred: " + e);
}
return null;
}
getArtboard(artboard, symbol, symbolOffset) {
//return if not instance of artboard or symbol
if (!(artboard instanceof Artboard || symbol instanceof SymbolInstance || symbol instanceof Group || symbol instanceof RepeatGrid)) {
return;
}
var self = this;
var layers = [];
var artboardBound = null;
var artboardChildren = [];
if (symbol instanceof SymbolInstance) {
artboardBound = symbol.globalBounds;
artboardChildren = symbol.children;
} else if (symbol instanceof Group || symbol instanceof RepeatGrid) {
artboardBound = artboard.globalBounds;
artboardChildren = symbol.children;
} else if (artboard instanceof Artboard) {
artboardBound = artboard.globalBounds;
artboardChildren = artboard.children;
}
//iterate all children inside this artboard/symbol
artboardChildren.forEach(function (child) {
var layer = {};
if (child instanceof Text) {
//text found
try {
//set rect with artboardBound offset
layer.rect = self.getLayerRect(child.globalBounds, artboardBound);
if (symbol instanceof SymbolInstance) {
//set rect with symbol offset
layer.rect.x = symbolOffset.x + layer.rect.x;
layer.rect.y = symbolOffset.y + layer.rect.y;
}
//set layer properties
layer.sid = child.guid;
layer.name = child.name;
layer.fixedWidth = 0;
//rotation
layer.rotation = child.rotation;
//opacity
layer.opacity = child.opacity;
//TODO: radius
//TODO: borders
//TODO: fills
//var fills = self.getLayerFills(child, child.fill);
//if (fills.length > 0)
//layer.fills = fills;
//TODO: shadow
//var shadow = self.getLayerShadow(child);
//if (shadow.length > 0)
//layer.shadow = shadow;
layer.font = {
content: child.text,
override: null,
font: child.styleRanges.length > 0 ? child.styleRanges[0].fontFamily : "",
size: child.styleRanges.length > 0 ? child.styleRanges[0].fontSize : "",
line: child.lineSpacing,
spacing: {
char: 0, //TODO: char spacing
para: 0, //TODO: para spacing
},
align: child.textAlign,
color: self.getLayerColor(child, child.fill),
transform: 0 //TODO: transform
}
try {
//extract attribute styles
var styles = [];
var rangeIndex = 0;
child.styleRanges.forEach(function (style) {
if (style.length > 0) {
styles.push({
content: child.text.substr(rangeIndex, style.length),
font: style.fontFamily,
size: style.fontSize,
line: 0,
spacing: {
char: 0, //ToDo: Due to bug in XD temp 0 have assign rather this "layer.font.spacing.char"style.charSpacing,
para: 0
},
align: "left",
color: self.getLayerColor(child, style.fill),
transform: 0
});
rangeIndex += style.length;
}
});
if (styles.length > 0 && child.text.length > rangeIndex) {
//style ranges are finished but texts remaining at end
styles.push({
content: child.text.substr(rangeIndex, child.text.length),
font: styles[styles.length - 1].font,
size: styles[styles.length - 1].size,
line: styles[styles.length - 1].line,
spacing: {
char: 0, //ToDo: Due to bug in XD temp 0 have assign rather this "layer.font.spacing.char",
para: styles[styles.length - 1].spacing.para,
},
align: styles[styles.length - 1].align,
color: styles[styles.length - 1].color,
transform: styles[styles.length - 1].transform
});
}
} catch (e) {
console.log("Exception occurred: " + e);
}
if (styles.length == 0) {
styles.push({
content: layer.font.override != null ? layer.font.override : layer.font.content,
font: layer.font.font,
size: layer.font.size,
line: layer.font.line,
spacing: {
char: 0, //ToDo: Due to bug in XD temp 0 have assign rather this "layer.font.spacing.char"
para: layer.font.spacing.para
},
align: layer.font.align,
color: layer.font.color,
transform: layer.font.transform
});
}
layer.font.styles = styles;
} catch (e) {
console.log("Exception occurred: " + e);
}
//TODO: masking
/*if (msLayer.hasClippingMask()) {
this.maskObjectID = (msGroup != null ? msGroup.objectID() : undefined);
this.maskRect = this.getLayerRect(msLayer.absoluteRect(), artboardFrame);
} else if ((msGroup != null && this.maskObjectID != msGroup.objectID()) || msLayer.shouldBreakMaskChain()) {
this.maskObjectID = undefined;
this.maskRect = undefined;
}
if (layerProperties.isMaskChildLayer) {
layer.rect = this.getLayerMaskRect(layer.rect);
}*/
//set symbol id if applicable
if (symbol instanceof SymbolInstance || symbol instanceof Group || symbol instanceof RepeatGrid) {
layer.symbol_instance_id = symbol.guid;
}
layers.push(layer);
}
if (child instanceof SymbolInstance) {
let bounds = {x: child.globalBounds.x, y: child.globalBounds.y};
var symbolLayers = self.getArtboard(artboard, child, bounds);
symbolLayers.forEach(function (layer) {
layers.push(layer);
});
} else if (child instanceof Group || child instanceof RepeatGrid) {
var symbolLayers = self.getArtboard(artboard, child, null);
symbolLayers.forEach(function (layer) {
layers.push(layer);
});
}
});
if (symbol == null) {
var artboardData = {
sid: artboard.guid,
name: artboard.name,
width: artboard.width,
height: artboard.height,
layers: layers
};
return artboardData;
} else {
return layers;
}
}
showHideArtboardTextLayers(artboard, symbol, layers, isShow) {
//return if not instance of artboard or symbol
if (!(artboard instanceof Artboard || symbol instanceof SymbolInstance || symbol instanceof Group || symbol instanceof RepeatGrid)) {
return;
}
var self = this;
var artboardChildren = [];
if (symbol instanceof SymbolInstance || symbol instanceof Group || symbol instanceof RepeatGrid) {
artboardChildren = symbol.children;
} else if (artboard instanceof Artboard) {
artboardChildren = artboard.children;
}
//iterate all children inside this artboard/symbol
artboardChildren.forEach(function (child) {
if (child instanceof Text) {
let layerId = child.guid;
for (var i = 0; i < layers.length; i++) {
if (layerId == layers[i].sid) {
try {
child.visible = isShow;
} catch (e) {
console.log("Exception occurred: " + e);
}
}
}
}
if (child instanceof SymbolInstance || child instanceof Group || child instanceof RepeatGrid) {
//show-hide layer text for this symbol
self.showHideArtboardTextLayers(artboard, child, layers, isShow);
}
});
}
setArtboard(artboard, symbol, scribble) {
if (scribble == null || scribble.layers == null) {
return;
}
//return if not instance of artboard or symbol
if (!(artboard instanceof Artboard || symbol instanceof SymbolInstance || symbol instanceof Group || symbol instanceof RepeatGrid)) {
return;
}
var self = this;
var layers = [];
var artboardChildren = [];
if (symbol instanceof SymbolInstance || symbol instanceof Group || symbol instanceof RepeatGrid) {
artboardChildren = symbol.children;
} else if (artboard instanceof Artboard) {
artboardChildren = artboard.children;
}
//iterate all children inside this artboard/symbol
artboardChildren.forEach(function (child) {
try {
let layerId = child.guid;
for (var i = 0; i < scribble.layers.length; i++) {
var scribbleLayer = scribble.layers[i];
if (layerId == scribbleLayer.sid) {
try {
layers.push({
child: child,
content: scribbleLayer.content
});
//remove this layer from scribble now and break;
//scribble.layers.splice(i, 1);
break;
} catch (e) {
console.log("Exception occurred: " + e);
}
}
}
if (child instanceof SymbolInstance || child instanceof Group || child instanceof RepeatGrid) {
try {
var symbolLayers = self.setArtboard(artboard, child, scribble);
symbolLayers.forEach(function (layer) {
layers.push(layer);
});
} catch (e) {
console.log("Exception occurred: " + e);
}
}
} catch (e) {
console.log("Exception occurred: " + e);
}
});
return layers;
}
getLayerRect(rect, referenceRect) {
if (referenceRect) {
return {
x: rect.x - referenceRect.x,
y: rect.y - referenceRect.y,
width: rect.width,
height: rect.height
};
}
return {
x: rect.x,
y: rect.y,
width: rect.width,
height: rect.height
};
}
getLayerFills(layer, fill) {
var self = this;
var layerFills = [];
try {
if (layer.fillEnabled) {
if (fill instanceof Color) {
layerFills.push({
type: "color",
color: self.getColor(fill)
});
} else if (layer instanceof LinearGradientFill) {
layerFills.push({
type: "gradient",
gradient: this.getLayerGradient(fill, "linear")
});
} else if (layer instanceof RadialGradientFill) {
layerFills.push({
type: "gradient",
gradient: this.getLayerGradient(fill, "radial")
});
} else if (layer instanceof BitmapFill) {
//TODO: bitmap fill
}
}
} catch (e) {
console.log("Exception occurred: " + e);
}
return layerFills;
}
getLayerColor(layer, fill) {
var self = this;
try {
if (layer.fillEnabled) {
if (fill instanceof Color) {
return self.getColor(fill);
}
}
} catch (e) {
console.log("Exception occurred: " + e);
}
return null;
}
getColor(color) {
if (color instanceof Color) {
return {
r: color.r,
g: color.g,
b: color.b,
a: Math.floor((color.a / 255) * 100) / 100
};