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 Icon](https://raw.githubusercontent.com/romannurik/Sketch-Stickers/master/assets/icon-menu.png) # 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. ![Screencast of the Stickers plugin](art/Stickers.gif) # 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 ================================================
{{ library.title }}
{{ library.subtitle }}
Library colors added
+{{ library.colors.length - 3 }}
None of your Sketch libraries have stickers yet! Learn more
No stickers or categories matched '{{ $globals.searchText }}'
Indexing libraries…
================================================ FILE: web/src/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. */ // trigger copying of related assets require('file-loader?name=[name].[ext]!./index.html'); // libraries import * as $ from 'jquery'; import Vue from 'vue'; import ElementVisibility from './lib/element-visibility'; import StickersClient from './client'; // load icons const requireAll = r => r.keys().map(r); requireAll(require.context('!svg-sprite-loader!./icons/', false, /.*\.svg$/)) .map(m => m.default) .reduce((acc, icon) => ({ ...acc, [icon.id]: icon }), {}); // consts const MAX_DRAW_WIDTH = 300; const MAX_DRAW_HEIGHT = 400; // page controller class StickersPage { constructor() { this.setupCoreUi(); this.setupStickersUi(); StickersClient.init(); StickersClient.on('load-progress', f => this.vue.indexLoadProgress = f); StickersClient.once('loaded', rawStickerIndex => { this.vue.stickerIndex = this.processRawStickerIndex(rawStickerIndex); this.vue.$nextTick(() => { $('.header-area__search-field').focus(); this.loadVisibleStickers(); }); }); } processRawStickerIndex(stickerIndex) { stickerIndex.libraries = stickerIndex.libraries .filter(lib => !!lib.sections.length); for (let library of stickerIndex.libraries) { for (let section of library.sections) { section.rows = []; let currentRow = null; let newRow = () => { currentRow = {items: []}; section.rows.push(currentRow); }; for (let item of section.items) { if (item.layout == 'row') { newRow(); currentRow.items.push(item); newRow(); } else { if (!currentRow) { newRow(); } currentRow.items.push(item); } } } } return stickerIndex; } setupCoreUi() { $(window).on('focus', () => { $('.header-area__search-field').focus().select(); }); $(document.body).attr('ui-mode', (window.location.search.match(/uiMode=(\w+)/) || [])[1] || 'cover'); if (window.location.search.match(/darkMode=1/)) { $(document.body).attr('is-dark-theme', '1'); } $(document).on('contextmenu', e => e.preventDefault()); $(document).on('click', 'a[href]', ev => { let url = $(ev.target).attr('href'); StickersClient.openUrl(url); ev.preventDefault(); }); var me = this; this.vueGlobal = new Vue({ data: { searchText: '' }, }); Vue.prototype.$globals = this.vueGlobal; function hiliteReplacer_() { return Array.from(arguments).slice(1, -2) .map((s, i) => i % 2 == 0 ? `${s}` : s) .join(''); } Vue.component('hilitext', { template: `
`, props: ['text'], methods: { highlight: (text, query) => { if (!query) { return text; } return String(text || '').replace(this.regexForSearchText(query), hiliteReplacer_); } } }); Vue.component('svg-icon', { template: ``, props: ['glyph'], }); Vue.component('sticker', { props: ['sticker', 'parentSection'], template: '#sticker-template', computed: { drawSize() { return me.calcDrawSize(this.sticker); } }, }); this.vue = new Vue({ el: '.root', data: { indexLoadProgress: 0, stickerIndex: null, }, methods: { addLibraryColors(library) { StickersClient.addLibraryColors(library.id); library.colorsAdded = true; }, closeWindow() { StickersClient.close(); }, onSearchKeydown(ev) { if (ev.keyCode == 27) { if (ev.target.value) { ev.preventDefault(); me.vueGlobal.searchText = ''; me.updateSearch(); } } }, onSearchInput(ev) { $(window).scrollTop(0); me.updateSearch(); }, }, }); } regexForSearchText(query) { return new RegExp((query || '') .replace(/^\s+|\s+$/g, '') .split(/\s+/) .map(s => `(${s})`) .join('(.*?)'), 'ig'); } updateSearch() { // TODO: move this to a watcher in vueGlobal this.vue.$nextTick(() => { const re = this.regexForSearchText(this.vueGlobal.searchText); const findIn = s => this.vueGlobal.searchText ? (s || '').search(re) >= 0 : true; const visitItem = item => { let found = false; if (item.items) { // section for (const subItem of item.items) { if (visitItem(subItem)) { found = true; } } if (findIn(item.title) || findIn(item.description)) { found = true; visitUnhide(item); } } else { // sticker found = findIn(item.name); } item._hide = !found; return found; }; const visitUnhide = item => { if (item.items) { for (const subItem of item.items) { visitUnhide(subItem); } } item._hide = false; }; let anyResults = false; for (const library of this.vue.stickerIndex.libraries) { let foundInLibrary = false; for (const section of library.sections) { let found; for (const row of section.rows) { if (visitItem(row)) { found = true; } } if (findIn(section.title) || findIn(section.description)) { found = true; for (const row of section.rows) { visitUnhide(row); } } section._hide = !found; anyResults = anyResults || found; foundInLibrary = foundInLibrary || found; } library._hide = !foundInLibrary; } this.vue.$forceUpdate(); $(document.body).toggleClass('has-active-search', !!this.vueGlobal.searchText); $(document.body).toggleClass('no-search-results', !anyResults); this.vue.$nextTick(() => { this.loadVisibleStickers(); }); }); } calcDrawSize(sticker) { // fit the sticker into a max width and height, keeping its aspect ratio let size = { width: sticker.width, height: sticker.height }; if (size.width > MAX_DRAW_WIDTH) { size.height = size.height * MAX_DRAW_WIDTH / size.width; size.width = MAX_DRAW_WIDTH; } if (size.height > MAX_DRAW_HEIGHT) { size.width = size.width * MAX_DRAW_HEIGHT / size.height; size.height = MAX_DRAW_HEIGHT; } size.width = Math.max(1, size.width); size.height = Math.max(1, size.height); return size; } setupStickersUi() { $(document).on('mousedown', '.sticker__thumb-container', ev => { let stickerId = $(ev.target).parents('.sticker').attr('data-sticker-id'); let rect = $(ev.target).get(0).getBoundingClientRect(); rect = { x: rect.left, y: rect.top, width: rect.right - rect.left, height: rect.bottom - rect.top }; StickersClient.startDragging(stickerId, rect); }); this.setupStickerImageLoading(); } setupStickerImageLoading() { this.loadVisibleStickers(); $(window).on('DOMContentLoaded load resize', () => this.loadVisibleStickers()); window.addEventListener('scroll', () => this.loadVisibleStickers(), true); // true == capture (all elements) } loadVisibleStickers() { this.fetchedImages = this.fetchedImages || new Set(); $('.sticker').each((index, el) => { let $el = $(el); let stickerId = $el.attr('data-sticker-id'); if ($el.attr('data-loaded')) { return; } if (!ElementVisibility.isElementInViewport(el)) { return; } this.fetchedImages.add(stickerId); StickersClient.getStickerImageUrl(stickerId).then(url => { $el.find('.sticker__thumb').attr('src', url).one('load', () => { $el.attr('data-loaded', true); }); }); }); } } $(window).on('load', () => { new StickersPage(); }); ================================================ FILE: web/src/index.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. */ // some default styles to make the view more native like @import './lib/embedded-ui'; @import './lib/svg-icons'; @import './variables'; @import './components/zerostate/zerostate'; @import './components/button/button'; $headerHeight: 48px; [v-cloak] { display: none !important; } html, body { height: 100%; margin: 0; -webkit-font-smoothing: antialiased; } html { box-sizing: border-box; background: transparent; font-family: $fontStackBody; color: var(--theme-color-fg-secondary); } body { @include theme-light; &[is-dark-theme] { @include theme-dark; } background: var(--theme-color-bg); display: flex; flex-direction: column; --side-margin: 36px; --left-keyline: 316px; --root-section-vert-padding: 40px; &[ui-mode="palette"] { @include medium { --side-margin: 20px; --left-keyline: 256px; } } } .root { display: flex; flex-direction: column; height: 100%; } .header-area { position: fixed; left: 0; top: 0; right: 0; height: $headerHeight; padding: 0 var(--side-margin); display: grid; align-items: center; z-index: 10; box-shadow: 0 1px 0 var(--theme-color-thin-border); background-color: var(--theme-color-bg-floating-header); -webkit-backdrop-filter: blur(12px); grid-template-columns: calc(var(--left-keyline) - var(--side-margin)) 1fr; [ui-mode="palette"] & { grid-template-columns: 1fr; } &__back-button { [ui-mode="palette"] & { display: none; } color: var(--theme-color-fg-tertiary); display: flex; align-items: center; justify-self: flex-start; margin: 0 0 0 -20px; padding: 0; -webkit-appearance: none; border: 0; background-color: transparent; outline: none; @include type-body-1; .svg-icon { width: 16px; height: 16px; margin-left: -4px; margin-right: 8px; } &:hover, &:focus { color: var(--theme-color-fg-primary); } } &__search-field-container { position: relative; height: 32px; justify-self: flex-start; width: 100%; max-width: 320px; margin-right: var(--side-margin); [ui-mode="palette"] & { justify-self: stretch; } .svg-icon { color: var(--theme-color-fg-secondary); position: absolute; left: 12px; top: 50%; transform: translateY(-50%); pointer-events: none; } } &__search-field { position: absolute; left: 0; top: 0; width: 100%; height: 100%; border: 0; border-radius: 4px; background-color: var(--theme-color-search); color: var(--theme-color-fg-primary); -webkit-appearance: none; padding: 0 0 0 40px; box-sizing: border-box; @include type-body-1; &:focus { background-color: var(--theme-color-search-active); outline: 0; } &::placeholder { color: var(--theme-color-fg-secondary); } } } .stickers-area { flex: 1 1 auto; display: flex; flex-direction: column; padding-top: $headerHeight; } .sticker-library-header { padding: 16px var(--side-margin); background-color: rgba(#000, .04); border-bottom: 1px solid var(--theme-color-thin-border); display: flex; align-items: center; &__title-lockup { display: flex; flex-direction: column; flex: 1; } &__icon { // box-shadow: 0 0 0 1px rgba(#000, .12) inset; background-size: cover; border-radius: 4px; width: 48px; height: 48px; margin-right: 8px; } &__title { @include type-headline-1; font-weight: 500; color: var(--theme-color-fg-secondary); } &__subtitle { @include type-body-3; color: var(--theme-color-fg-secondary); } &__colors-area { display: flex; flex-direction: row; align-items: center; margin: -8px 0; } &__colors-added { display: flex; flex-direction: row; align-items: center; @include type-body-3; color: var(--theme-color-fg-tertiary); .svg-icon { width: 16px; height: 16px; margin-right: 4px; } } &__add-colors { @include button(small, flat); --color: var(--theme-color-fg-primary); } &__colors-preview { display: flex; flex-direction: row; } &__color { width: 20px; height: 20px; border-radius: 4px; margin-left: 4px; box-shadow: 0 0 0 1px rgba(#000, .12) inset; } &__color-more { @include type-body-3; color: var(--theme-color-fg-secondary); display: flex; align-items: center; padding: 0 4px; width: auto; } } .sticker-root-section { position: relative; $scrollFadeSize: 60px; display: flex; align-items: stretch; flex-shrink: 0; padding: var(--root-section-vert-padding) 0 0 0; border-bottom: 1px solid var(--theme-color-thin-border); @include narrow { flex-direction: column; } // gradient fade for scrolled portions of the content area &::after { content: ''; position: absolute; left: calc(var(--left-keyline) - #{$scrollFadeSize}); top: 1px; bottom: 1px; width: $scrollFadeSize; background-image: var(--theme-gradient-fade-to-bg); @include narrow { display: none; } } &__meta { z-index: 1; align-self: flex-start; position: sticky; position: -webkit-sticky; top: calc(var(--root-section-vert-padding) + #{$headerHeight}); @include narrow { position: relative; top: unset; } box-sizing: border-box; display: flex; flex: 0 0 auto; flex-direction: column; width: var(--left-keyline); padding: 0 40px var(--root-section-vert-padding) var(--side-margin); } &__overline { @include type-body-4; color: var(--theme-color-fg-tertiary); white-space: nowrap; text-overflow: ellipsis; overflow: hidden; } &__title { @include type-headline-1; font-weight: 800; color: var(--theme-color-fg-primary); } &__description { @include type-body-2; margin-top: 16px; color: var(--theme-color-fg-secondary); } &__link { @include button; align-self: flex-start; margin-top: 8px; } &__content { display: flex; flex-direction: column; flex: 1 1 auto; min-width: 0; } &__content-row { padding: 12px var(--side-margin) var(--root-section-vert-padding) (#{$scrollFadeSize}); // space for box-shadows and gradient margin: -12px 0 0 (-$scrollFadeSize); // offset for box shadow @include narrow { padding-left: var(--side-margin); margin-left: 0; } overflow-x: auto; align-self: stretch; display: flex; flex-direction: row; > * { margin-right: 20px; // force a right-margin &:last-child { position: relative; &::after { content: ''; position: absolute; right: calc(-1 * var(--side-margin)); // the margin width: 1px; height: 20px; } } } } &[layout="flow"] .sticker-root-section__content-row { flex-flow: row wrap; .sticker { margin-bottom: 24px; } } } @mixin sticker-effects { box-shadow: 0 0 0 1px var(--theme-color-thin-border) inset; } @mixin sticker-no-effects { box-shadow: none !important; } // a column of stickers .sticker-sub-section { display: flex; flex-direction: column; margin-right: 48px; &__title { @include type-body-1; margin-bottom: 16px; color: var(--theme-color-fg-primary); font-weight: 500; } .sticker + .sticker { margin-top: 12px; } &__content.has-background-color { @include sticker-effects; padding: 24px; } &__content.is-hide-names { .sticker__caption { display: none; } } &[layout="row"] &__content { display: flex; flex-direction: row; .sticker + .sticker { margin-top: 0; margin-left: 20px; } } } .sticker { display: flex; flex-direction: column; &:not([data-loaded]) &__thumb-container { background-color: var(--theme-color-bg-level-2); } &:not([data-loaded]) &__thumb { opacity: 0; } &__thumb-container { --hit-area-padding: 4px; margin: calc(0px - var(--hit-area-padding)); padding: var(--hit-area-padding); cursor: pointer; display: flex; background-color: transparent; transition: background-color .1s ease; &:hover .sticker__thumb { //transform: scale(1.03); opacity: .85; transform: translateY(-2px); } } &__thumb { // @include sticker-effects; object-fit: contain; background-color: transparent; transition: transform .1s ease, opacity .1s ease; opacity: 1; } &__caption { margin-top: 4px; @include type-body-3; color: var(--theme-color-fg-tertiary); } &.has-background-color { .sticker__thumb-container { @include sticker-effects; padding: calc(var(--hit-area-padding) + 24px); } .sticker__caption { margin-top: 8px; margin-bottom: 12px; } } } .no-stickers { @include zero-state-image('zero-state'); } .search-empty { display: none; .no-search-results & { display: flex; } @include zero-state-image('no-results'); } body.has-active-search [data-search-match="none"] { display: none; } body.has-active-search [data-search-match="direct"] [data-search-match="none"] { display: flex; } body.has-active-search [data-search-match="direct"] > .sticker__caption { display: unset; } .search-highlight { background-color: var(--theme-color-search-highlight); border-radius: 4px; } .page-loading { display: flex; animation: page-load-appear .7s ease .2s; animation-fill-mode: backwards; @keyframes page-load-appear { from { opacity: 0; } to { opacity: 1; } } @include zero-state-image('indexing'); $progressThickness: 4px; &__progressbar { position: relative; margin-top: 40px; height: $progressThickness; width: 160px; // border-radius: 1000px; // during transition, this isn't applied... so just kill it for now background-color: var(--theme-color-bg-level-3); // overflow: hidden; } &__progress { position: absolute; left: 0; top: 0; width: calc(100% - #{$progressThickness} * 2); height: 100%; background-color: var(--theme-color-accent); transform-origin: 0% 0%; transform: scaleX(0); transition: transform .5s cubic-bezier(.25, .25, 0, 1); } } ================================================ FILE: web/src/lib/element-visibility.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 jQuery from 'jquery'; export default { /** * Test if the given element is in th current viewport. * https://stackoverflow.com/a/7557433 */ isElementInViewport(el) { if (el instanceof jQuery) { el = el.get(0); } const rect = el.getBoundingClientRect(); return ( rect.bottom >= 0 && rect.right >= 0 && rect.top <= jQuery(window).height() && rect.left <= jQuery(window).width()); } }; ================================================ FILE: web/src/lib/embedded-ui.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. */ *, *::before, *::after { -webkit-user-select: none; user-select: none; } input, textarea { -webkit-user-select: auto; user-select: auto; } html { cursor: default; } ================================================ FILE: web/src/lib/svg-icons.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. */ // defaults .svg-icon { width: 24px; height: 24px; fill: currentColor; } ================================================ FILE: web/src/plugin-call-stub.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. */ // This is a stub client used during development. const STUB_STICKER_INDEX = require('./_stub-sticker-index.json'); const ACTIONS = { close() { }, startDragging(id, rect) { }, addLibraryColors(libraryId) { }, requestLayerImageUrl(stickerId, callbackName) { let sticker = __getStickerById(stickerId); let canvas = document.createElement('canvas'); canvas.width = sticker.width * 2; canvas.height = sticker.height * 2; let ctx = canvas.getContext('2d'); ctx.scale(2, 2); ctx.fillStyle = '#3F51B5'; ctx.fillRect(0, 0, sticker.width, sticker.height); ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.font = Math.ceil(Math.max(13, Math.min(sticker.width, sticker.height) / 10)) + 'px Menlo'; ctx.fillStyle = 'rgba(255,255,255,.6)'; ctx.fillText(`${sticker.width}x${sticker.height}`, sticker.width / 2, sticker.height / 2); let url = canvas.toDataURL(); // let subPath = sticker.imagePath.replace(/.*net.nurik.roman.sketch.stickers/, ''); // let url = '/real-sticker-cache/' + subPath; window[callbackName](stickerId, url); }, loadStickerIndex(callbackName, progressCallbackName) { // window[progressCallbackName](0); // setTimeout(() => window[progressCallbackName](.3), 100); // setTimeout(() => window[progressCallbackName](.5), 300); // setTimeout(() => window[progressCallbackName](.9), 1000); // setTimeout(() => window[callbackName](STUB_STICKER_INDEX), 1500); setTimeout(() => window[callbackName](STUB_STICKER_INDEX), 0); }, }; window['pluginCall'] = function pluginCall(action, ...args) { console.log(`pluginCall: ${action} with args ${JSON.stringify(args)}`); ACTIONS[action].apply(null, args); }; function __getStickerById(id) { let foundSticker = null; let findInSection = section => { (section.items || []).forEach(item => { if (item.type == 'layer' && item.id == id) { foundSticker = item; } else if (item.type == 'section') { findInSection(item); } }); }; for (let library of STUB_STICKER_INDEX.libraries) { for (let section of library.sections) { findInSection(section); } } return foundSticker; } ================================================ FILE: web/src/variables.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. */ $fontStackBody: -apple-system, BlinkMacSystemFont; @function make-soft-gradient-color-to-transparent($color) { @return linear-gradient(to right, rgba($color, 1.00) 0%, rgba($color, 0.90) 30%, rgba($color, 0.67) 60%, rgba($color, 0.50) 75%, rgba($color, 0.33) 85%, rgba($color, 0.00) 100%); } @mixin theme-light { $__bg: #fff; $__accent: #3D5AFE; --theme-color-bg: #{$__bg}; --theme-color-bg-level-2: #{darken($__bg, 4%)}; --theme-color-bg-level-3: #{darken($__bg, 10%)}; --theme-color-bg-floating-header: #{rgba($__bg, .85)}; --theme-color-fg-primary: #{rgba(#000, .87)}; --theme-color-fg-secondary: #{rgba(#000, .54)}; --theme-color-fg-tertiary: #{rgba(#000, .38)}; --theme-color-thin-border: #{rgba(#000, .12)}; --theme-color-accent: #{$__accent}; --theme-color-button: #{$__accent}; --theme-color-button-hover: #{darken($__accent, 10%)}; --theme-color-button-active: #{darken($__accent, 20%)}; --theme-color-button-fg: #fff; --theme-color-search: #{rgba(#000, .12)}; --theme-color-search-active: #{rgba(#000, .24)}; --theme-color-search-highlight: #FBBC04; --theme-gradient-fade-to-bg: #{make-soft-gradient-color-to-transparent($__bg)}; } @mixin theme-dark { $__bg: #202124; $__accent: #536DFE; --theme-color-bg: #{$__bg}; --theme-color-bg-level-2: #{lighten($__bg, 6%)}; --theme-color-bg-level-3: #{lighten($__bg, 10%)}; --theme-color-bg-floating-header: #{rgba($__bg, .75)}; --theme-color-fg-primary: #fff; --theme-color-fg-secondary: #{rgba(#fff, .7)}; --theme-color-fg-tertiary: #{rgba(#fff, .5)}; --theme-color-thin-border: #{rgba(#fff, .2)}; --theme-color-accent: #{$__accent}; --theme-color-button: #{lighten($__accent, 10%)}; --theme-color-button-hover: #{lighten($__accent, 15%)}; --theme-color-button-active: #{lighten($__accent, 20%)}; --theme-color-button-fg: #000; --theme-color-search: #{rgba(#fff, .2)}; --theme-color-search-active: #{rgba(#fff, .3)}; --theme-color-search-highlight: #F29900;//#EA8600; --theme-gradient-fade-to-bg: #{make-soft-gradient-color-to-transparent($__bg)}; } @mixin narrow { @media only screen and (max-width: 440px) { @content; } } @mixin medium { @media only screen and (max-width: 800px) { @content; } } @mixin type-headline-1 { font-size: 20px; line-height: 28px; } @mixin type-headline-2 { font-size: 16px; line-height: 24px; } @mixin type-body-1 { font-size: 14px; line-height: 20px; } @mixin type-body-2 { font-size: 13px; line-height: 20px; } @mixin type-body-3 { font-size: 12px; line-height: 16px; } @mixin type-body-4 { font-size: 10px; line-height: 16px; } ================================================ FILE: web/webpack.config.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 path = require('path'); const sassAssetFunctions = require('node-sass-asset-functions'); const express = require('express'); const os = require('os'); module.exports = { mode: process.env.NODE_ENV || 'development', devServer: { contentBase: path.join(__dirname, '../web-dist'), compress: true, port: 9000, watchContentBase: true, before(app) { app.use('/real-sticker-cache', express.static(path.join( os.homedir(), 'Library/Caches/net.nurik.roman.sketch.stickers/'))); } }, entry: { 'plugin-call': [ './src/plugin-call-stub.js', ], 'index': [ './src/index.js', 'webpack-dev-server/client?http://localhost:9080/' ], }, output: { filename: '[name].js', path: path.resolve(__dirname, '../web-dist') }, resolve: { alias: { // use full (compiler + runtime) version of vue vue: 'vue/dist/vue.js' } }, performance: { hints: false }, node: { // https://sketchplugins.com/d/2188-webpacks-bundled-code-trigger-throw-new-errormissing-action-name/2 setImmediate: false }, module: { rules: [ { test: /\.(html)$/, use: [ { loader: 'extract-loader', }, { loader: 'html-loader', options: { attrs: [ 'img:src', 'link:href' ], interpolate: true, minimize: 'production' === process.env.NODE_ENV, }, }, ] }, { test: /\.(scss)$/, use: [ { loader: 'file-loader', options: { name: '[name].css' } }, { loader: 'extract-loader', }, { loader: 'css-loader', options: { minimize: 'production' === process.env.NODE_ENV, }, }, { loader: 'sass-loader', options: { functions: sassAssetFunctions({ images_path: path.join(__dirname, 'src'), }), }, }, ] }, { test: /\.(png|svg)$/, use: [ { loader: 'file-loader', options: { name: '[name].[ext]' } }, { loader: 'image-webpack-loader', } ] }, { test: /\.(woff2)$/, use: [ { loader: 'file-loader', options: { name: '[name].[ext]' } }, ] }, ], } };