SKETCH PLUGIN WITH JAVASCRIPT

In this blog we’ll see how to create the basic files that make up a Sketch plugin; we’ll write some JavaScript and create a user interface for our plugin with the help of some HTML and CSS.

The plugin we’ll be creating is called “Mosaic”.We’ll study the basic documents that make up a Sketch plugin; we’ll write some JavaScript and create a user interface for our plugin with the assist of some HTML and CSS.

Sketch Plugin And How Do They Work?

In Sketch, plugins are a way to feature functions and capability that aren’t found in Sketch. Considering that there’s nearly always going to be a few missing characteristic or integration in any given program, one can begin to consider how plugins might be especially useful and powerful. Sketch plugins are able to do things like manipulating the color, shape, length, order, style, grouping, and outcomes of layers, but additionally able to do such things as make requests to internet sources, gift a consumer interface, and an awful lot, lots extra! Most Sketch plugins are written in JavaScript, and some times in, Objective-C and Swift.

Mosaic

Feed it your layers, tweak a few settings, and Mosaic will create a pattern. Mosaic is inspired by Adobe Fireworks plugin called Twist-and-Fade which turned into quite powerful, able to replica a layer any range of instances whilst adjusting its hue, role, rotation, size, and opacity. The plugin was even able to generate animated GIFs.Duplicate any Sketch layer (bitmap or vector) and tweak the duplicates’ layer’s role, rotation, and opacity. This will supply us an advent to manipulating layers the usage of Sketch’s JavaScript APIs. Display a user interface created using HTML, CSS, and JS, a good way to teach you about the way to without problems create an interface for the plugin. The plugin interface is quite important since it’s how we’ll gather the user’s inputs concerning how the person wants the resulting mosaic image to look.

Creating the Base Plugin

1. First, we’ll be growing the “base” for the plugin we want to construct. We ought to create all the essential documents and folders that make up a plugin manually, but thankfully we don’t ought to — because Sketch can do it for us. After we’ve generated the template plugin, we’ll be capable of customize it as we see fit. With Sketch open, test the menu bar at the top of the screen and click Plugins -> Run Script.

This will open up a dialog container that we are able to use to test and run the code.

const UI = require(“sketch/ui”);
UI.message(“message”);

2. Next, hit Save Script as Plugin inside the bottom-left of the window, input whatever name you’d like for this plugin then Save Script as Plugin .

3. Press “Save” within the bottom-left of the window and enter some thing call you want for this plugin to have.

Congratulations, you’ve just written your first Sketch plugin!

First, it imports the sketch/ui module of Sketch’s built-in JS library, and assigns it to the UI variable. This module contains many useful interface-related methods, we’ll use:

const UI = require(“sketch/ui”);

Next, it calls the message method with the string of text we want displayed in the tooltip we saw:

UI.message(“message”);

The message() method sends message to the user.There’s also different ways to give common UI elements like alerts, prompts, and such, a number of which we’ll be the use of as we construct Mosaic.

CUSTOMIZING OUR PLUGIN’S METADATA

We now have a simple plugin to begin from, but we nonetheless need to tweak it to change the plugin’s metadata. For this step, we’ll want to peek into what’s referred to as the plugin bundle.

When you hit save the ‘Run Script’ window, Sketch saved your plugin as a folder named Mosaic.Sketchplugin that you could discover inside the ~/Library/Application Support/com.Bohemiancoding.Sketch3/Plugins listing. You could also pull it up through Plugins -> Manage Plugins -> (proper-click on your plugin) -> Reveal Plugins Folder.

Sketch registered the .Sketchplugin extension as a “bundle” (a special sort of folder that looks as a record) and requested for it to routinely open in Sketch while opened. Right-click on Mosaic.Sketchplugin, then click “Show Package Contents”.

Inside, you should see the following listing :

Contents/

└ Resources/

└ Sketch/

└ manifest.Json

└ script.Cocoascript

Go ahead and rename the last report to index.Js,

Contents/

└ Resources/

└ Sketch/

└ manifest.Json

└ index.Js

Let’s start by tweaking the file named manifest.json.

The plugin appear serves mainly two purposes:

First, it presents metadata that describes the plugin to the user — such things as its call, version, the writer’s name, and so on. Sketch makes use of this records within the Sketch -> Preferences -> Plugins dialog to create a listing and description in your plugin.

Second, it additionally tells Sketch approximately the way to get right down to your business; that is, it tells Sketch how you’d like your plugin’s menu to appearance, what hotkeys to assign in your plugin, and where your plugin’s code.

{
“description”: “Generate awesome designs and repeating patterns from your layers!”,
“x”: “=> Your name here <=”
}
Change your identifier to com.your-name.mosaic:

{
“identifier”: “com.your-name.mosaic”
}
The menu and commands keys are responsible for telling Sketch what code to call and in response to what

{
“menu”: {
“title” : “Mosaic”,
“items” : [
“com.bohemiancoding.sketch.runscriptidentifier”
],
“isRoot”: true
}
}

This tells Sketch to place the first level of menu items directly under the Plugins menu, rather than nesting them under the menu’s title.

{
“menu”: {
“title” : “Mosaic”,
“items” : [
“open”,
{
“title” : “I’m a sub-menu!”,
“items” : [
“another-command-identifier”
]
}
]
}
}

Open Sketch/index.js in your code editor, delete what’s already there, and paste in the following:

function onRun(context){
const window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(
NSMakeRect(0, 0, 145, 500),
NSWindowStyleMaskClosable | NSWindowStyleMaskTitled | NSWindowStyleMaskResizable,
NSBackingStoreBuffered,
false
);

window.releasedWhenClosed = false;

window.makeKeyAndOrderFront(nil);
};

const window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer(
NSMakeRect(0, 0, 145, 500),
NSWindowStyleMaskClosable | NSWindowStyleMaskTitled | NSWindowStyleMaskResizable,
NSBackingStoreBuffered,
false
);

Code Explanation:

First, we name alloc() on NSWindow; this basically means “set apart a few reminiscence for an instance of NSWindow”. It’s sufficient to realize that you’ll have to try this for every instance of a local class you want to create. The alloc technique is available in every native magnificence.

Next, we name NSWindow’s initializer method (that is, the method that truely creates an instance of NSWindow), which is known as initWithContentRect:styleMask:backing:defer:. You’ll word that’s one-of-a-kind from what we call in our code above — it’s were given a gaggle of colons (:) between every argument. Since we can’t use that syntax in JavaScript, Sketch without difficulty renames it to something we can sincerely use by way of replacing the colons with underscores, which is how we get its JS name:

initWithContentRect_styleMask_backing_defer.

Next, we skip in each of the arguments the technique needs. For the first argument, contentRect, we supply a rectangle with a size massive sufficient for our consumer interface.

For styleMask, we use a bitmask which says that we want our window to have a near button, a title bar, and to be resizable.

The next arguments, backing and defer, are continually going to be set to NSBackingStoreBuffered and false, so we don’t really need to worry about them.

THE INTERFACE

download the HTML and CSS code here

Once you’ve downloaded it, extract it, then move the folder named “web-ui” into our plugin’s Resources folder.

We’ll add the code needed to create our WKWebView beneath the code we wrote for our window:

function onRun(context){
// Create window

const window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer(
NSMakeRect(0, 0, 145, 500),
NSWindowStyleMaskClosable | NSWindowStyleMaskTitled | NSWindowStyleMaskResizable,
NSBackingStoreBuffered,
false
);

window.releasedWhenClosed = false;

// Create web view, and set it as the view for our window to display

const webView = WKWebView.alloc().init();

window.contentView = webView;

// Load our UI into the web view

const webUIFolderURL = context.scriptURL
.URLByDeletingLastPathComponent()
.URLByAppendingPathComponent(“../Resources/web-ui/”);

const indexURL = webUIFolderURL.URLByAppendingPathComponent(“index.html”);

webView.loadFileURL_allowingReadAccessToURL(indexURL, webUIFolderURL);

// Make window key and move to front

window.makeKeyAndOrderFront(nil);
};

If we run our plugin now, we’ll see that now we’ve got a window open that displays our web user interface. Success!

Again, before moving on, let’s examine what the code we added does:

const webView = WKWebView.alloc().init();

This should look familiar — it’s basically the same as what we did when we made our NSWindow: allocate memory for a web view, then initialize it.

window.contentView = webView;

This line of code tells our window to display the web view we just made.

const webUIFolderURL = context.scriptURL
.URLByDeletingLastPathComponent()
.URLByAppendingPathComponent(“../Resources/web-ui/”);
Make it as follows
file://path-to-your-plugin/Contents/Resources/web-ui/
Consider the following alterations:
window.standardWindowButton(NSWindowZoomButton).hidden = true;
window.standardWindowButton(NSWindowMiniaturizeButton).hidden = true;
window.floatingPanel = true;
window.becomesKeyOnlyIfNeeded = true;
window.frameAutosaveName = “mosaic-panel-frame”;

For the full code and its working visit:

ORGANIZING THE CODE

We will be happy to answer your questions on designing, developing, and deploying comprehensive enterprise web, mobile apps and customized software solutions that best fit your organization needs.

As a reputed Software Solutions Developer we have expertise in providing dedicated  remote and outsourced technical resources for software services at very nominal cost. Besides experts in full stacks We also build web solutions, mobile apps and work on system integration, performance enhancement, cloud migrations and big data analytics. Don’t hesitate to get in touch with us!

Leave a Reply

Your email address will not be published. Required fields are marked *