We recently open-sourced Alembic, a Sketch plugin that extracts colors from images. When I started working on it, I knew that using a basic dialog window wasn’t going to work with the interface I had in mind for it. So, I experimented with other ways to create a custom interface for Sketch plugins and decided to use a floating panel with a WebView inside to create the actual interface.
Unfortunately, there’s not a lot of documentation around how to advancedly use Cocoa for Sketch plugins. In this article, we’ll look into how to create a sample plugin with a floating panel containing a WebView and most importantly, how to make the WebView communicate with Sketch.
If you’re not familiar with building Sketch plugins, I highly recommend starting with Sketch’s Developer Site introduction and basic examples before reading this article. If you have any trouble or questions when experimenting around new ideas for plugins, I also recommend going to the Sketch Plugins forum created by Ale from Sketch, to see if someone already encountered the same problem.
The article is divided into two parts: the first part is about creating the panel and the interface, the second part is about the communication between Sketch and the WebView.
Creating the panel
We’ll start by creating the panel itself, but before doing so, you can download the basic plugin structure to start with. We’re going to use AppKit’s NSPanel class, a subclass of NSWindow used to create secondary windows, which is exactly what we want our panel to be.
We have a panel! The plain white background is a little bland to make it look like a window that belongs in macOS, though. Let’s add a blurred background with AppKit’s NSVisualEffectView class.
The panel is now visually finished, but we have some issues: we can launch as many panels as we want and we can’t close any of them.
To fix the possibility to launch multiple panels, we’ll store a reference to the first panel we open with Foundation’s NSThread. Now, we can check if there’s already a panel opened before running the plugin again.
The next step is to close the panel when the Close button is clicked, we’ll also remove the reference (so we can open it again) and stop the plugin.
Creating the interface
Now that we have the panel, we’ll use WebKit’s WebView class to add a Web page to it, located in the plugin’s Resources folder.
You should now have a floating panel with a local Web page inside, congratulations! If not, everything is fine, here’s the code.
In the next part, we’ll see the most important part: how to make the WebView and Sketch communicate so we can actually do something with the interface we just made. Make sure to be there!