Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Loading a Cocoa Framework in a Sketch Plugin

This is what Craft does:

function loadFramework(pluginRoot) {
  if (NSClassFromString('PanelsManager') == null) {
    var mocha = [Mocha sharedRuntime];
    return [mocha loadFrameworkWithName:'Panels' inDirectory:pluginRoot];
  } else {
    return true;
  }
}

var scriptPath = context.scriptPath;
var pluginRoot = [scriptPath stringByDeletingLastPathComponent];
loadFramework(pluginRoot);
[[PanelsManager sharedManager] load];

They took that code from Avocode's plugin, which does this:

var pluginRoot = sketch.scriptPath.stringByDeletingLastPathComponent();

loadFramework(pluginRoot);

[Avocode load];
var avocode = [[Avocode alloc] init];
[avocode export:pluginRoot];

function loadFramework(pluginRoot) {
  if (NSClassFromString('Avocode') == null) {
    var mocha = [Mocha sharedRuntime];
    return [mocha loadFrameworkWithName:"AvocodeExporter" inDirectory:pluginRoot + "/avocode-exporter"];
  } else {
    return true;
  }
}

Basically, you use Mocha to load the Framework, and then either the Framework takes control, or you just access it from CocoaScript like you do with other Cocoa objects.

Caveats: not all Frameworks can be used in this way. If you need to use Obj-C blocks to use the Framework, CocoaScript doesn't support them. If you need to use delegates, take a look at MochaJSDelegate.

Alternatively, you may want to use an external app to process your data. There's a nice example of how to do that here: https://github.com/abynim/Sketch-PluginHelper

Owner

FTR, MMMarkdown works like a charm:

function loadFramework(pluginRoot) {
  if (NSClassFromString('MMMarkdown') == null) {
    var mocha = [Mocha sharedRuntime]
    return [mocha loadFrameworkWithName:'MMMarkdown' inDirectory:pluginRoot]
  } else {
    return true
  }
}

var scriptPath = context.scriptPath
var pluginRoot = [scriptPath stringByDeletingLastPathComponent]
loadFramework(pluginRoot)
var html = [MMMarkdown HTMLStringWithMarkdown:"# foo\n## bar\n- list item 1\n- list item 2\n- list item 3" error:null]
log(html)

outputs this:

screenshot 2016-02-09 10 55 41

Here's the Plugin I've used, in case you want to save yourself some time compiling MMMarkdown: https://www.dropbox.com/s/5h03ma847wpy0ok/Markdown%20to%20HTML.sketchplugin.zip?dl=0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment