编程语言/sketch:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
Kangkk​(留言 | 贡献)
小 文字替换 -“{{leftrightflex|”替换为“{{Double-columns|”
 
(未显示同一用户的44个中间版本)
第1行: 第1行:
== 引言 ==
== 引言 ==
一个偶然的机会,开始接触设计软件的插件开发,在此记录 sketch 软件的插件开发过程。{{Timepoint|timepoint=2021-6-23 4:47 pm}}
一个偶然的机会,开始接触设计软件的插件开发,在此记录 sketch 软件的插件开发过程。{{Timepoint|timepoint=2021-6-23 4:47 pm}}
== API ==
<blockquote><pre>
Library: Library
Style: Style
Fill: Fill
ImageData: ImageData
Image: Image
Shadow: Shadow
Document: Document
SharedStyle: SharedStyle
Override: Override
Group: Group
Artboard: Artboard
Border: Border
BorderOptions: BorderOptions
Shape: Shape
Blur: Blur
Gradient: Gradient
SymbolMaster: SymbolMaster
DataOverride: DataOverride
Text: Text
HotSpot: HotSpot
Page: Page
ImportableObject: ImportableObject
Flow: Flow
SymbolInstance: SymbolInstance
ShapePath: ShapePath
GradientStop: GradientStop
</pre></blockquote>


== 插件 ==
== 插件 ==
第15行: 第44行:


===== manifest.json =====
===== manifest.json =====
清单 [https://developer.sketch.com/plugins/plugin-manifest manifest.json] 提供集成到 sketch 菜单栏中的信息。示例。
<syntaxhighlight lang="javascript">
{
  "$schema": "https://raw.githubusercontent.com/sketch-hq/SketchAPI/develop/docs/sketch-plugin-manifest-schema.json",
  "icon": "icon.png",
  "appcast": "<网址>/appcast.xml",
  "description": "<描述>",
  "compatibleVersion": "<版本>",
  "commands": [
    {
      "name": "<菜单标签卡选项名称>",
      "identifier": "medici.openPlugin",
      "script": "<引入 js 文件入口的相对地址>",
      "shortcut": "command u",
      "handler": "openPlugin"
    }
  ],
  "menu": {
    "title": "☁️设计云",
    "items": [
      "medici.openPlugin"
    ]
  }
}
</syntaxhighlight>


===== sketch-module-web-view =====
===== sketch-module-web-view =====
加载网页
加载网页
===== Symbolic Link =====
===== sketch/dom =====
<syntaxhighlight lang="javascript">
import sketch from "sketch/dom";</syntaxhighlight>
{| class="wikitable"
|-
| [[/getSelectedDocument|getSelectedDocument]] || 示例 || 示例
|-
| 示例 || 示例 || 示例
|-
| 示例 || 示例 || 示例
|}
== webview ==
{{shc|<syntaxhighlight lang="bash">
npm install sketch-module-web-view --save-dev</syntaxhighlight>|$|/home/kangkk}}
=== 通信 ===
就像 photoshop 一样,ui 界面端通信 sketch 运行环境,需要使用 window.postMessage 方法传递数据。然后 sketch 运行环境通过 webViewContents.on 监听并接收数据。
{| class="wikitable"
|-
! ui 界面端(发送数据) !! sketch 运行环境(接收数据)
|-
| <syntaxhighlight lang="javascript">
window.postMessage('onMyMessage', 'item');
window.postMessage('onMyMessage', {
  foo: 'item'
});
window.postMessage('onMyMessage', 'item', 'foo', 'biz');</syntaxhighlight> || <syntaxhighlight lang="javascript">
webview.webContents.on('onMyMessage', item => {
  Settings.setSettingForKey('key', JSON.stringify(item));
}</syntaxhighlight>
|}
如果想在 sketch 运行环境中向 ui 界面端传递单向数据,也可使用 browserWindow.webContents.executeJavaScript 方法。executeJavaScript 方法可以参考 photoshop 中的 cs.evalScript 方法。大致上是相同的,区别在于 cs.evalScript 在是 ui 界面端 执行 photoshop 运行环境中的方法,而 browserWindow.webContents.executeJavaScript 是反过来的?
{| class="wikitable"
|-
! ui 界面端(接收数据) !! sketch 运行环境(发送数据)
|-
| <syntaxhighlight lang="javascript">
window.somefunc = function(arg) {
  console.log(arg)
}
</syntaxhighlight> || <syntaxhighlight lang="javascript">browserWindow.webContents.executeJavaScript('somefunc("hello")').then(res => {
  // TODO
});
browserWindow.webContents.executeJavaScript(
  `localStorage.setItem("${key}",'${value}')`
);
</syntaxhighlight>
|}
=== html ===
==== iframe ====
在 sketch 的 iframe 中,由于使用 iframe 并不能获取其 contentWindow,这与 photoshop 有着极大的区别。
{{Double-columns|<syntaxhighlight lang="javascript">
console.log(iframe.contentDocument)
console.log(iframe.contentWindow.document)
</syntaxhighlight>|{{consoleout|<pre>Blocked a frame with origin "null" from accessing a frame with origin "https://login.ops.qihoo.net:4430".  The frame requesting access has a protocol of "file", the frame being accessed has a protocol of "https". Protocols must match.
null
SecurityError: Blocked a frame with origin "null" from accessing a cross-origin frame. Protocols, domains, and ports must match.
Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://fb.me/react-crossorigin-error for more information.
</pre>}}}}
所以需要调整策略,改用 postmessage。
== 调试 ==
[https://github.com/skpm/sketch-dev-tools sketch-dev-tools] 用于调试 sketch。
调试日志的位置在:<code>~/Library/Logs/com.bohemiancoding.sketch3/Plugin Log.log</code>
更方便的做法是打开控制台,在日志报告的选项卡里我们可以直接找到 <code>Plugin Log.log</code> 这个文件。里面记录了在 sketch 插件运行环境的所有 <code>console</code> 的输出。
<div class="pageBoxGreen">这里需要注意的是 sketch 插件运行环境,也就是 cocoascript 环境,我的理解是是一种 js 的变体 dsl。</div>
以上就是在 sketch 插件运行环境的 <code>console</code> 输出获取方式。ui 层的 <code>console</code> 输出获取可以直接在插件上点击右键审视元素,打开浏览器的开发者工具,里面有你所有想要的~~。
=== 联调 ===
为了方便,我单独设置了 <code>symbolic link</code> 在 npm 里面。
<syntaxhighlight lang="javascript">...
  "scripts": {
    ...
    "link": "skpm-link",
    ...
  },
...</syntaxhighlight>
这样虽然多出来了一步操作,但是更方便我清晰知道哪一步的作用是什么,当执行 <code>npm run link</code> 之后,会在 sketch 的插件文件夹内生成一个被命名为插件名称的文件夹,文件夹内是一个项目内 <code>npm start</code> 构建出来的 sketch 插件的软连接。
[[文件:Sketch-symbolic-link-1.png|600px|无框|无|sketch插件软连接与真实插件的区别]]
== cocoascript ==
[https://developer.sketch.com/plugins/cocoascript cocoascript] 环境。
== 编辑器 ==
通知 sketch 使用一个编辑器编辑插件。
{{shc|<syntaxhighlight lang="bash">
defaults write ~/Library/Preferences/com.bohemiancoding.sketch3.plist "Plugin Editor" "/usr/local/bin/atom"</syntaxhighlight>|$|/home/kangkk}}
== 项目结构 ==
要扩展插件,所以我重构了一下项目的结构,现如下(重构中,并不是最终结果)。
{{Double-columns|<pre>
.
├── assets
│   ├── icon.png
│   └── question.png
├── package.json
├── package-lock.json
├── README.md
├── scripts
│   ├── build-test.js
│   └── update-version.js
├── src
│   ├── api
│   │   ├── action
│   │   │   ├── artboard.ts
│   │   │   ├── assist.ts
│   │   │   ├── cocoa.ts
│   │   │   ├── config.ts
│   │   │   ├── document.ts
│   │   │   ├── export.ts
│   │   │   ├── file.ts
│   │   │   ├── info.ts
│   │   │   ├── layer.ts
│   │   │   ├── page.ts
│   │   │   ├── slice.ts
│   │   │   └── type.ts
│   │   ├── communication
│   │   │   ├── login
│   │   │   │   ├── receive.ts
│   │   │   │   └── send.ts
│   │   │   └── plugin
│   │   │      ├── receive.ts
│   │   │      └── send.ts
│   │   ├── controller
│   │   │   ├── feedback
│   │   │   │   └── feedback.ts
│   │   │   ├── login
│   │   │   │   └── index.ts
│   │   │   └── plugin
│   │   │      └── index.ts
│   │   ├── extend
│   │   │   └── cache.ts
│   │   └── store
│   │      ├── index.ts
│   │      └── token.ts
│   ├── client
│   │   ├── communication
│   │   │   └── plugin
│   │   │      ├── receive.js
│   │   │      └── send.ts
│   │   ├── config
│   │   │   ├── http.ts
│   │   │   └── uuap.ts
│   │   ├── extend
│   │   │   └──  ajax.ts
│   │   ├── page
│   │   │   ├── error
│   │   │   │   ├── noNet.tsx
│   │   │   │   └── type.ts
│   │   │   ├── feedback
│   │   │   │   └── feedback.ts
│   │   │   ├── login
│   │   │   │   └── index.ts
│   │   │   └── plugin
│   │   │      ├── index.tsx
│   │   │      ├── root.tsx
│   │   │      ├── style.less
│   │   │      └── type.ts
│   │   ├── service
│   │   │   ├── artboard.ts
│   │   │   ├── group.ts
│   │   │   ├── project.ts
│   │   │   ├── team.ts
│   │   │   └── type.ts
│   │   ├── store
│   │   │   ├── index.ts
│   │   │   └── token.ts
│   │   ├── template
│   │   │   ├── feedback
│   │   │   │   └── index.html
│   │   │   └── plugin
│   │   │      └── index.html
│   │   └── util
│   │      ├── ajax.ts
│   │      ├── file.ts
│   │      └── type.ts
│   ├── manifest.json
│   └── types
│      ├── sketch-module-web-view.d.ts
│      ├── skpm-dialog.d.ts
│      ├── skpm-fs.d.ts
│      ├── skpm-path.d.ts
│      └── window.d.ts
├── tsconfig.json
├── webpack.skpm.config.js
└── yarn.lock
</pre>|<blockquote>
我将运行环境和 UI 分开,模拟前后端的概念,当插件加载的时候,会先寻找 <code>package.json</code> 中的 <code>skpm.resources</code> 参数,打包的是模拟出来的前端 <code>client</code> 代码。
<syntaxhighlight lang="javascript">...
  "skpm": {
    "name": "360设计云",
    "manifest": "src/manifest.json",
    "main": "medici.sketchplugin",
    "assets": [
      "assets/**/*"
    ],
    "resources": [
      "src/client/communication/plugin/receive.js"
    ]
  },
...</syntaxhighlight>
后端加载则通过打包 <code>src/manifest.json</code> 文件中的 <code>commands.script</code>,并调用 <code>commands.script</code> 引入的文件中的钩子函数 <code>commands.handler</code>。
<syntaxhighlight lang="javascript">...
  "commands": [
    {
      "name": "上传画板",
      "identifier": "medici.openPlugin",
      "script": "./api/controller/plugin/index.ts",
      "shortcut": "command u",
      "handler": "openPlugin"
    }
  ],
...</syntaxhighlight>
前后数据交互通过 <code>communication</code> 文件夹内的文件进行。<br>
在这个项目中,UI 层使用的是封装的 webview,这里有一个需要注意的地方是 webview 引入了页面模板(不管是 HTML 还是 EJS,或者其他),在模板中引入 JS 文件时,使用的是打包生成后的文件在 sketch 插件包中的相对路径。并且引入文件格式是 <code>.js</code>,示例如下。
{{Hc|src/client/template/plugin/index.html|<syntaxhighlight lang="html5">
...
    <!-- 寻址路径 -->
    <script src="../src_client_communication_plugin_receive.js" ></script>
  </body>
...</syntaxhighlight>
}}
简单示意图。
[[文件:Sketch-plugin-design-1.png|600px|无框|无|Sketch-plugin-design-1]]
</blockquote>
}}
== sketchObject ==
[[/sketchObject|sketchObject]]
== other ==
{| class="wikitable"
|-
| roadhog || cross-env || concurrently
|-
| sketch-dev-tools || 示例 || 示例
|}
=== sharedStyleId ===
<syntaxhighlight lang="javascript">
const outOfSync = !!layer.sharedStyleId && layer.style.isOutOfSyncWithSharedStyle(layer.sharedStyle)</syntaxhighlight>
=== symbolId ===
获取 MSSymbolMaster。[[/MSSymbolMaster|MSSymbolMaster]] 的示例。
{{Double-columns|<syntaxhighlight lang="javascript">
const document = context.document;
log(document.documentData().symbolWithID(layer?.symbolId));</syntaxhighlight>|{{consoleout|<pre>
<MSSymbolMaster: 0x7fe41b62d400> icon_using document (3C94663C-B213-4FCD-A7CB-43A6AA877859)
</pre>}}}}
获取 symbol 样式。
{{Double-columns|<syntaxhighlight lang="javascript">
if (layer?.symbolId) {
  const document = context.document;
  const immutableMaster = document.documentData().symbolWithID(layer?.symbolId);
  const layerItem = sketch.fromNative(immutableMaster);
  log(layerItem);
}</syntaxhighlight>|{{consoleout|<pre>
if (layer?.symbolId) {
    const document = context.document;
    const immutableMaster = document.documentData().symbolWithID(layer?.symbolId);
    const layerItem = sketch.fromNative(immutableMaster);
    log(layerItem);
  }
...
        type = Style;
        verticalAlignment = "<MOUndefined: 0x6000025b8da0>";
    };
    symbolId = "9AD4358B-C5B7-4D59-BBA3-D451D757685E";
    transform =    {
    };
    type = SymbolMaster;
}
</pre>}}}}
=== MSImmutableSymbolMaster ===
{{Double-columns|<syntaxhighlight lang="javascript">
const document = context.document;
const immutableMaster = document.documentData().symbolWithID(layer?.symbolId).immutableModelObject();
log(immutableMaster)</syntaxhighlight>|{{consoleout|<pre>
MSImmutableSymbolMaster: 0x7fe942b0d7d0> icon_using document (3C94663C-B213-4FCD-A7CB-43A6AA877859)
</pre>}}}}
== 示例 ==
{| class="wikitable"
|-
| [https://github.com/MagicSketch/MagicMirror MagicMirror] || [https://github.com/timuric/Content-generator-sketch-plugin Content-generator-sketch-plugin] ||[https://github.com/utom/sketch-measure sketch-measure]
|}
== 参考 ==
== 参考 ==
* https://developer.sketch.com/reference/api/
* https://developer.sketch.com/reference/api/
* https://developer.sketch.com/plugins/debugging/
* https://www.sketch.com/extensions/plugins/
* https://sketchplugins.com/
* https://github.com/sketch-hq/sketch-document/
* https://github.com/sketch-hq/SketchAPI