-
Notifications
You must be signed in to change notification settings - Fork 7
/
inventory.js
2151 lines (1795 loc) · 73.8 KB
/
inventory.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
#import 'sandbox.js'
#import 'persistence.js'
// Namespaced library of functions common across multiple plugins
var com = com || {};
// todo: update pattern code to [self setPatternImage:image collection:self.documentData.images]
// Get the path of the plugin, without the name of the plugin
// todo: Could need some regex love for sure
com.getflourish = (function() {
var my = {};
my.execute = function(block) {
try
{
block();
}
catch (e)
{
log("Execution failed: " + e);
}
}
my.config = {
colorInventoryName: "Color Inventory",
pageName: "Style Sheet",
textStylePlaceholder: "The big brown fox jumps over the lazy dog.",
maxColorsPerRow: 5
}
var pluginPath = sketch.scriptPath;
var lastSlash = pluginPath.lastIndexOf("/");
var basePath = pluginPath.substr(0, lastSlash);
my.config.background_image = basePath + "/pattern.png";
my.common = {
// Adds an artboard to the given page
addArtboard: function(page, name) {
var artboard = MSArtboardGroup.new();
frame = artboard.frame();
frame.setWidth(400);
frame.setHeight(400);
frame.setConstrainProportions(false);
page.addLayers([artboard]);
artboard.setName(name);
return artboard;
},
addCheckeredBackground: function(artboard) {
log(artboard)
var layer = artboard.addLayerOfType("rectangle");
layer.frame().setWidth(artboard.frame().width());
layer.frame().setHeight(artboard.frame().height());
layer.setName("Background");
var image = NSImage.alloc().initWithContentsOfFile(my.config.background_image);
var fill = layer.style().fills().addNewStylePart();
if (fill) {
fill.setFillType(4);
var coll = layer.style().fills().firstObject().documentData().images();
[fill setPatternImage:image collection:coll]
fill.setPatternFillType(0);
fill.setPatternTileScale(1);
}
doc.currentPage().deselectAllLayers();
// layer.setIsSelected(true);
// my.utils.sendToBack();
layer.setIsLocked(true);
return layer;
},
addSolidBackground: function (artboard, hex_string) {
var layer = artboard.addLayerOfType("rectangle");
layer.frame().setWidth(artboard.frame().width());
layer.frame().setHeight(artboard.frame().height());
layer.style().fills().addNewStylePart();
layer.style().fill().setFillType(0);
layer.setName("Background");
color = MSColor.colorWithNSColor(NSColor.colorWithHex_alpha(hex_string, 1));
layer.style().fill().setColor(color)
return layer;
},
// Adds a new page to the document
addPage: function(name) {
// look for existing style sheet, otherwise create a new page with the styles
var page = doc.addBlankPage();
page.setName(name);
doc.setCurrentPage(page);
// my.common.refreshPage();
return page;
},
addTextLayer: function(target, label) {
var textLayer = target.addLayerOfType("text");
textLayer.setStringValue(label)
textLayer.setName(label)
return textLayer;
},
addTextLayerEmphasis: function(target, label) {
var textLayer = target.addLayerOfType("text");
textLayer.setStringValue(label)
textLayer.setName(label)
textLayer.setFontPostscriptName("HelveticaNeue-Bold");
return textLayer;
},
addTextLayerTitle: function(target, label) {
var textLayer = target.addLayerOfType("text");
textLayer.setStringValue(label)
textLayer.setName(label)
textLayer.setFontSize(44);
textLayer.setFontPostscriptName("HelveticaNeue-Thin");
return textLayer;
},
createSelect: function (msg, items, selectedItemIndex){
selectedItemIndex = selectedItemIndex || 0
var accessory = [[NSComboBox alloc] initWithFrame:NSMakeRect(0,0,200,25)]
[accessory addItemsWithObjectValues:items]
[accessory selectItemAtIndex:selectedItemIndex]
var alert = [[NSAlert alloc] init]
[alert setMessageText:msg]
[alert addButtonWithTitle:'OK']
[alert addButtonWithTitle:'Cancel']
[alert setAccessoryView:accessory]
var responseCode = [alert runModal]
var sel = [accessory indexOfSelectedItem]
return [responseCode, sel]
},
createWebView: function (url) {
// WebView tests (shift alt ctrl y)
/**
* The first script call creates the panel with the saved HTML page.
* The following script calls execute the JavaScript calls in the webView.
*/
// Add a hint to whomever is instantiating us,
// that we'd like to stick around for a while.
coscript.shouldKeepAround = true;
// Include additionl frameworks.
framework('WebKit');
framework('AppKit');
// Define a WebViewLoad delegate function - should be converted to an ObjC class.
// See https://github.com/logancollins/Mocha
var WebViewLoadDelegate = function () {};
// Add the initiating delegate (callback) function.
WebViewLoadDelegate.prototype.webView_didClearWindowObject_forFrame = function (sender, scriptObject, frame) {
var jswrapper = 'try {[[js]]} catch (e) {e.toString();}',
jscode = 'document.body.innerHTML;',
js = jswrapper.replace('[[js]]', jscode);
var result = scriptObject.evaluateWebScript(js);
log(result);
};
// Add the delegate (callback) function which is called when the page has loaded.
WebViewLoadDelegate.prototype.webView_didFinishLoadForFrame = function (sender, frame) {
var jswrapper = 'try {[[js]]} catch (e) {e.toString();}',
jscode = 'document.body.innerHTML;',
js = jswrapper.replace('[[js]]', jscode);
var scriptObject = sender.windowScriptObject();
var result = scriptObject.evaluateWebScript(js);
log(result);
};
// Prepare the function that will be used as an object added to the
// scriptObject. The object should be visible with it's methods and properties
// from the page JavaScript and should be usable to call Sketch script
// functions from the page JavaScript.
var runThis = function runThis () {
var that = function () {};
// Property visible to JavaScript.
that.fixed = "Property named fixed";
// Method visible to JavaScript.
that.log = function () {
log('Called from JavaScript via the Sketch script RunThis object.');
return true;
};
// Method returns whether a selector should be hidden
// from the scripting environment. If "false" is returned none is hidden.
that.isSelectorExcludedFromWebScript = function (selector) {
log('selector');
log(selector);
return false;
};
// Method returns whether a key should be hidden
// from the scripting environment. If "false" is returned none is hidden.
that.isKeyExcludedFromWebScript = function (key) {
log('key');
log(key);
return false;
};
return that;
};
// Set the url to the saved webpage
// Split the scriptpath into an array, remove last item which is
// the script name, create a string from the array again and wrap the
// path with 'file://' and the html file name.
var URL = '';
var path = url.split('/');
path.pop();
path = path.join('/') + '/';
URL = encodeURI('file://' + url + "styles.html");
log(URL)
/**
* Prepare the panel, show it and save it into the persistent store.
*/
var setupWebViewPanel = function () {
// Prepare the panel:
// Set the panel size and
// initialize the webview and load the URL
var frame = NSMakeRect(0, 0, 320, 480);
var webView = WebView.alloc().initWithFrame(frame);
var webViewFrame = webView.mainFrame();
// The FrameLoadDelegate offers the webView_didFinishLoadForFrame
// method which is called when the web page is loaded.
// !!! The methods never fire because:
// - it is implemented wrong?
// - the delegate's method never is called because the script ends before the
// page is loaded?
var loadDelegate = new WebViewLoadDelegate();
webView.setFrameLoadDelegate(loadDelegate);
webViewFrame.loadRequest(NSURLRequest.requestWithURL(NSURL.URLWithString(URL)));
// Set up the panel window
var mask = NSTitledWindowMask + NSClosableWindowMask + NSMiniaturizableWindowMask + NSUtilityWindowMask;
var panel = NSPanel.alloc().initWithContentRect_styleMask_backing_defer(frame, mask, NSBackingStoreBuffered, true);
// Add the webView to the prepared panel
panel.contentView().addSubview(webView);
// Show the panel
panel.makeKeyAndOrderFront(panel);
// persist the panel and the webView.
persist.set('panel', panel);
persist.set('webView', webView);
};
var update = function (){
var webView = persist.get('webView').mainFrame().loadRequest(NSURLRequest.requestWithURL(NSURL.URLWithString(URL)));
}
var doScript = function () {
var jswrapper = 'try {[[js]]} catch (e) {e.toString();}',
jscode = '',
js = jswrapper.replace('[[js]]', jscode);
// var result = webView.stringByEvaluatingJavaScriptFromString(js);
// Get the windowScriptObject as the scripting connector
var scriptObject = webView.windowScriptObject();
// Add the RunThis object with the key 'callThis'. The callThis
// object should be accessible by the page JavaScript.
// !!! The object is seen by the page JavaScript but the methods/porperties
// are not present.
var runThisFunc = runThis();
scriptObject.setValue_forKey(runThisFunc, 'callThis');
// Add a text line.
jscode = 'de.unodo.writeTest("From the Sketch script ' + new Date() + '");';
js = jswrapper.replace('[[js]]', jscode);
var result = scriptObject.evaluateWebScript(js);
log(result);
// Call the callback function to check if the 'callThis' class is visible
// in the page for JavaScript.
jscode = 'de.unodo.callBack();';
js = jswrapper.replace('[[js]]', jscode);
var result = scriptObject.evaluateWebScript(js);
log(result);
// Get the form data.
jscode = 'de.unodo.getFormData();';
js = jswrapper.replace('[[js]]', jscode);
var result = scriptObject.evaluateWebScript(js);
log('Formfield "Name" value: ' + result);
};
var panel = persist.get('panel');
var webView = persist.get('webView');
// If the panel does not exisit (null is returned from persist.get),
// set the panel up and show it.
// Else make the panel the front window and run the JavaScript functions.
if (panel === null) {
log('setupWebViewPanel');
setupWebViewPanel();
} else {
// Show the panel
update();
panel.makeKeyAndOrderFront(panel);
// var loadDelegate = new WebViewLoadDelegate;
// webView.setFrameLoadDelegate(loadDelegate);
// Run the scripts
// doScript();
}
log('done');
},
filePicker: function (url, fileTypes){
// Panel
var openPanel = [NSOpenPanel openPanel]
[openPanel setTitle:"Import Colors"]
[openPanel setMessage:"Select a JSON file containing color information."];
[openPanel setPrompt:"Import"];
[openPanel setCanCreateDirectories:false]
[openPanel setCanChooseFiles:true]
[openPanel setCanChooseDirectories:false]
[openPanel setAllowsMultipleSelection:false]
[openPanel setShowsHiddenFiles:false]
[openPanel setExtensionHidden:false]
[openPanel setAllowedFileTypes:fileTypes]
// [openPanel setDirectoryURL:url]
var openPanelButtonPressed = [openPanel runModal]
if (openPanelButtonPressed == NSFileHandlingPanelOKButton) {
allowedUrl = [openPanel URL]
}
return allowedUrl
},
fileSaver: function (){
// Panel
var openPanel = [NSOpenPanel openPanel]
[openPanel setTitle:"Choose a location…"]
[openPanel setMessage:"Select the export location…"];
[openPanel setPrompt:"Export"];
[openPanel setCanCreateDirectories:true]
[openPanel setCanChooseFiles:false]
[openPanel setCanChooseDirectories:true]
[openPanel setAllowsMultipleSelection:false]
[openPanel setShowsHiddenFiles:false]
[openPanel setExtensionHidden:false]
// [openPanel setDirectoryURL:url]
var openPanelButtonPressed = [openPanel runModal]
if (openPanelButtonPressed == NSFileHandlingPanelOKButton) {
allowedUrl = [openPanel URL]
}
return allowedUrl
},
// Returns the page if it exists or creates a new page
getPageByName: function(name) {
for (var i = 0; i < doc.pages().count(); i++) {
var page = doc.pages().objectAtIndex(i);
if (page.name() == name) {
doc.setCurrentPage(page);
return page;
}
}
var page = my.common.addPage(name);
return page;
},
dump: function (obj) {
log("#####################################################################################")
log("## Dumping object " + obj )
log("## obj class is: " + [obj className])
log("#####################################################################################")
log("obj.properties:")
log([obj class].mocha().properties())
log("obj.propertiesWithAncestors:")
log([obj class].mocha().propertiesWithAncestors())
log("obj.classMethods:")
log([obj class].mocha().classMethods())
log("obj.classMethodsWithAncestors:")
log([obj class].mocha().classMethodsWithAncestors())
log("obj.instanceMethods:")
log([obj class].mocha().instanceMethods())
log("obj.instanceMethodsWithAncestors:")
log([obj class].mocha().instanceMethodsWithAncestors())
log("obj.protocols:")
log([obj class].mocha().protocols())
log("obj.protocolsWithAncestors:")
log([obj class].mocha().protocolsWithAncestors())
log("obj.treeAsDictionary():")
log(obj.treeAsDictionary())
},
// Returns an artboard from a given page
getArtboardByPageAndName: function(page, name) {
var theArtboard = null;
var abs = page.artboards().objectEnumerator();
while (a = abs.nextObject()) {
if (a.name() == name) {
theArtboard = a;
break;
}
}
if (theArtboard == null) theArtboard = my.common.addArtboard(page, name);
return theArtboard;
},
isIncluded: function(arr, obj) {
return (arr.indexOf(obj) != -1);
},
getDirectoryFromBrowserForFilename: function (filename) {
// Path and file access
var document_path = [[doc fileURL] path].split([doc displayName])[0];
var path = document_path + filename;
var fileTypes = [];
var fileURL = com.getflourish.common.fileSaver();
path = fileURL.path();
// Authorize Sketch to save a file
new AppSandbox().authorize(path, function () {});
return path;
},
showMarginsOf: function (layer) {
// calculates margins and displays them
var parent = layer.parentGroup();
var ml = layer.absoluteRect().x() - parent.absoluteRect().x();
var mt = layer.absoluteRect().y() - parent.absoluteRect().y();
var mr = parent.frame().width() - ml - layer.frame().width();
var mb = parent.absoluteRect().y() + parent.frame().height() - layer.absoluteRect().y() - layer.frame().height();
var margin = "x: " + ml + ", y: " + mt + " / right: " + mr + ", bottom: " + mb;
doc.showMessage(margin);
},
refreshPage: function() {
var c = doc.currentPage();
doc.setCurrentPage(0);
doc.setCurrentPage(doc.pages().count() - 1);
doc.setCurrentPage(c);
},
removeArtboardFromPage: function (page, name) {
var theArtboard = null;
var abs = page.artboards().objectEnumerator();
while (a = abs.nextObject()) {
if (a.name() == name) {
page.removeLayer(a)
break;
}
}
},
// Removes all layers from an artboard
removeAllLayersFromArtboard: function(artboard) {
var layers = artboard.children().objectEnumerator();
while (layer = layers.nextObject()) {
artboard.removeLayer(layer);
}
},
resize: function(layer, width, height) {
var frame = layer.frame();
frame.setWidth(width);
frame.setHeight(height);
},
// Saves a string to a file
// save_file_from_string: function (filename, the_string) {
// var path = [@"" stringByAppendingString:filename],
// str = [@"" stringByAppendingString:the_string];
//
// if (in_sandbox()) {
// sandboxAccess.accessFilePath_withBlock_persistPermission(filename, function(){
// [str writeToFile:path atomically:true encoding:NSUTF8StringEncoding error:null];
// }, true)
// } else {
// [str writeToFile:path atomically:true encoding:NSUTF8StringEncoding error:null];
// }
// },
save_file_from_string: function (filename, the_string) {
var path = [@"" stringByAppendingString:filename],
str = [@"" stringByAppendingString:the_string];
str.dataUsingEncoding_(NSUTF8StringEncoding).writeToFile_atomically_(path, true)
}
}
my.colorInventory = {
generate: function (palettes) {
var currentlySelectedArtboard = doc.currentPage().currentArtboard();
if (currentlySelectedArtboard == null) {
doc.showMessage("Please select an artboard. The Inventory will be placed next to it.");
}
var exists = false;
// start tracking the time
var startTime = new Date();
// page that the artboard will be created on
var styleSheetPage = doc.currentPage();
// the right most artboard
var rma = com.getflourish.layers.getRightmostArtboard();
// get hex colors from document
var hexColors = com.getflourish.colorInventory.getDocumentColors();
if (hexColors.length != 0) {
// feedback
doc.showMessage("Analyzing Colors…");
// setup predicate
var predicate = NSPredicate.predicateWithFormat("name == %@ AND className == %@", com.getflourish.config.colorInventoryName, "MSArtboardGroup");
// get the color artboard
var colorArtboard = styleSheetPage.children().filteredArrayUsingPredicate(predicate);
if (colorArtboard.count() == 0) {
// todo: adding is broken
colorArtboard = com.getflourish.common.addArtboard(styleSheetPage, com.getflourish.config.colorInventoryName);
} else {
colorArtboard = colorArtboard[0];
exists = true;
}
// if no palettes are provided, analyse the document to get them
if (palettes == null) {
// get hex colors from color artboard
var colorArtboardColors = com.getflourish.utils.arrayFromImmutableArray(com.getflourish.colorInventory.getColorArtboardColors(colorArtboard));
// get defined colors
var queryResult = com.getflourish.colorInventory.getDefinedColors(colorArtboard);
// todo: optimize
var palettes = com.getflourish.colorInventory.getPalettesFromMergingColors(queryResult, hexColors);
// add text colors to the palettes
}
// clear the artboard before adding swatches
colorArtboard.removeAllLayers();
// Add background
var bg = com.getflourish.common.addCheckeredBackground(colorArtboard);
coscript.setShouldKeepAround(true)
coscript.scheduleWithInterval_jsFunction(0.01, function() {
var execTime = (new Date() - startTime) / 1000;
doc.showMessage("Painting Swatches… " + execTime + " s");
// create colorsheet by passing palettes that contain multiple color objects (name, value)
com.getflourish.colors.createColorSheet(colorArtboard, palettes);
// position artboard
if (!exists) com.getflourish.colorInventory.positionArtboard(colorArtboard, currentlySelectedArtboard);
// finish it up
com.getflourish.colorInventory.finish(colorArtboard);
// resize background
bg.frame().setWidth(colorArtboard.frame().width())
bg.frame().setHeight(colorArtboard.frame().height())
// zoom
com.getflourish.view.zoomTo(colorArtboard)
// Feedback
var execTime = (new Date() - startTime) / 1000;
doc.showMessage("Generated Color Inventory in " + execTime + " s");
return colorArtboard;
});
} else {
doc.showMessage("No colors found :(")
}
},
getColorArtboardColors: function(colorArtboard) {
// get all layers of the current page
var layers = colorArtboard.children();
// analyse the colors
var rawHexColors = [layers valueForKeyPath:"@distinctUnionOfObjects.style.fill.color.hexValue"];
return rawHexColors;
},
getColorURL: function() {
var url = [doc askForUserInput:"Paste URL from Coolors or Hailpixel…" initialValue:"http://coolors.co/e0e086-acbe14-2c1f19-327a76-bce2d7"]
return url;
},
getColorsFromCoolorsString: function(string) {
var pos = string.lastIndexOf("/") + 1;
var colorString = string.substring(pos);
var colors = colorString.split("-");
var swatches = [];
for (var i = 0; i < colors.length; i++) {
var color = colors[i];
swatches.push({
name: "Imported Color",
color: color
})
}
return swatches;
},
getColorsFromHailString: function(string) {
var pos = string.lastIndexOf("/#") + 1;
var colorString = string.substring(pos);
var colors = colorString.split(",");
var swatches = [];
for (var i = 0; i < colors.length; i++) {
var color = colors[i];
if(color != ",") {
swatches.push({
name: "Imported Color",
color: color
})
}
}
return swatches;
},
getColorsFromURL: function(url) {
if (url.indexOf("http://color.hailpixel.com/") == 0) {
return com.getflourish.colorInventory.getColorsFromHailString(url);
} else if (url.indexOf("http://coolors.co/") == 0) {
return com.getflourish.colorInventory.getColorsFromCoolorsString(url);
}
return null;
},
getDefinedColors: function (artboard) {
// get defined colors, rename existing swatches
var predicate = NSPredicate.predicateWithFormat("NOT (name BEGINSWITH %@) && className == %@", "Untitled", "MSLayerGroup");
var queryResult = artboard.children().filteredArrayUsingPredicate(predicate);
return queryResult;
},
getDocumentColors: function() {
var borderColors = com.getflourish.colorInventory.getDocumentBorderColors();
var gradients = com.getflourish.colorInventory.getDocumentGradients();
var imageFills = com.getflourish.colorInventory.getDocumentImageFills();
var solidFillColors = com.getflourish.colorInventory.getDocumentSolidFillColors();
var textColors = com.getflourish.colorInventory.getDocumentTextColors();
// concat
// todo: concat and display by type
var allColors = solidFillColors.concat(textColors).unique();
return allColors;
},
getDocumentBorderColors: function() {
return com.getflourish.colorInventory.getDestinctProperties("style.border.color");
},
getDocumentGradients: function() {
return com.getflourish.colorInventory.getDestinctProperties("style.fill.gradient");
},
getDocumentImageFills: function () {
return com.getflourish.colorInventory.getDestinctProperties("style.fill.image");
},
getDocumentSolidFillColors: function () {
return com.getflourish.colorInventory.getDestinctProperties("style.fill.color");
},
getDocumentTextColors: function () {
return com.getflourish.colorInventory.getDestinctProperties("textColor");
},
getDestinctProperties: function (keyPath) {
// get all layers of the current page, except the ones used on the color artboard
var layers = doc.currentPage().children();
var predicate = NSPredicate.predicateWithFormat("NOT(parentArtboard.name == %@)", com.getflourish.config.colorInventoryName);
var result = layers.filteredArrayUsingPredicate(predicate);
// analyse the colors
var keyPath = "@distinctUnionOfObjects." + keyPath;
var objects = [result valueForKeyPath:keyPath];
var properties = com.getflourish.utils.arrayFromImmutableArray(objects);
return properties;
},
export: function (filename) {
var data = {};
var colorName = null;
var colorSheet = com.getflourish.common.getArtboardByPageAndName(doc.currentPage(), com.getflourish.config.colorInventoryName);
var hexColor = null;
var pName;
// file name of the exported file
var filename = "typography.css"
// let the user choose the export location
var fileURL = com.getflourish.common.fileSaver();
path = fileURL.path();
// get authorization to write to the export folder
new AppSandbox().authorize(path, function () {
// get defined colors, rename existing swatches
var predicate = NSPredicate.predicateWithFormat("className == %@ AND name != %@", "MSLayerGroup", "Untitled Color Swatch");
var queryResult = colorSheet.children().filteredArrayUsingPredicate(predicate);
for (var j = 0; j < queryResult.length(); j++) {
// check if there are swatches (groups of color swatches)
var group = queryResult[j];
colorName = group.name();
pName = "Defined";
// loop through all child layers to find the color
var layers = group.layers().array();
for (var i = 0; i < layers.count(); i++) {
// get the current layer
var currentLayer = layers[i];
if (currentLayer.name().indexOf("Color Swatch") == 0) {
hexColor = currentLayer.name().substr(13);
// remember color and name
// todo: format string for use in SCSS?
colorName = colorName;
// check for palette in name
if (colorName.indexOf(">") != -1) {
pName = colorName.substr(0, colorName.indexOf(">") - 1);
colorName = colorName.substr(colorName.indexOf(">") + 2);
}
if (data[pName] == null) data[pName] = {};
data[pName][colorName] = hexColor;
}
}
}
var output = JSON.stringify(data, undefined, 2);
if (output == "{}") {
doc.showMessage("Nothing to export. You need to define swatches.")
} else {
path += "/colors.json";
com.getflourish.common.save_file_from_string(path, output);
doc.showMessage("Exported to " + path);
}
});
},
import: function () {
// let user select a json file from the file browser
var fileTypes = ["json"];
var document_path = [[doc fileURL] path].split([doc displayName])[0];
var fileURL = com.getflourish.common.filePicker(document_path, fileTypes);
var str = JSON.parse(NSString.stringWithContentsOfFile(fileURL));
var importedPalettes = [];
var newSwatches = [];
var color;
var newSwatch;
if (str != null) {
for (var key in str) {
if (str.hasOwnProperty(key)) {
var palette = str[key];
var swatches = [];
for (var swatch in palette) {
color = palette[swatch].replace("#", "");
newSwatch = {
name: swatch,
color: color
}
newSwatches.push(newSwatch);
}
var newPalette = {
name: key,
swatches: newSwatches
}
importedPalettes.push(newPalette);
newSwatches = [];
}
}
}
if (importedPalettes.length > 0) {
com.getflourish.colorInventory.generate(importedPalettes);
} else {
doc.showMessage("Nothing to import.");
}
},
importFromURL: function() {
// get coolors url from user input
var url = com.getflourish.colorInventory.getColorURL();
// get colors from url
var swatches = com.getflourish.colorInventory.getColorsFromURL(url);
// add them to palettes
var palettes = [];
palettes.push({
name: "Imported",
swatches: swatches
})
// create a new artboard
var artboard = com.getflourish.common.getArtboardByPageAndName(doc.currentPage(), "Imported Colors");
artboard.removeAllLayers();
var bg = com.getflourish.common.addCheckeredBackground(artboard);
// generate color sheet
com.getflourish.colors.createColorSheet(artboard, palettes);
// position artboard
com.getflourish.colorInventory.positionArtboard(artboard, artboard);
// finish
com.getflourish.colorInventory.finish(artboard);
// resize background
bg.frame().setWidth(artboard.frame().width())
bg.frame().setHeight(artboard.frame().height())
},
getPalettesFromMergingColors: function(queryResult, definedColors) {
var documentColors = [];
var primaryColors = [];
var palettes = [];
var paletteNames = [];
for (var i = 0; i < queryResult.count(); i++) {
var group = queryResult[i];
// check if there are swatches (groups of color swatches)
colorName = group.name();
// check if the color swatch has a defined name
predicate2 = NSPredicate.predicateWithFormat("name BEGINSWITH %@", "Color Swatch");
querySwatches = group.children().filteredArrayUsingPredicate(predicate2);
// do something with the color swatch
if (querySwatches.count() == 1) {
// get color
c = querySwatches[0].style().fill().color();
index = definedColors.indexOf(c);
primaryIndex = primaryColors.indexOf(c);
// see wether the color name contains palette information
pIndex = colorName.indexOf(">");
if (pIndex != -1) {
// has palette name
pName = colorName.substr(0, pIndex);
// add new palette
if (paletteNames.indexOf(pName) == -1) {
paletteNames.push(pName);
// push the palette
palettes.push({
name: pName,
swatches: []
});
}
var foo = NSPredicate.predicateWithFormat("(style.fill != NULL) && (style.fill.color.hexValue isEqualForSync:%@) && NOT(parentArtboard.name == %@)", c, com.getflourish.config.colorInventoryName);
var bar = doc.currentPage().children().filteredArrayUsingPredicate(foo);
palettes[paletteNames.indexOf(pName)].swatches.push({
name: colorName,
color: c,
occurences: bar.count()
});
definedColors.splice(index, 1);
} else {
// not part of a palette
var foo = NSPredicate.predicateWithFormat("(style.fill != NULL) && (style.fill.color.hexValue isEqualForSync:%@) && NOT(parentArtboard.name == %@)", c, com.getflourish.config.colorInventoryName);
var bar = doc.currentPage().children().filteredArrayUsingPredicate(foo);
primaryColors.push({
name: colorName,
color: c,
occurences: bar.count()
});
definedColors.splice(index, 1);
}
// check if defined color is still part of the documents colors
if (index == -1) {
// do not remove the color from the defined swatches
// definedColors.splice(index, 1);
// primaryColors.splice(primaryIndex, 1);
}
}
};
for (var i = 0; i < definedColors.length; i++) {
predicate = NSPredicate.predicateWithFormat("(style.fill != NULL) && (style.fill.color.hexValue isEqualForSync:%@) && NOT(parentArtboard.name == %@)", definedColors[i], com.getflourish.config.colorInventoryName);
queryResult = doc.currentPage().children().filteredArrayUsingPredicate(predicate);
documentColors.push({
name: "Untitled Color Swatch",
color: definedColors[i],
occurences: queryResult.count()
});
}
documentColors.sort(function(a, b) {
return b.occurences - a.occurences;
});
palettes.push({
name: "Defined Colors",
swatches: primaryColors
});
palettes.push({
name: "Undefined Colors",
swatches: documentColors
});
// experimental border colors
// var borderColors = com.getflourish.colorInventory.getDocumentBorderColors();
// log(borderColors)
// var borderSwatches = [];
// for (var i = 0; i < borderColors.length; i++) {
// borderSwatches.push({
// name: "Untitled Color Swatch",
// color: borderColors[i].hexValue()
// })
// }
// palettes.push({
// name: "Border Colors",
// swatches: borderSwatches
// });
return palettes;
},
positionArtboard: function(what, where) {
// Position the artboard next to the last artboard
// The actual position that we want is the right edge of the
// rightmost artboard plus a margin of 100px.
// the right most artboard
var rma = com.getflourish.layers.getRightmostArtboard();
// var rma = where;
if(rma.name() != what.name()) {
// var shift = what.frame().width();
// com.getflourish.colorInventory.shiftArtboardsFromArtboardBy(where, shift);
var left = rma.frame().width() + rma.frame().x() + 100;
var top = rma.frame().y();
what.frame().setX(left);
what.frame().setY(top);
} else {
var left = rma.frame().x();
var top = rma.frame().y();
what.frame().setX(left);
what.frame().setY(top);
}
},
shiftArtboardsFromArtboardBy: function(artboard, shift) {
// Make sure an artboard is selected
var selectedArtboard = artboard;
doc.currentPage().deselectAllLayers();
selectedArtboard.setIsSelected(true);
var width = selectedArtboard.frame().width();
artboards = doc.currentPage().artboards();
// Move all artboards that are next to the selected one
for (var i = 0; i < artboards.count(); i++) {
// only move artboards on the same y position
if (artboards[i] != selectedArtboard) {
if (artboards[i].frame().y() == selectedArtboard.frame().y() && artboards[i].frame().x() > selectedArtboard.frame().x()) {
var newX = artboards[i].frame().x() + shift + 100;
artboards[i].frame().setX(newX);
}
}
}
},
finish: function(artboard) {
// deselect all layers
doc.currentPage().deselectAllLayers();
// select current artboard
artboard.setIsSelected(true);
// refresh
// todo: this is costly
com.getflourish.common.refreshPage();