Repository: romannurik/Sketch-Stickers
Branch: master
Commit: 379963ff5266
Files: 33
Total size: 106.8 KB
Directory structure:
gitextract_wp65fbp2/
├── .appcast.xml
├── .gitignore
├── .vscode/
│ └── settings.json
├── LICENSE
├── README.md
├── assets/
│ └── plugin-call.js
├── examples/
│ └── Stickers Example Library.sketch
├── package.json
├── skpm-build-with-child.js
├── src/
│ ├── color-util.js
│ ├── commands.js
│ ├── manifest.json
│ ├── sticker-index.js
│ ├── stickers-ui.js
│ ├── util-libraries.js
│ ├── util-progress-reporter.js
│ └── util.js
└── web/
├── index.js
├── package.json
├── src/
│ ├── .gitignore
│ ├── _stub-sticker-index.json.readme.md
│ ├── client.js
│ ├── components/
│ │ ├── button/
│ │ │ └── button.scss
│ │ └── zerostate/
│ │ └── zerostate.scss
│ ├── index.html
│ ├── index.js
│ ├── index.scss
│ ├── lib/
│ │ ├── element-visibility.js
│ │ ├── embedded-ui.scss
│ │ └── svg-icons.scss
│ ├── plugin-call-stub.js
│ └── variables.scss
└── webpack.config.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .appcast.xml
================================================
================================================
FILE: .gitignore
================================================
# build artifacts
web-dist
_sandbox
*.sketchplugin
# npm
node_modules
.npm
npm-debug.log
# mac
.DS_Store
# WebStorm
.idea
================================================
FILE: .vscode/settings.json
================================================
{
"search.exclude": {
"**/node_modules": true,
"*.sketchplugin": true,
"web-dist": true,
}
}
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================

# Stickers plugin for Sketch
A Sketch plugin that lets you browse and quickly drag+drop stickers ([specially tagged layers](https://github.com/romannurik/Sketch-Stickers/wiki/Getting-started-for-stickersheet-authors)) in your Sketch Libraries.

# Installation
* [Download the latest release](https://github.com/romannurik/Sketch-Stickers/releases/latest) and double-click the `.sketchplugin` file to install.
* Or you can install the plugin with [Sketch Runner](http://bit.ly/SketchRunnerWebsite).
# Build instructions
_This plugin was created using `skpm`. For a detailed explanation on how things work, checkout the [skpm Readme](https://github.com/skpm/skpm/blob/master/README.md)._
================================================
FILE: assets/plugin-call.js
================================================
/*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
window['pluginCall'] = window.postMessage;
================================================
FILE: package.json
================================================
{
"name": "sketch-stickers",
"description": "A Sketch plugin that lets you browse and quickly drag+drop stickers (specially tagged layers) in your Sketch Libraries.",
"version": "0.3.11",
"engines": {
"sketch": ">=49.0"
},
"skpm": {
"name": "Stickers",
"manifest": "src/manifest.json",
"main": "Stickers.sketchplugin",
"assets": [
"assets/**/*",
"!assets/**/*.js",
"web-dist/**/*",
"!web-dist/plugin-call.js"
]
},
"scripts": {
"build": "./skpm-build-with-child.js web",
"watch": "./skpm-build-with-child.js web --watch",
"postinstall": "npm run build && skpm-link"
},
"resources": [
"assets/**/*.js"
],
"repository": {
"type": "git",
"url": "https://github.com/romannurik/Sketch-Stickers.git"
},
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/romannurik/Sketch-Stickers/issues"
},
"homepage": "https://github.com/romannurik/Sketch-Stickers#readme",
"author": "Roman Nurik ",
"dependencies": {
"@skpm/events": "^0.1.1",
"@skpm/fs": "^0.1.2",
"@skpm/path": "^0.1.0",
"babel-polyfill": "^6.26.0",
"js-yaml": "^3.11.0",
"mocha-js-delegate": "^0.1.1",
"sketch-module-web-view": "3.5.1"
},
"devDependencies": {
"@skpm/builder": "^0.5.4"
}
}
================================================
FILE: skpm-build-with-child.js
================================================
#!/usr/bin/env node
const {spawn} = require('child_process');
const process = require('process');
run();
async function run() {
let watchMode = process.argv.includes('--watch');
const web = require('./web');
if (!watchMode) {
await web.build();
await skpmBuild();
} else {
let firstRun = true;
// watch changes to the web app
web.watch((err, stats) => {
skpmBuild(firstRun ? ['--watch'] : []);
firstRun = false;
});
}
}
function skpmBuild(args) {
return new Promise((resolve, reject) => {
const skpmBuild = spawn('skpm-build', args);
skpmBuild.stdout.pipe(process.stdout);
skpmBuild.stderr.pipe(process.stderr);
skpmBuild.on('close', (code) => resolve());
});
}
================================================
FILE: src/color-util.js
================================================
/**
* Returns true if every color in the array of SVG colors is already
* in the document.
*/
export function areAllLibraryColorsInDocument(libSvgColors, document) {
let assets = document.documentData().assets();
let libMSColors = libSvgColors.map(c => svgColorToMSColor(c));
// collect all colors currently in this doc that aren't in the
// target colors and save them, to add back at the end
let existingColors = assets.colorAssets
? Array.from(assets.colorAssets()).map(ca => ca.color())
: Array.from(assets.colors());
let libColorsInDoc = libMSColors
.filter(libColor => existingColors.find(docColor => docColor.isEqual(libColor)));
return libColorsInDoc.length == libMSColors.length;
}
/**
* Adds all the colors in the given array of SVG colors to the document's
* colors.
*/
export function addLibraryColorsToDocument(libSvgColors, document) {
// TODO: error out on Sketch 53
let assets = document.documentData().assets();
let libMSColors = libSvgColors.map(c => svgColorToMSColor(c));
// collect all colors currently in this doc that aren't in the
// target colors and save them, to add back at the end
let existingColorsToKeep = Array.from(assets.colors())
.filter(color =>
libMSColors.reduce(
(keep, libColor) => keep && !color.isEqual(libColor), true));
assets.removeAllColors();
libMSColors.forEach(color => assets.addColor(color));
existingColorsToKeep.forEach(color => assets.addColor(color));
}
/**
* Converts an SVG/CSS color string like '#fff' or 'rgba(...)'
* to an MSColor
*/
export function svgColorToMSColor(color) {
let ic = MSImmutableColor.colorWithSVGString(color);
return MSColor.alloc().initWithRed_green_blue_alpha_(
ic.red(), ic.green(), ic.blue(), ic.alpha());
}
/**
* Converts an MSColor to an SVG/CSS color string.
*/
export function msColorToSVGColor(color) {
let r = Math.round(255 * color.red());
let g = Math.round(255 * color.green());
let b = Math.round(255 * color.blue());
let a = Number(Number(color.alpha()).toFixed(2));
return `rgba(${r}, ${g}, ${b}, ${a})`;
}
================================================
FILE: src/commands.js
================================================
/*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if (!global._babelPolyfill) {
require('babel-polyfill');
}
import {StickersUI} from './stickers-ui.js';
import * as util from './util';
export function onShowStickers(context) {
let window = new StickersUI(context);
window.showHide();
}
export function onClearCache(context) {
util.rmdirRecursive(util.getPluginCachePath());
context.document.showMessage(`✅ Sticker library index cleared`);
}
================================================
FILE: src/manifest.json
================================================
{
"identifier" : "net.nurik.roman.sketch.stickers",
"compatibleVersion": 49,
"bundleVersion": 1,
"icon": "icon-plugin.png",
"commands": [
{
"script" : "./commands.js",
"handlers": {
"run": "onShowStickers"
},
"name" : "Show Stickers",
"shortcut": "cmd shift \\",
"identifier" : "show_stickers",
"description" : "Show or hide the Stickers window.",
"icon" : "icon-menu.png"
},
{
"script" : "./commands.js",
"handlers": {
"run": "onClearCache"
},
"name" : "Clear Library Index",
"identifier" : "clear_cache",
"description" : "Clear the Stickers library index for troubleshooting purposes.",
"icon" : "icon-menu.png"
}
],
"menu": {
"items": [
"show_stickers",
"-",
"clear_cache"
],
"title": "Stickers"
}
}
================================================
FILE: src/sticker-index.js
================================================
/*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import fs from '@skpm/fs';
import path from '@skpm/path';
import yaml from 'js-yaml';
import * as util from './util';
import * as colorUtil from './color-util';
import {ProgressReporter} from './util-progress-reporter';
const INDEX_FORMAT_VERSION = 4;
const FORCE_REBULD = false;
/**
* Returns a sticker index JSON for the user's libraries, building and caching it
* if needed.
*/
export async function makeStickerIndexForLibraries({onProgress}) {
let libraries = Array.from(NSApp.delegate().librariesController().libraries())
.filter(lib => !!lib.locationOnDisk() && !!lib.enabled() && !!lib.libraryID())
.map(lib => ({
libraryId: String(lib.libraryID()),
name: String(lib.name()),
sketchFilePath: String(lib.locationOnDisk().path()),
}))
// filter out duplicate library IDs
.filter((lib, index, self) => {
let firstWithId = self.findIndex(l => l.libraryId === lib.libraryId) === index;
if (!firstWithId) {
log(`Library at ${lib.sketchFilePath} not shown, there's already a library ` +
`with ID ${lib.libraryId} in the list of libraries.`);
}
return firstWithId;
});
let progressReporter = new ProgressReporter();
progressReporter.on('progress', progress => onProgress(progress));
let childProgressReporters = progressReporter.makeChildren(libraries.length);
// build indexes
let compositeIndex = {libraries: []};
for (let [i, lib] of libraries.entries()) {
await util.unpeg();
// for this library, checksum the contents so we can later check if it's changed
// NOTE: performance should be pretty good for files a few MB in size
let fileHash = String(NSFileManager.defaultManager()
.contentsAtPath(lib.sketchFilePath).sha1AsString());
let cachePath = path.join(util.getPluginCachePath(), lib.libraryId);
let libraryIndex = null;
let indexCachePath = path.join(cachePath, 'index.json');
try {
libraryIndex = JSON.parse(fs.readFileSync(indexCachePath, {encoding: 'utf8'}));
} catch (e) {
}
if (FORCE_REBULD ||
!libraryIndex ||
!libraryIndex.archiveVersion ||
libraryIndex.fileHash !== fileHash ||
(libraryIndex.formatVersion || 0) < INDEX_FORMAT_VERSION) {
// need to rebuild the cached index
let doc = util.loadDocFromSketchFile(lib.sketchFilePath);
doc.setFileURL(NSURL.fileURLWithPath(lib.sketchFilePath));
libraryIndex = await buildStickerIndexForLibrary(
lib.libraryId, lib.name, doc, childProgressReporters[i]);
// store library colors
const assets = doc.documentData().assets();
let colors = [];
if (assets.colorAssets) {
colors = Array.from(assets.colorAssets()).map(ca => ca.color());
} else if (assets.colors) {
colors = assets.colors();
}
if (colors.length) {
libraryIndex.colors = Array.from(colors).map(c => colorUtil.msColorToSVGColor(c));
}
// cache the index
util.mkdirpSync(path.dirname(indexCachePath));
fs.writeFileSync(indexCachePath,
JSON.stringify(Object.assign(libraryIndex, {
archiveVersion: Number(MSArchiveHeader.metadataForNewHeader()['version']),
formatVersion: INDEX_FORMAT_VERSION,
fileHash
})),
{encoding: 'utf8'});
} else {
childProgressReporters[i].forceProgress(1);
}
compositeIndex.libraries.push(libraryIndex);
}
return compositeIndex;
}
/**
* Builds the sticker index for the given library (libraryId and document).
*/
async function buildStickerIndexForLibrary(libraryId, defaultLibName, document, progressReporter) {
let libraryIndex = {id: libraryId, sections: []};
let cachePath = path.join(util.getPluginCachePath(), libraryId);
// first, find sticker sections (stored in text layers)
let sectionsById = {};
let allTextLayers = util.getAllLayersMatchingPredicate(
document,
NSPredicate.predicateWithFormat('className == %@', 'MSTextLayer'));
allTextLayers.reverse(); // layer list order, not stacking order
for (let textLayer of allTextLayers) {
let text = textLayer.stringValue();
if (text.indexOf('!Sticker') < 0) {
continue;
}
let parsedMetadata = parseStickerMetadata(text);
for (let section of parsedMetadata.sections) {
section.libraryId = libraryId;
if (section.id in sectionsById) {
log(`Duplicate sticker section id ${section.id}, skipping duplicates`);
} else {
sectionsById[section.id] = section;
libraryIndex.sections.push(section);
}
}
if (parsedMetadata.libraryMeta.title) {
libraryIndex.title = parsedMetadata.libraryMeta.title;
}
if (parsedMetadata.libraryMeta.subtitle) {
libraryIndex.subtitle = parsedMetadata.libraryMeta.subtitle;
}
}
// nest sections
for (let section of Array.from(libraryIndex.sections)) {
let parentId = section.id.substr(0, section.id.lastIndexOf('.'));
if (parentId) {
let parentSection = sectionsById[parentId];
if (!parentSection) {
log(`Unknown parent section ${parentId}`);
continue;
}
parentSection.items = parentSection.items || [];
parentSection.items.push(section);
// remove from the root
libraryIndex.sections.splice(libraryIndex.sections.indexOf(section), 1);
}
}
// go through all layers tagged to a section
let possibleStickers = util.getAllLayersMatchingPredicate(
document,
NSPredicate.predicateWithFormat('name matches ".*@.*"'));
possibleStickers.reverse(); // layer list order, not stacking order
progressReporter.total = possibleStickers.length;
for (let layer of possibleStickers) {
progressReporter.increment();
if (layer instanceof MSTextLayer && String(layer.name()).startsWith('!Sticker')) {
// for text layers containing actual metadata, don't treat it as a sticker
continue;
}
let parsedName = parseLayerName(layer.name(), sectionId => sectionId in sectionsById);
// if this is an icon, capture it as the icon
if (parsedName.specialInstructions.icon) {
libraryIndex.iconPath = path.join(cachePath, 'icon.png');
util.captureLayerImage(document, layer, libraryIndex.iconPath);
}
if (parsedName.isSticker) {
// this is a sticker
let layerId = String(layer.objectID());
let id = libraryId + '.' + layerId;
let layerInfo = {
type: 'layer',
id,
layer,
name: parsedName.sanitizedName,
imagePath: path.join(cachePath, layerId + '.png'),
contentPath: path.join(cachePath, layerId + '.json'),
width: Number(layer.absoluteInfluenceRect().size.width),
height: Number(layer.absoluteInfluenceRect().size.height),
};
// capture layer image
util.captureLayerImage(document, layer, layerInfo.imagePath);
// capture layer content
let imm = layer.immutableModelObject();
imm.setName(parsedName.sanitizedName);
let serializedLayer = JSON.parse(MSJSONDataArchiver.archiveStringWithRootObject_error_(
imm, null));
fs.writeFileSync(layerInfo.contentPath, JSON.stringify(serializedLayer), {encoding: 'utf8'});
await util.unpeg();
for (let sectionId of parsedName.sectionIds) {
let section = sectionsById[sectionId];
section.items = section.items || [];
section.items.push(layerInfo);
}
}
}
// cull any sections that don't indirectly or directly contain stickers
let nonEmptyItems = items => items.filter(item => {
if (item.type == 'layer') {
return true;
} else if (item.type == 'section') {
item.items = nonEmptyItems(item.items || []);
return item.items.length > 0;
}
});
libraryIndex.sections = nonEmptyItems(libraryIndex.sections);
libraryIndex.title = libraryIndex.title || defaultLibName || util.getDocumentName(document);
return libraryIndex;
}
/**
* Parses the given string for stickers metadata (i.e. "!StickerSection ...")
*/
function parseStickerMetadata(str) {
let parsed = {sections:[], libraryMeta:{}};
let items = str
.replace(/[‘’]/g, `'`)
.replace(/[“”]/g, `"`)
.split(/!Sticker(Section|Library)\s*/g)
.slice(1)
.reduce((result, value, index, array) => {
// split array [1,2,3,4] into pairs [[1,2],[3,4]]
if (index % 2 == 0) {
result.push(array.slice(index, index + 2));
}
return result;
}, []);
for (let [type, text] of items) {
if ('Section' === type) {
let sectionIdMatch = text.match(/^@[\w\.]+$/igm);
if (!sectionIdMatch) {
continue;
}
let id = sectionIdMatch[0];
try {
parsed.sections.push(Object.assign(
{title: id},
yaml.safeLoad(text.substr(sectionIdMatch[0].length)),
{id, items: [], type: 'section'}));
} catch (e) {
log(`Error parsing sticker section YAML for ${id}`);
}
} else if ('Library' === type) {
try {
Object.assign(parsed.libraryMeta, yaml.safeLoad(text));
} catch (e) {
log(`Error parsing library metadata YAML`);
}
}
}
return parsed;
}
const SPECIAL_INSTRUCTIONS = new Set(['icon']);
/**
* Parses the given layer name. The second arg is a function
* that returns true if the given section ID (e.g. "@Foo.Bar") is a
* valid section ID.
*/
function parseLayerName(name, isValidSectionIdFn) {
let parsed = {
isSticker: false,
sectionIds: [],
sanitizedName: name,
specialInstructions: {},
};
name = String(name || '');
let unspecialParts = name
.split(/(@+[\w\.]+)/)
.filter(part => {
if ('@' === part.charAt(0)) {
if ('@' === part.charAt(1)) {
// special instruction
let instr = part.slice(2);
if (SPECIAL_INSTRUCTIONS.has(instr)) {
parsed.specialInstructions[instr] = true;
return false; // remove from sanitized name
}
} else {
// possible section id
if (isValidSectionIdFn(part)) {
parsed.sectionIds.push(part);
parsed.isSticker = true;
return false // remove from sanitized name
} else {
// log(`Sticker section not found ${sectionId} for layer named ${name}`);
// continue;
}
}
}
return true;
});
parsed.sanitizedName = unspecialParts.join('').replace(/^\s+|\s+$/g, '').replace(/\s+/, ' ');
return parsed;
}
================================================
FILE: src/stickers-ui.js
================================================
/*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import path from '@skpm/path';
import fs from '@skpm/fs';
import BrowserWindow from 'sketch-module-web-view';
import * as libraries from './util-libraries';
import * as util from './util';
import * as colorUtil from './color-util';
import {makeStickerIndexForLibraries} from './sticker-index';
const THREAD_DICT_KEY = 'stickers.BrowserWindow';
const UI_MODE = 'cover';
const DARK_MODE = (MSTheme && MSTheme.sharedTheme().isDark)
? MSTheme.sharedTheme().isDark()
: (NSAppKitVersionNumber >= 1671 &&
'Dark' === String(NSUserDefaults.standardUserDefaults().stringForKey('AppleInterfaceStyle')));
const BUILD_SKETCH_53_BETA_1 = 71402;
export class StickersUI {
constructor(context) {
this.context = context;
}
/**
* Shows or hides the Stickers window (if already shown).
* The state is stored in the main thread's threadDictionary.
*/
showHide() {
let browserWindow = this.getPersistedObj();
if (browserWindow) {
if (UI_MODE == 'cover') {
browserWindow.close();
this.setPersistedObj(null);
} else {
browserWindow.show();
}
} else {
this.createAndShow();
}
}
getPersistedObj() {
let threadDict = NSThread.mainThread().threadDictionary();
return threadDict[THREAD_DICT_KEY];
}
setPersistedObj(obj) {
let threadDict = NSThread.mainThread().threadDictionary();
if (obj) {
threadDict[THREAD_DICT_KEY] = obj;
} else {
threadDict.removeObjectForKey(THREAD_DICT_KEY);
}
}
runWebCallback(callbackName, ...args) {
let js = (
`window['${callbackName}'](` +
args.map(arg => JSON.stringify(arg)).join(', ') +
`);`);
try {
this.webContents.executeJavaScript(js);
} catch (e) {
log(e.message);
log(e);
}
}
createAndShow() {
let docWindow = this.context.document.documentWindow();
this.browserWindow = new BrowserWindow({
backgroundColor: '#ffffffff',
identifier: 'stickers.web',
width: 800,
height: 600,
show: false,
alwaysOnTop: UI_MODE == 'palette',
frame: UI_MODE == 'palette',
hasShadow: UI_MODE == 'palette',
acceptsFirstMouse: true,
});
this.webContents = this.browserWindow.webContents;
this.setupWebAPI();
this.browserWindow.on('closed', () => {
this.setPersistedObj(null);
coscript.setShouldKeepAround(false);
});
this.browserWindow.on('blur', () => {
if (UI_MODE == 'cover') {
this.browserWindow.close();
}
});
if (UI_MODE == 'cover') {
this.browserWindow.setResizable(false);
this.browserWindow._panel.setFrame_display_animate_(docWindow.frame(), false, false);
this.browserWindow._panel.setHidesOnDeactivate(false);
}
this.browserWindow.once('ready-to-show', () => {
this.browserWindow.show();
if (UI_MODE == 'cover') {
docWindow.addChildWindow_ordered_(this.browserWindow._panel, NSWindowAbove);
}
});
this.browserWindow.loadURL(String(
this.context.plugin.urlForResourceNamed('index.html') +
`?uiMode=${UI_MODE}&darkMode=${DARK_MODE ? 1 : 0}`));
this.setPersistedObj(this.browserWindow);
}
setupWebAPI() {
let libraryIndexesById = {};
this.webContents.on('loadStickerIndex', (callbackName, progressCallbackName) => {
// trigger the creation of the sticker index
makeStickerIndexForLibraries(
{onProgress: progress => this.runWebCallback(progressCallbackName, progress)})
.then(stickerIndex => {
stickerIndex.libraries.forEach(libraryIndex => {
libraryIndex.colorsAvailable = libraryIndex.colors && libraryIndex.colors.length;
if (MSArchiveHeader.metadataForNewHeader().build >= BUILD_SKETCH_53_BETA_1) {
// no need to do this in Sketch 53
libraryIndex.colorsAvailable = false;
}
if (libraryIndex.colorsAvailable) {
libraryIndex.colorsAdded = colorUtil.areAllLibraryColorsInDocument(
libraryIndex.colors, this.context.document);
}
libraryIndexesById[libraryIndex.id] = libraryIndex;
});
this.runWebCallback(callbackName, stickerIndex);
})
.catch(e => log(e.message));
});
this.webContents.on('openUrl', url => {
NSWorkspace.sharedWorkspace().openURL(NSURL.URLWithString(url));
});
// add a handler for a call from web content's javascript
this.webContents.on('close', () => this.browserWindow.close());
this.webContents.on('requestLayerImageUrl', (stickerId, callbackName) => {
let imagePath = this.getStickerCachedImagePath(stickerId);
// let url = nsImageToDataUri(NSImage.alloc().initWithContentsOfFile(imagePath));
let url = 'file://' + imagePath;
this.runWebCallback(callbackName, stickerId, url);
});
// add a handler for a call from web content's javascript
this.webContents.on('startDragging', (stickerId, rect) => {
try {
let [libraryId, layerId] = stickerId.split(/\./, 2);
let archiveVersion = libraryIndexesById[libraryId].archiveVersion;
this.startDragging(libraryId, archiveVersion, stickerId, rect, this.browserWindow._webview);
} catch (e) {
// TODO: do this everywhere somehow
log(e.message);
log(e);
}
if (UI_MODE == 'cover') {
this.browserWindow.close();
}
});
// add a handler for a call from web content's javascript
this.webContents.on('addLibraryColors', (libraryId) => {
try {
let library = libraryIndexesById[libraryId];
colorUtil.addLibraryColorsToDocument(library.colors, this.context.document);
} catch (e) {
// TODO: do this everywhere somehow
log(e.message);
log(e);
}
})
}
/**
* Triggers the beginning of a drag operation on the given sticker ID
*/
startDragging(libraryId, archiveVersion, stickerId, rect, srcView) {
let library = libraries.getLibraryById(libraryId, {onlyEnabled: true});
let image = NSImage.alloc().initWithContentsOfFile(this.getStickerCachedImagePath(stickerId));
// deserialize layer
let serializedLayerJson = fs.readFileSync(
this.getStickerCachedContentPath(stickerId), {encoding: 'utf8'});
let unarchiveFn = ( // method was renamed in Sketch 64 -- extra 'd')
MSJSONDataUnarchiver.unarchivedObjectWithString_asVersion_corruptionDetected_error ||
MSJSONDataUnarchiver.unarchiveObjectWithString_asVersion_corruptionDetected_error);
let decodedImmutableObj = unarchiveFn(serializedLayerJson, archiveVersion || 999, null, null);
let layer = decodedImmutableObj.newMutableCounterpart();
// create a dummy document and import the layer into it, so that
// foreign symbols can be created in it and sent along with the layer
// to the pasteboard
let dummyDocData = MSDocumentData.alloc().init();
dummyDocData.addBlankPage().addLayer(layer);
// import any symbols and shared styles used in library (either from the library itself or
// other libraries referenced from the library... i.e. nested libraries)
libraries.replaceSymbolsAndSharedStylesInLayerWithLibrary(dummyDocData, layer, library);
// initiate cocoa drag operation
// let pbItem = NSPasteboardItem.new();
// pbItem.setData_forType_(
// image.TIFFRepresentation(),
// NSPasteboardTypePNG);
let dragItem = NSDraggingItem.alloc().initWithPasteboardWriter(image);
// pbItem.release();
dragItem.setDraggingFrame_contents_(
NSMakeRect(rect.x, rect.y, rect.width, rect.height),
image);
let mouse = NSEvent.mouseLocation();
let event = NSEvent.eventWithCGEvent(CGEventCreateMouseEvent(
null,
kCGEventLeftMouseDown,
CGPointMake(
mouse.x - srcView.window().frame().origin.x,
NSHeight(NSScreen.screens().firstObject().frame())
- mouse.y + srcView.window().frame().origin.y),
kCGMouseButtonLeft));
let draggingSession = srcView.beginDraggingSessionWithItems_event_source_(
NSArray.arrayWithObject(dragItem.autorelease()), event, srcView);
draggingSession.setAnimatesToStartingPositionsOnCancelOrFail(false);
draggingSession.setDraggingFormation(NSDraggingFormationNone);
// copy to pasteboard
let dpb = NSPasteboard.pasteboardWithName(NSDragPboard);
dpb.clearContents(); // remove the image version from the pasteboard
try {
let layerWriter = Array.from(NSApp.delegate().pasteboardManager().writers())
.find(x => String(x.className()) === 'MSPasteboardLayersReaderWriter');
if (layerWriter) {
layerWriter.writeData_toPasteboard(
MSPasteboardLayers.pasteboardLayersWithLayers([layer]),
dpb);
}
// TODO: use this simpler method when it's no longer broken (as of Sketch 70.5)
// MSPasteboardManager.writePasteboardLayers_toPasteboard(
// MSPasteboardLayers.pasteboardLayersWithLayers([layer]),
// dpb);
} catch (err) {
if (err.nativeException) {
console.log(err.nativeException.name(), err.nativeException.reason());
console.log(err.nativeException.callStackSymbols());
}
throw err;
}
}
getStickerCachedImagePath(stickerId) {
let [libraryId, layerId] = stickerId.split(/\./, 2);
return path.join(util.getPluginCachePath(), libraryId, layerId + '.png');
}
getStickerCachedContentPath(stickerId) {
let [libraryId, layerId] = stickerId.split(/\./, 2);
return path.join(util.getPluginCachePath(), libraryId, layerId + '.json');
}
}
================================================
FILE: src/util-libraries.js
================================================
/*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as util from './util';
/**
* Returns the MSAssetLibrary / MSUserAssetLibrary with the given library ID
* (which is a UUID)
*/
export function getLibraryById(libraryId, {onlyEnabled = false} = {}) {
return util.arrayFromNSArray(getLibrariesController().libraries())
.filter(lib => onlyEnabled ? !!lib.enabled() : true)
.find(lib => String(lib.libraryID()) == String(libraryId));
}
/**
* Adds the given .sketch file as a library in Sketch.
*/
export function addLibrary(context, librarySketchFilePath) {
getLibrariesController().addAssetLibraryAtURL(NSURL.fileURLWithPath(librarySketchFilePath));
getLibrariesController().notifyLibraryChange(
getLibrariesController().userLibraries().firstObject()); // notify change on any lib
}
/**
* Replaces all symbol instances and shared styles under (and including) the given parent layer with
* those found in the given MSAssetLibrary.
*/
export function replaceSymbolsAndSharedStylesInLayerWithLibrary(
parentDocument, parentLayer, library) {
if (parentLayer.children) {
let maybeImportForeignObjectWithId = objectId => {
// TODO: is this valid/useful?
// let existing = parentDocument.documentData().foreignSymbols()
// .find(fs => String(fs.symbolMaster().symbolID()) == String(symbolId));
// if (existing) {
// return existing;
// }
let objectInLibrary = (
library.document().symbolWithID(objectId) ||
library.document().textStyleWithID(objectId) ||
library.document().layerStyleWithID(objectId));
if (objectInLibrary) {
let foreignObject = objectInLibrary.foreignObject();
if (foreignObject) {
// the shared obj in the target library is a foreign obj from yet
// another library, try to import it from the other library, and if
// unavailable, grab the MSForeignObject and add it to the target
// document directly
let nestedLibrary = getLibraryById(foreignObject.libraryID(), {onlyEnabled: true});
if (nestedLibrary) {
let objectInNestedLibrary = (
nestedLibrary.document().symbolWithID(foreignObject.remoteShareID()) ||
nestedLibrary.document().textStyleWithID(foreignObject.remoteShareID()) ||
nestedLibrary.document().layerStyleWithID(foreignObject.remoteShareID()) ||
objectInLibrary /* worst case, just try to import the object in the outer lib */);
return importObjectFromLibrary(objectInNestedLibrary, nestedLibrary,
parentDocument.documentData());
} else {
if (objectInLibrary instanceof MSSymbolMaster) {
// TODO: investigate what other dependencies we may need to bring in
// when calling addForeignXX() on a foreign object from another doc.
// likely we need to add other foreign objects that this one relies on
parentDocument.documentData().addForeignSymbol(foreignObject);
return foreignObject;
} /*else if (objectInLibrary instanceof MSTextStyle) {
parentDocument.documentData().addForeignTextStyle(foreignObject);
} else if (objectInLibrary instanceof MSLayerStyle) {
parentDocument.documentData().addForeignLayerStyle(foreignObject);
}*/
}
}
// the symbol in the target library is local to the library, import it
// from the library
return importObjectFromLibrary(objectInLibrary, library,
parentDocument.documentData());
}
return null;
};
// Deep import is necessary when importing override symbols that themselves have overrides
// This method returns a mapping from local to foreign ID
let deepImportOverrides = (overridesDict) => {
let localToForeignIdMap = {};
for (let k in overridesDict) {
let foreignObject = maybeImportForeignObjectWithId(overridesDict[k]);
if (foreignObject) {
// swap out the symbol ID that's local to the library for the symbol ID
// for the foreign symbol in the new document linked to the library
localToForeignIdMap[String(overridesDict[k])] = String(foreignObject.localShareID());
}
localToForeignIdMap = Object.assign(
localToForeignIdMap,
deepImportOverrides(overridesDict[k]));
}
return localToForeignIdMap;
};
let allSymbolInstances = util.getAllLayersMatchingPredicate(
parentLayer, NSPredicate.predicateWithFormat('className == %@', 'MSSymbolInstance'));
allSymbolInstances.forEach(symbolInstance => {
let symbolId = symbolInstance.symbolID();
let foreignSymbol = maybeImportForeignObjectWithId(symbolId);
if (foreignSymbol) {
symbolInstance.changeInstanceToSymbol(foreignSymbol.symbolMaster());
replaceSymbolsAndSharedStylesInLayerWithLibrary(
parentDocument, foreignSymbol.symbolMaster(), library);
}
let overrides = util.dictFromNSDict(symbolInstance.overrides());
let localToForeignSharedObjectIdMap = deepImportOverrides(overrides);
symbolInstance.updateOverridesWithObjectIDMap(localToForeignSharedObjectIdMap);
});
let allLayersWithSharedStyle = util.getAllLayersMatchingPredicate(
parentLayer, NSPredicate.predicateWithFormat('sharedStyleID != nil'));
allLayersWithSharedStyle.forEach(layerWithSharedStyle => {
let styleId = layerWithSharedStyle.sharedStyleID();
let foreignSharedStyle = maybeImportForeignObjectWithId(styleId);
if (foreignSharedStyle) {
if (layerWithSharedStyle instanceof MSTextLayer) {
// preserve formatted string value before setting shared style (which resets
// character-level formatting)
let aStr = layerWithSharedStyle.attributedStringValue();
layerWithSharedStyle.setSharedStyle(foreignSharedStyle.localSharedStyle());
layerWithSharedStyle.setAttributedStringValue(aStr);
} else { // inherits MSStyledLayer
let style = layerWithSharedStyle.style().copy();
layerWithSharedStyle.setSharedStyle(foreignSharedStyle.localSharedStyle());
layerWithSharedStyle.setStyle(style);
}
}
});
}
}
/**
* Compatibility layer for importForeignSymbol_fromLibrary_intoDocument,
* removed in Sketch 50.
*
* @param {MSModelObject} libraryObject The object (e.g. symbol master, style) in library to import
* @param {MSAssetLibrary} library The library to import from
* @param {MSDocumentData} parentDocumentData The document data to import into
* @returns {MSForeignObject}
*/
function importObjectFromLibrary(libraryObject, library, parentDocumentData) {
let librariesController = getLibrariesController();
let shareableObjectReference = MSShareableObjectReference.referenceForShareableObject_inLibrary(
libraryObject, library);
return librariesController.importShareableObjectReference_intoDocument(
shareableObjectReference, parentDocumentData);
}
/**
* Returns an MSDocument for the library with the given ID (cached).
* Note: this operation may take a while.
*/
export function docForLibraryId(libraryId) {
docForLibraryId.__cache__ = docForLibraryId.__cache__ || {};
if (!(libraryId in docForLibraryId.__cache__)) {
let library = Array.from(getLibrariesController().libraries())
.find(lib => String(lib.libraryID()) == libraryId);
if (!library) {
return null;
}
docForLibraryId.__cache__[libraryId] = utils.loadDocFromSketchFile(
String(library.locationOnDisk().path()));
}
return docForLibraryId.__cache__[libraryId];
}
/**
* Gets the app instance's MSAssetLibraryController
*/
function getLibrariesController() {
return AppController.sharedInstance().librariesController();
}
================================================
FILE: src/util-progress-reporter.js
================================================
/*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import EventEmitter from '@skpm/events';
export class ProgressReporter extends EventEmitter {
constructor(total = 0) {
super();
this.total_ = total;
this.counter = 0;
this.childReporters = [];
}
get total() {
return this.total_;
}
set total(total) {
this.total_ = total;
this.emitProgress();
}
get progress() {
if (!this.total && !this.childReporters.length) {
return 0;
}
return (this.childReporters.reduce((acc, child) => acc + child.progress, 0) + this.counter) /
(this.total + this.childReporters.length);
}
increment() {
++this.counter;
this.emitProgress();
}
forceProgress(progress) {
if (this.childReporters.length) {
throw new Error('Cannot force progress when there are child reporters');
}
if (!this.total) {
this.total = 1;
}
this.counter = progress * this.total;
this.emitProgress();
}
makeChildren(numChildren) {
let newChildren = Array(numChildren).fill(0).map(a => {
let childReporter = new ProgressReporter();
childReporter.on('progress', () => this.emitProgress());
return childReporter;
});
this.childReporters = this.childReporters.concat(newChildren);
this.emitProgress();
return newChildren;
}
emitProgress() {
this.emit('progress', this.progress);
}
}
================================================
FILE: src/util.js
================================================
/*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import path from '@skpm/path';
/**
* Performs a depth-first traversal of the layer tree, starting
* at the provided root layer.
*/
export function walkLayerTree(rootLayer, visitFunction, {reverse} = {reverse: false}) {
let visit_ = layer => {
// visit this layer
visitFunction(layer);
// visit children
let subLayers;
if ('layers' in layer) {
subLayers = arrayFromNSArray(layer.layers());
} else if ('artboards' in layer) {
subLayers = arrayFromNSArray(layer.artboards());
} else {
return;
}
if (reverse) {
subLayers.reverse();
}
subLayers.forEach(subLayer => visit_(subLayer));
};
visit_(rootLayer);
}
/**
* Converts an NSArray to a JS array
*/
export function arrayFromNSArray(nsArray) {
// TODO: this may no longer be needed... as of recent versions of sketch
// NSArray seems to be array-like. or at least replace with Array.from(nsarray)
let arr = [];
let count = nsArray.count();
for (let i = 0; i < count; i++) {
arr.push(nsArray.objectAtIndex(i));
}
return arr;
}
/**
* Convert an NSDictionary-type object to a JS dict.
* As of Sketch 50.2, this is needed for some cases of symbol instance overrides
*/
export function dictFromNSDict(nsDict) {
let dict = {};
for (let key in nsDict) {
dict[key] = nsDict[key];
}
return dict;
}
/**
* Returns the first layer matching the given NSPredicate
*
* @param {MSDocument|MSLayerGroup} parent The document or layer group to search.
* @param {NSPredicate} predicate Search predicate
*/
export function getAllLayersMatchingPredicate(parent, predicate) {
if (parent instanceof MSDocument) {
// MSDocument
return parent.pages().reduce(
(acc, page) => acc.concat(getAllLayersMatchingPredicate(page, predicate)),
[]);
}
// assume MSLayerGroup
return Array.from(parent.children().filteredArrayUsingPredicate(predicate));
}
/**
* Returns the first layer matching the given NSPredicate
*
* @param {MSDocument|MSLayerGroup} parent The document or layer group to search.
* @param {NSPredicate} predicate Search predicate
*/
export function getFirstLayerMatchingPredicate(parent, predicate) {
if (parent instanceof MSDocument) {
// MSDocument
let results;
for (page of Array.from(parent.pages())) {
let firstInPage = getFirstLayerMatchingPredicate(page, predicate);
if (firstInPage) {
return firstInPage;
}
}
return null;
}
// assume MSLayerGroup
return getAllLayersMatchingPredicate(parent, predicate)[0] || null;
}
/**
* Finds the layer with the given objectID in the given document.
*/
export function getLayerById(document, layerId) {
return getFirstLayerMatchingPredicate(document,
NSPredicate.predicateWithFormat('objectID == %@', layerId));
}
/**
* Copied from @skpm/fs with intermediate directories.
*/
export function mkdirpSync(path, mode) {
mode = mode || 0o777;
let err = MOPointer.alloc().init();
let fileManager = NSFileManager.defaultManager();
fileManager.createDirectoryAtPath_withIntermediateDirectories_attributes_error(path, true, {
NSFilePosixPermissions: mode
}, err);
if (err.value() !== null) {
throw new Error(err.value());
}
}
/**
* Returns an MSDocument for the given .sketch file path. May take
* a long time!
*/
export function loadDocFromSketchFile(filePath) {
let doc = MSDocument.new();
doc.readDocumentFromURL_ofType_error_(
NSURL.fileURLWithPath(filePath),
'com.bohemiancoding.sketch.drawing',
null);
return doc;
}
/**
* Returns an NSImage for the given layer in the given document.
*/
export function getLayerImage(document, layer) {
let tempPath = NSTemporaryDirectory().stringByAppendingPathComponent(
NSUUID.UUID().UUIDString() + '.png');
captureLayerImage(document, layer, tempPath);
return NSImage.alloc().initWithContentsOfFile(tempPath);
}
/**
* Saves the given layer in the given document to a PNG file at the given path.
*/
export function captureLayerImage(document, layer, destPath) {
let air = layer.absoluteInfluenceRect();
let rect = NSMakeRect(air.origin.x, air.origin.y, air.size.width, air.size.height);
let exportRequest = MSExportRequest.exportRequestFromExportFormat_layer_inRect_useIDForName_(
MSExportFormat.formatWithScale_name_fileFormat_(2.0, 'temp.png', 'png'),
layer,
rect, // avoid trimming
true);
if (!(layer instanceof MSArtboardGroup || layer instanceof MSSymbolMaster)) {
exportRequest.includeArtboardBackground = false;
}
// exportRequest.shouldTrim = false;
document.saveArtboardOrSlice_toFile_(exportRequest, destPath);
}
/**
* Converts an NSImage to a data URL string (png).
*/
export function nsImageToDataUri(image) {
let data = image.TIFFRepresentation();
let bitmap = NSBitmapImageRep.imageRepWithData(data);
data = bitmap.representationUsingType_properties_(NSPNGFileType, null);
let base64 = 'data:image/png;base64,' + data.base64EncodedStringWithOptions(0);
return base64;
}
/**
* Returns the system cache path for the plugin.
*/
export function getPluginCachePath() {
let cachePath = String(NSFileManager.defaultManager().URLsForDirectory_inDomains_(
NSCachesDirectory,
NSUserDomainMask)[0].path());
let pluginCacheKey = String(__command.pluginBundle().identifier()); // TODO: escape if needed
return path.join(cachePath, pluginCacheKey);
}
/**
* Deletes the given file or directory recursively (i.e. it and its
* subfolders).
*/
export function rmdirRecursive(path) {
NSFileManager.defaultManager().removeItemAtPath_error_(path, null);
}
/**
* Give the CPU some breathing room.
*/
export function unpeg() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(), 0);
});
}
/**
* Profile the running time of a method
*/
export function _profile(fnOrPromise, tag = '') {
tag = tag ? ` [${tag}]` : '';
let t = Number(new Date());
let finish = () => {
t = Number(new Date()) - t;
log(`profile${tag}: ${t}ms`);
};
if (fnOrPromise instanceof Promise) {
fnOrPromise.then(() => finish());
return fnOrPromise;
} else {
fnOrPromise();
finish();
}
}
/**
* Returns the name of the given document, if it has one.
*
* @param {MSDocument} document
*/
export function getDocumentName(document) {
let fileURL = document.fileURL();
if (fileURL) {
fileURL = String(fileURL.path());
return path.basename(fileURL).replace(/\.[^.]+$/, ''); // strip extension
}
return null;
}
================================================
FILE: web/index.js
================================================
const webpack = require('webpack');
const process = require('process');
module.exports = {
build: () => new Promise((resolve, reject) => {
makeInstance().run((err, stats) => {
printWebpackStats(err, stats);
resolve();
});
}),
watch: (cb) => {
makeInstance().watch({}, (err, stats) => {
printWebpackStats(err, stats);
if (cb) {
cb(err, stats);
}
});
},
};
function makeInstance() {
let oldcwd = process.cwd();
process.chdir(__dirname);
let config = require('./webpack.config.js');
let inst = webpack(config);
process.chdir(oldcwd);
return inst;
}
function printWebpackStats(err, stats) {
if (err) {
console.error(err);
}
if (stats) {
console.log(stats.toString({
modules: false,
colors: true,
}));
}
};
================================================
FILE: web/package.json
================================================
{
"name": "sketch-stickers-web",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start:dev": "webpack-dev-server",
"build": "NODE_ENV=production webpack-cli",
"watch": "NODE_ENV=production webpack-cli --watch"
},
"private": true,
"license": "Apache-2.0",
"devDependencies": {
"css-loader": "^0.28.11",
"extract-loader": "^2.0.1",
"file-loader": "^1.1.11",
"html-loader": "^0.5.5",
"image-webpack-loader": "^4.2.0",
"json-loader": "^0.5.7",
"node-sass": "^5.0.0",
"node-sass-asset-functions": "^0.1.0",
"sass-loader": "^7.0.1",
"svg-sprite-loader": "^4.1.3",
"webpack-cli": "^2.0.14",
"webpack-dev-server": "^3.1.3"
},
"dependencies": {
"event-emitter": "^0.3.5",
"jquery": "^3.3.1",
"vue": "^2.6.12"
}
}
================================================
FILE: web/src/.gitignore
================================================
_stub-sticker-index.json
================================================
FILE: web/src/_stub-sticker-index.json.readme.md
================================================
To make rapid development on the web page easier (outside of Sketch, preview in the brower):
1. Run the plugin with actual stickers in one of your libraries.
2. Grab the relevant `index.json` file from `~/Library/Caches///index.json`.
This is the cached sticker index. That file should look something like:
```
{
"sections": [
...
],
}
```
3. Copy the file into this folder and rename it to `_stub-sticker-index.json`.
4. Wrap the contents in:
```
{
"libraries": [
]
}
```
================================================
FILE: web/src/client.js
================================================
/*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const ee = require('event-emitter');
let __layerImages__ = {};
let __layerImageResolves__ = {};
class StickersClient {
getStickerImageUrl(stickerId) {
return new Promise((resolve, reject) => {
if (__layerImages__[stickerId]) {
resolve(__layerImages__[stickerId]);
} else if (__layerImageResolves__[stickerId]) {
// already sent request to client, just tack on this resolve() fn
__layerImageResolves__[stickerId].push(resolve);
} else {
// no request for this layer sent yet
__layerImageResolves__[stickerId] = [resolve];
pluginCall('requestLayerImageUrl', stickerId, '__onLayerImageAvailable__');
}
});
}
__onLayerImageAvailable__(stickerId, url) {
__layerImages__[stickerId] = url;
(__layerImageResolves__[stickerId] || []).forEach(resolve => resolve(url));
}
init() {
pluginCall('loadStickerIndex', '__onLoadComplete__', '__onLoadProgress__');
}
close() {
pluginCall('close');
}
openUrl(url) {
pluginCall('openUrl', url);
}
startDragging(stickerId, rect) {
pluginCall('startDragging', stickerId, rect);
}
addLibraryColors(libraryId) {
pluginCall('addLibraryColors', libraryId);
}
};
ee(StickersClient.prototype);
let instance = new StickersClient();
window.__onLayerImageAvailable__ = instance.__onLayerImageAvailable__.bind(instance);
window.__onLoadProgress__ = f => {
instance.emit('load-progress', f);
};
window.__onLoadComplete__ = stickerIndex => {
instance.stickerIndex = stickerIndex;
instance.emit('load-progress', 1);
instance.emit('loaded', stickerIndex);
};
module.exports = instance;
================================================
FILE: web/src/components/button/button.scss
================================================
/*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@mixin button($size: small,
$level: secondary,
$color: var(--theme-color-button),
$colorHover: var(--theme-color-button-hover),
$colorActive: var(--theme-color-button-active),
$colorFg: var(--theme-color-button-fg)) {
--color: #{$color};
display: flex;
align-items: center;
color: var(--color);
font-weight: 500;
text-decoration: none;
border-radius: 4px;
border: 0;
cursor: pointer;
outline: 0;
@if $size == small {
@include type-body-3;
padding: 6px 12px;
.svg-icon {
width: 20px;
height: 20px;
}
}
@else if $size == large {
@include type-body-1;
padding: 10px 16px;
}
.svg-icon:first-child:not(:last-child) {
margin-right: 4px;
}
.svg-icon:last-child:not(:first-child) {
margin-left: 4px;
}
@if $level == secondary {
box-shadow: 0 0 0 1px var(--color) inset;
background-color: transparent;
&:hover,
&:focus,
&:active {
color: $colorFg;
background-color: var(--color);
}
&:focus,
&:active {
--color: #{$colorHover};
}
}
@else if $level == flat {
background-color: transparent;
&:hover {
--color: #{$colorHover};
}
&:focus,
&:active {
--color: #{$colorActive};
}
}
@else if $level == primary {
color: $colorFg;
background-color: var(--color);
&:hover {
--color: #{$colorHover};
}
&:focus,
&:active {
--color: #{$colorActive};
}
}
}
================================================
FILE: web/src/components/zerostate/zerostate.scss
================================================
/*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@import '../button/button';
.zero-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 96px 0;
flex: 1 0 auto;
&__text {
@include type-headline-2;
color: var(--theme-color-fg-tertiary);
margin-top: 40px;
max-width: 400px;
text-align: center;
em {
font-style: normal;
font-weight: 500;
color: var(--theme-color-fg-primary);
}
}
&__link {
@include button(large, primary);
margin-top: 24px;
}
}
@mixin zero-state-image($name) {
.zero-state__image {
$src: #{'./images/' + $name + '@2x.png'};
background-image: url($src);
background-size: cover;
background-position: 50% 50%;
width: 100%;
max-width: image-width($src) / 2;
height: image-height($src) / 2;
body[is-dark-theme] & {
$src: #{'./images/' + $name + '-dark@2x.png'};
background-image: url($src);
max-width: image-width($src) / 2;
height: image-height($src) / 2;
}
}
}
================================================
FILE: web/src/index.html
================================================