forked from bomberstudios/sketch-framer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Export to Framer.sketchplugin
401 lines (339 loc) · 13.6 KB
/
Export to Framer.sketchplugin
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
// Sketch Framer (ctrl alt command f)
/* Import the variables and complain if they are undefined */
#import 'sketch-framer-config.js'
#import 'sandbox.js'
/* Configuration */
var framerjs_url = "http://shortcuts-for-framer.s3.amazonaws.com/framer.js";
function major_version() {
return [NSApp applicationVersion].substr(0,1);
}
function should_become_view(layer) {
return is_group(layer) || [layer name].slice(-1) == '+';
}
function is_group(layer) {
return [layer isMemberOfClass:[MSLayerGroup class]] || [layer isMemberOfClass:[MSArtboardGroup class]]
}
function should_ignore_layer(layer) {
return [layer name].slice(-1) == '-' || [layer className] == "MSPage";
}
function sanitize_filename(name){
return name.replace(/(\s|:|\/)/g ,"_").replace(/__/g,"_").replace("*","").replace("+","").replace("@@hidden","");
}
function has_art(layer) {
// return true;
if(is_group(layer) && !should_flatten_layer(layer)) {
var has_art = false;
var sublayers = [layer layers];
for (var sub=([sublayers count] - 1); sub >= 0; sub--) {
var sublayer = [sublayers objectAtIndex:sub]
if(!should_ignore_layer(sublayer) && !should_become_view(sublayer)) {
has_art = true;
}
}
return has_art;
} else {
return true;
}
}
function export_layer(layer, depth) {
log_depth("Exporting <" + [layer name] + ">", depth);
var filename = images_folder + "/" + sanitize_filename([layer name]) + ".png";
if(show_errors && [layer isMemberOfClass:[MSArtboardGroup class]] && major_version == 3) {
[[NSApplication sharedApplication] displayDialog:"Sketch Framer currently doesn't support artboards with Sketch 3. Please remove the artboard and have layers directly on the canvas. You can group everything at the top level and move it to (0,0) for intended results." withTitle:"Sketch Framer known bugs"]
}
// copy off-screen
var layer_copy = [layer duplicate];
var frame = [layer_copy frame];
[frame setX:-100000];
[frame setY:-100000];
var artnames = [];
var has_art = false;
// remove subgroups and only leave shapes
if(is_group(layer) && !should_flatten_layer(layer)) {
// log([layer name] + " is a group and i'm trying to extract its shapes")
var sublayers = [layer_copy layers];
for (var sub=([sublayers count] - 1); sub >= 0; sub--) {
var sublayer = [sublayers objectAtIndex:sub]
if(!should_ignore_layer(sublayer)) {
// log(" " + [layer name] + "." + [sublayer name] + " (" + [sublayer className] + ")");
if(should_become_view(sublayer)) {
log(" REMOVING " + [sublayer name]);
[sublayer removeFromParent];
} else {
log(" KEEPING " + [sublayer name]);
artnames.push([sublayer name])
has_art = true
}
}
}
} else {
// not a group, single art
has_art = true;
}
if(!has_art) {
log_depth("Exporting <" + [layer name] + ">, no image", depth);
} else {
log_depth("Exporting <" + [layer name] + "> including children art (" + artnames.join(", ") + ")", depth);
// export
var rect = [layer_copy rectByAccountingForStyleSize:[[layer_copy absoluteRect] rect]],
slice = [MSSlice sliceWithRect:rect scale:2];
if (in_sandbox()) {
sandboxAccess.accessFilePath_withBlock_persistPermission(target_folder, function(){
[doc saveArtboardOrSlice:slice toFile:filename];
}, true)
} else {
[doc saveArtboardOrSlice:slice toFile:filename];
}
}
// remove it
[layer_copy removeFromParent];
}
function should_flatten_layer(layer) {
var name = [layer name];
if(name.slice(-1) == "*") {
return true;
} else {
return false;
}
}
function log_depth(message, depth) {
var padding = "";
for(var i=0; i<depth; i++) {
padding = padding + ">"
}
log(padding + " " + message);
}
function process_layer(layer,metadata_container,depth) {
if (should_ignore_layer(layer)) {
log_depth("Ignoring <" + [layer name] + "> of type <" + [layer className] + ">", depth);
return;
}
if(should_become_view(layer)){
log_depth("Processing <" + [layer name] + "> of type <" + [layer className] + ">", depth);
// If layer is a group, do:
// temporarily show it
if (![layer isVisible]) {
[layer setName:[layer name] + "@@hidden"]
}
[layer setIsVisible:true];
// - Get layer data
var layer_data = extract_metadata_from(layer);
layer_data.children = [];
// - Export image if layer has no subgroups
if (!should_flatten_layer(layer) && is_group(layer)) {
var sublayers = [layer layers];
// Apparently, Sketch returns child layers in reverse order (back to front),
// so we'll loop backwards through them:
for (var sub=([sublayers count] - 1); sub >= 0; sub--) {
var current = [sublayers objectAtIndex:sub]
process_layer(current,layer_data.children,depth+1);
}
}
export_layer(layer, depth);
metadata_container.push(layer_data);
if ([layer name].indexOf("@@hidden") != -1) {
// If it was hidden, make it hidden again and fix the name
var _name = [layer name].replace("@@hidden", "");
[layer setIsVisible:false];
[layer setName:_name];
}
}
if ([layer name].indexOf("@@mask") != -1) {
var _name = [layer name].replace("@@mask", "");
log("Re-enabling mask " + _name);
[layer setHasClippingMask:true];
[layer setName:_name];
}
}
function save_file_from_string(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];
}
}
function get_next_id() {
return ++object_id;
}
function mask_bounds(layer) {
var sublayers = [layer layers];
var effective_mask = null;
for (var sub=0; sub < [sublayers count]; sub++) {
var current = [sublayers objectAtIndex:sub];
if(current && [current hasClippingMask]) {
// If a native mask is detected, rename it and disable it (for now) so we can export its contents
var _name = [current name] + "@@mask";
[current setName:_name];
[current setHasClippingMask:false];
log("Disabling mask " + [current name]);
if (!effective_mask) {
// Only the bottom-most one will be effective
log("Effective mask " + _name)
effective_mask = current
}
}
}
if (effective_mask) {
return metadata_for(effective_mask);
} else {
return null;
}
}
function calculate_real_position_for(layer) {
var gkrect = [GKRect rectWithRect:[layer rectByAccountingForStyleSize:[[layer absoluteRect] rect]]],
absrect = [layer absoluteRect];
var rulerDeltaX = [absrect rulerX] - [absrect x],
rulerDeltaY = [absrect rulerY] - [absrect y],
GKRectRulerX = [gkrect x] + rulerDeltaX,
GKRectRulerY = [gkrect y] + rulerDeltaY;
return {
x: Math.round(GKRectRulerX),
y: Math.round(GKRectRulerY)
}
}
function metadata_for(layer) {
var frame = [layer frame],
gkrect = [GKRect rectWithRect:[layer rectByAccountingForStyleSize:[[layer absoluteRect] rect]]],
absrect = [layer absoluteRect],
position = calculate_real_position_for(layer),
x,y,w,h,r
if ([layer className] == "MSArtboardGroup") {
// FIXME: This is probably still wrong, test with different artboard positions
x = [[layer absoluteRect] rulerX],
y = [[layer absoluteRect] rulerY],
// x = position.x,
// y = position.y,
w = [frame width],
h = [frame height],
r = {
x: x,
y: y,
width: w,
height: h
}
} else {
x = position.x,
y = position.y,
w = [gkrect width],
h = [gkrect height],
r = {
x: x,
y: y,
width: w,
height: h
}
}
log("{ x:"+x+", y:"+y+", width:"+w+", height:"+h+"}")
return r
}
function extract_metadata_from(layer) {
var maskFrame = mask_bounds(layer);
var layerFrame = metadata_for(layer);
// call maskframe first so it disables the mask, so we can get correct layerframe
//metadata.id = get_next_id(); // FIXME
var metadata = {
name: sanitize_filename([layer name]),
layerFrame: layerFrame,
maskFrame: maskFrame
};
if(has_art(layer)) {
metadata.image = {
path: "images/" + sanitize_filename([layer name]) + ".png",
frame: layerFrame
};
metadata.imageType = "png";
// TODO: Find out how the modification hash is calculated in Framer.app
// metadata.modification = new Date();
}
// if it was invisible, mark this in the metadata as well
if ([layer name].indexOf("@@hidden") != -1) {
metadata.visible = false
}
return metadata;
}
var document_path = [[doc fileURL] path].split([doc displayName])[0],
document_name = [doc displayName].replace(".sketch",""),
target_folder = document_path + document_name,
images_folder = target_folder + "/images",
framer_folder = target_folder + "/framer",
file_manager = [NSFileManager defaultManager],
object_id = 0
function main() {
log('#################################################################################################################################################');
// Create folders
if (in_sandbox()) {
sandboxAccess.accessFilePath_withBlock_persistPermission(target_folder, function(){
[file_manager createDirectoryAtPath:target_folder withIntermediateDirectories:true attributes:nil error:nil];
[file_manager createDirectoryAtPath:images_folder withIntermediateDirectories:true attributes:nil error:nil];
[file_manager createDirectoryAtPath:framer_folder withIntermediateDirectories:true attributes:nil error:nil];
}, true)
} else {
[file_manager createDirectoryAtPath:target_folder withIntermediateDirectories:true attributes:nil error:nil];
[file_manager createDirectoryAtPath:images_folder withIntermediateDirectories:true attributes:nil error:nil];
[file_manager createDirectoryAtPath:framer_folder withIntermediateDirectories:true attributes:nil error:nil];
}
// Get JS files from Github
var task = [[NSTask alloc] init],
argsArray = [NSArray arrayWithObjects:"-O", framerjs_url, nil];
[task setCurrentDirectoryPath:framer_folder];
[task setLaunchPath:"/usr/bin/curl"];
[task setArguments:argsArray];
[task launch];
// Get library files if one if configured and isn't yet downloaded
if(FramerLibraryUrl) {
if(![file_manager fileExistsAtPath:(framer_folder + "/" + FramerLibraryFileName)]) {
var task2 = [[NSTask alloc] init],
argsArray = [NSArray arrayWithObjects:"-O", FramerLibraryUrl, nil];
[task2 setCurrentDirectoryPath:framer_folder];
[task2 setLaunchPath:"/usr/bin/curl"];
[task2 setArguments:argsArray];
[task2 launch];
}
}
// Get all layers in current page
var all_layers = [[doc currentPage] layers],
metadata = [];
for (var i=0; i < [all_layers count]; i++) {
process_layer([all_layers objectAtIndex:i],metadata, 0);
}
file_path = framer_folder + "/views." + document_name + ".js";
var file_contents = "window.FramerPS = window.FramerPS || {};\nwindow.FramerPS['" + document_name +"'] = " + JSON.stringify(metadata,null,2);
save_file_from_string(file_path,file_contents);
// Save JS files from templates:
save_file_from_string(framer_folder + "/framerps.js", FramerPSJSContents);
if(![file_manager fileExistsAtPath:(target_folder + "/" + FramerScriptFileName)]) {
save_file_from_string(target_folder + "/" + FramerScriptFileName, FramerScriptFileContents);
}
// Create HTML and open in default browser if it's the first time we're exporting
if(![file_manager fileExistsAtPath:(target_folder + "/index.html")]) {
save_file_from_string(target_folder + "/index.html", FramerIndexFileContents.replace("{{ views }}",'<script src="framer/views.' + document_name + '.js"></script>'));
var open_task = [[NSTask alloc] init],
open_task_args = [NSArray arrayWithObjects:(target_folder + "/index.html"), nil];
[open_task setCurrentDirectoryPath:framer_folder];
[open_task setLaunchPath:"/usr/bin/open"];
[open_task setArguments:open_task_args];
[open_task launch];
}
log('#################################################################################################################################################');
// Display message in toolbar
[doc showMessage: "Sketch Framer: Project exported to “" + target_folder + "”"];
}
/*
This plugin will export your Sketch document to a Framer project.
This command REQUIRES at least Sketch Version 2.3 (419),
as it uses an API not available in earlier versions
- Every layer group will become an ImageView, backed by the pixel and/or shape layers in that layer group.
- Views are accessible by name under the PSD object (yeah, I know...)
- Framer respects the layer hierarchy, so a sub layer group will become a subview. This way you can define your view structure in Photoshop.
- TODO: Layer groups with vector masks will become views with clipping enabled. You can optionally add "scroll" to the layer group name to make it a ScrollView.
- Layer group names should be unique, if they're not Framer will silently rename them on export.
// TODO: Check for duplicated names in exported files
// TODO: Calculate proper IDs (not sure what they're used for, but hey...)
// TODO: Calculate proper modification hash
// TODO: Embed framer.js on this file, instead of 'curl'ing it from Github
*/
main();