正文
代码结构
manifest.json
用来声明插件配置信息,commands 定义所有可执行命令,每条 command 有唯一标志符,identifier,menu 定义插件菜单,通过 identifier 关联到执行命令。handlers.actions 下面可以配置需要监听的事件,Sketch 会在事件被触发时执行相应的事件方法,可以在
Action List
这里看到所有的 Action 或者装一个
Action-Logger
插件可以看到事件什么时候触发。
{
"name" : "first-plugin",
"identifier" : "com.w3ctrain",
"version" : "1.0",
"description" : "first plugin",
"author" : "w3ctrain",
"commands" : [
{
"script" : "plugin.js",
"handlers": {
"run": "onRun",
"actions": {
"SelectionChanged.finish": "onSelectionChanged"
}
},
"name": "Say Hello World",
"identifier" : "com.w3ctrain.HelloWorld"
}
],
"menu" : {
"items" : [
"com.w3ctrain.HelloWorld"
],
"title" : "first plugin"
}
}
plugin.js
对应 manifest.json script 字段的执行脚本,这样的脚本可以有很多个,也可以随意命名。
var onRun = function (context) {
context.document.showMessage("Hello World")
}
var onSelectionChanged = function (context) {
var selection = context.actionContext.document.selectedLayers().layers();
if (selection.length >= 1) {
context.actionContext.document.showMessage(`${selection.length} layers selected`)
} else {
context.actionContext.document.showMessage("nothing selected")
}
}
把插件放到 ~/Library/Application Support/com.bohemiancoding.sketch3/Plugins/ 目录下,就可以在 Plugins 菜单中执行。