The Beginner’s Guide to Writing Sketch Plugins Part 4 — Real World Examples

In the previous articles, we learned how to set up our coding environment for debugging, how to display multiple kinds of user notifications, and what a few basic coding concepts can do. With all of this, the foundation is set to start writing our own plugins.

Luckily Bohemian Coding has provided some documentation to their classes: http://developer.sketchapp.com/reference/class/

Unluckily, as it’s explained at the top of that page, it’s a “work in progress.” So not everything is listed out, and there aren’t many examples of what to do with it.

Personally, I learn best by example. Understanding code can be very challenging, but when you see it used in a way that’s relatable to your own knowledge or experience, it becomes much easier. So the following are three use cases I’ve found while working with Sketch, and hopefully they’re similar to your own or you find them useful!

Example 1: Switching an artboard’s height and width

Changing an artboard from portrait to landscape or vice versa, is something that Sketch strangely doesn’t do. I did a quick search and was unable to find another plugin that does this, so this is an ideal time to write our own!

For clarity, let’s outline what we’re going to do in normal words. By doing this, we’re clear about what we want to do and how we’re going to do it. It also helps identify any edge cases we might encounter. It’s almost like doing a UX flow right?

For this plugin, we will be writing a script that does the following:

  • First, make sure something is selected
  • Then make sure the something selected is an artboard
  • Then get the original height and width of the selected artboard and store them in variables
  • Then set a new height based on the old width and set a new width based on the old height
  • Finally, alert the user when the script is done

Adding another script to your MyPlugin

Instead of adding more code to MyScript.js from the previous articles, let’s just create a new script called RotateArtboard.js and add it to our MyPlugin.sketchplugin folder.

Add the following code into RotateArtboard.js. Every main script needs to be in an onRun function, so this script is always a good base to start from:

You’ll notice we’re importing our common.js file from the previous article, so we can use the same alert function we already wrote!

Based on the previous articles, you should have these files in there:

Now, open up manifest.json, so we can add another script to our manifest.

Copy the block of code that has all the MyScript.js commands, add a comma after the MyScript block, and paste before the commands end bracket like this:

You should now see the new script in your MyPlugin menu (feel free to change shortcuts by the way, these are just placeholder):

Now that we’re all set up, back to the code!

To get what’s selected, you use the following:

var selection = context.selection;

This creates an array variable with all the layers that are selected. Now we can check that array to see if there’s anything inside it. If the count is 0, then nothing is selected, so we’ll tell the user to select something.

if(selection.count() == 0){
doc.showMessage("Please select something.";
}

But if the count is not 0, then there is something inside it, and at least one layer must be selected. Now we can loop through the selected layers, to check if they are artboards (an MSArtboardGroup):

if(selection.count() == 0){
doc.showMessage("Please select something.");
} else {
for(var i = 0; i < selection.count(); i++){
if(selection[i].class() == "MSArtboardGroup"){
//do something
}
}
}

You can use this same technique to check if a selection is a Text Layer (MSTextLayer), a Group (MSGroupLayer), a Shape (MSShapeGroup / undocumented), an Imported Image (MSBitmapLayer), or a Symbol (MSSymbolInstance / undocumented).

To get an artboard’s height and width, you first need to get its frame. Through the frame, you can both get and set values.

Create a variable called artboard based on the array item in the for loop, then we can get it’s current values. Using a for loop ensures that we can select multiple artboards at a time.

var artboard = selection[i];
var artboardFrame = artboard.frame();
var artboardWidth = artboardFrame.width();
var artboardHeight = artboardFrame.height();

Now create two new variables with the values we actually want, which is the height and width flipped:

 var newArtboardWidth = artboardHeight;
var newArtboardHeight = artboardWidth;

Then we use artboardFrame to set the width and height with the new variables:

 artboardFrame.setWidth(newArtboardWidth);
artboardFrame.setHeight(newArtboardHeight);

And finally, we’ll user our custom alert to tell the user that the script is done and display the new values:

var alertMessage = "New Height: "+newArtboardHeight+ " | New Width: "+newArtboardWidth;
alert(“Artboard Rotated!", alertMessage)

Here is the entire script with comments:

Example 1 Summary:

So in this example, we learned how to:

  • Check if something is selected
  • Figure out what type of layer is selected, then do something if it’s the one we want
  • Get our selected artboard’s original frame, height, and width and store it in a variable
  • Create new variables with the values we want
  • Set our selected artboard’s frame with those variables

Example 2: Selecting layers and setting their names to it’s symbol name

Here’s another real world issue that I found while using symbols. If I add a brand new symbol from my library, the layer name changes to the name of symbol. If I switch that symbol to a different symbol, the layer name remains the old name. Sometimes I want the layer name generic, but other times I don’t and want to reset it to the new symbol. Another perfect time for a plugin!

For this example, download this Sketch file for reference.

In the Sketch file, you’ll see on the first artboard there’s a symbol called Square centered in the middle. There’s also another symbol in the library called Circle.

Select Square and using the options on the right change the Square to Circle

Now look at the layers on the left, it still says Square! I guess I could manually change it, but that’s no fun, especially if you have multiple instances that need to be changed.

For this plugin, let’s outline what we’re going to do again:

  • First make sure something is selected
  • Then make sure the something is a Symbol
  • Then get the name of the Symbol
  • Then check if the name of the Symbol is the name of the layer
  • If not, change the layer name to the name of the Symbol
  • Finally, alert the user when the script is done

You’ll notice that there are some similarities between this script and the last, mainly making sure something is selected, then checking what that selection is. So we can reuse some of these concepts here, but since it’s a pretty specific use case, we’ll keep them as separate scripts.

Following the first steps from the last example, let’s add another script to MyPlugin.sketchplugin by creating a new file called SetLayerNameToSymbolName.js and add it to manifest.json. To save some time, just use RotateArtboard.js and “Save As”. We’ll be using a lot of this script already, so we might as well start from there and change a few things.

Your folder should now have these files:

In this script, instead of checking if the selection is an MSArtboardGroup, we’ll check if it’s an MSSymbolInstance. Then if it is, we can get the symbolMaster name and compare it to the layer name.

Here’s the new script with just a few lines changed:

Example 2 Summary

In this example we learned:

  • That the same technique to check if a selection is an artboard is the same way to check if a selection is a symbol
  • How to get the symbolMaster name and layer name
  • How to compare the two and set the layer name if they differ

Example 3: Setting all layer names to the symbol name

The previous script works perfectly, but sometimes I don’t want to select the layers manually. Sometimes after swapping a lot of symbols in my document, I just want to reset all the layer names back to their symbol name without selecting the layer. To do this we’ll need to do a few things differently:

  • First, get all the pages in the document
  • Then get all the artboards in each page
  • Then get all the layers in each artboard
  • Then we can check if any of those layers is a Symbol layer
  • Then check if the layer name doesn’t already equal the symbol name
  • If so, change the layer name and alert the user

Since we’re no longer looking at what’s selected, we’ll need to modify our script to loop through the document page data instead. Then we’ll use a series of nested for loops to iterate through the artboards array, then layers array, to finally get to each layer. A for loop, inside a for loop, inside a for loop. Forloopception!

We’d probably want to keep our original script to change the layer names by selection since that is also convenient, so for this one we’ll create another new script.

Start by saving a new file called: SetAllLayerNamesToSymbolNames.js and also add it to the manifest.json like we did before.

You should now have this many files in your MyPlugin.sketchplugin folder:

And the plugin in your menu list, along with the previous examples should display this after you add it to the manifest:

To get a documents page data you’d use this:

var pages = [doc pages];

To get the artboards in a page, you need to use a for loop:

To get the layers in an artboard, you need to use a for loop inside that for loop:

Then to get each individual layer, you need loop through the layers inside that for loop, then finally check what kind of layer it is:

Once we know that it’s a symbol layer, we can then move on to checking it’s name and comparing it to the layer name. Then if they are different, set the layer name to the symbol name, and that’s it!

Here’s what the entire script looks like, I’ve commented almost every line to help explain what’s going on:

Example 3 Summary:

In this example, we learned how to:

  • Loop through all the pages of the document to get to the artboards
  • Then loop through the artboards of the page to get to the layers
  • Then loop through the layers of the artboard to check what type it is
  • Then compare the layer name to the symbol name
  • Then finally, if the names are different, change the layer name to the symbol’s name

Conclusion

So these are just three examples of how you can start to use all the basic coding concepts we’ve learned with Sketch’s available classes. There’s much more you can do, but we’re really just getting started! Coming up next, I’ll be listing out even more ways to access additional classes inside Sketch, and providing more real world examples.

Thanks for all the recommends and shares so far, I’m glad to know these have been useful, see you next time!

You can download the plugin here. And as always, feel free to contact me or comment if you have any questions, feedback or suggestions. Twitter, Facebook, Email.

Continue to Part 5

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.