├── .gitignore ├── LICENSE ├── README.md ├── _ ├── backups │ ├── Avatar Library by Drawer.sketch │ ├── test-library.sketch │ └── wm-gdp-library.sketch └── test │ ├── Avatar Library by Drawer.sketch │ ├── test-library.sketch │ └── wm-gdp-library.sketch ├── appcast.xml ├── art ├── add-custom-stickers.png ├── add-documentation.mp4 ├── add-stickers.png ├── clear-symbol-index.png ├── define-categories.png ├── endless-dropdowns.mp4 ├── layout-altered.png ├── layout-combined.png ├── layout-default.png ├── search-in-symbol-browser.mp4 ├── symbol-browser-features.gif ├── symbol-browser-features.mp4 ├── symbol-browser-logo.png ├── symbol-browser-post-thumbnail.png ├── tag-stickers-and-symbols.png └── understand-layout.png ├── assets ├── icon-menu.png ├── logo-dark.svg ├── logo-light.svg ├── newbg.png ├── plugin-call.js ├── sketch-file-outlined.svg ├── sketch-file.svg ├── symbol-browser.png └── user.config ├── examples └── Example Sketch Library.sketch ├── package-lock.json ├── package.json ├── skpm-build-with-child.js ├── src ├── color-util.js ├── commands.js ├── handler.js ├── manifest.json ├── sticker-index.js ├── stickers-ui.js ├── util-libraries.js ├── util-progress-reporter.js └── util.js ├── symbol-browser.sketchplugin.zip ├── symbol-browser.sketchplugin └── Contents │ ├── Resources │ ├── icon-menu.png │ ├── index.html │ ├── index.js │ ├── logo-dark.svg │ ├── logo-light.svg │ ├── newbg.png │ ├── plugin-call.js │ ├── plugin-call.js.map │ ├── sketch-file-outlined.svg │ ├── sketch-file.svg │ ├── symbol-browser.png │ └── user.config │ └── Sketch │ ├── commands.js │ ├── commands.js.map │ ├── handler.js │ ├── handler.js.map │ └── manifest.json └── web ├── index.js ├── package-lock.json ├── package.json ├── src ├── .gitignore ├── _stub-sticker-index.json.readme.md ├── client.js ├── components │ ├── button │ │ └── button.scss │ └── zerostate │ │ └── zerostate.scss ├── icons │ ├── add_circle_outline.svg │ ├── arrow_back_ios.svg │ ├── check.svg │ └── search.svg ├── index.html ├── index.js ├── lib │ ├── element-visibility.js │ ├── embedded-ui.scss │ └── svg-icons.scss ├── plugin-call-stub.js └── variables.scss └── webpack.config.js /.gitignore: -------------------------------------------------------------------------------- 1 | # build artifacts 2 | web-dist 3 | _sandbox 4 | 5 | # npm 6 | node_modules 7 | .npm 8 | npm-debug.log 9 | 10 | 11 | # mac 12 | .DS_Store 13 | 14 | # WebStorm 15 | .idea 16 | _ 17 | _/test/wm-gdp-library.sketch 18 | _/backups/Avatar Library by Drawer.sketch -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Pratik Shah 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Sketch Symbol Browser 3 | 4 | Sketch Symbol Browser 5 | 6 | Better way to browse your symbols. Make the most of your Design System by bringing symbols and UI Sticker sheet together. 7 |
8 | 9 | This plugin lets you.. 10 | - Browse Symbols from multiple Libraries (All in one place) 11 | - True-to-size symbol preview 12 | - Drag-N-Drop Symbols and UI Kit / Stickers 13 | - Add documentation to your Sketch Library 14 | - `New` Share instances of the Symbol 15 | - `New` Works offline 16 | 17 | Visit plugin website for more: http://symbol-browser.pratikshah.website 18 |

19 | 20 | 21 | [![GitHub Release](https://img.shields.io/github/release/pratikjshah/symbol-browser.svg?style=popout)]() 22 | [![Github All Releases](https://img.shields.io/github/downloads/pratikjshah/symbol-browser/total.svg?style=popout)]() 23 | [![GitHub License](https://img.shields.io/github/license/pratikjshah/symbol-browser.svg?style=popout)]() 24 | 25 | 26 | ## Installation Guide 27 | - [⬇️Download](https://github.com/pratikjshah/symbol-browser/releases/latest/download/symbol-browser.sketchplugin.zip) the latest release of the plugin 28 | - Un-zip 29 | - Double-click on the `symbol-browser.sketchplugin` 30 | 31 |
32 | 33 | #### Important links: 34 | * 🚀 [Release Notes](http://symbol-browser.pratikshah.website/#features) 35 | * 👨‍🔬 [Example Sketch library](https://www.sketch.com/s/f577ec9e-127a-4c5a-bd26-22ba9ddb64f5) 36 | 37 | 38 | #### Wiki Pages: 39 | * [Getting started with Symbols Browser](https://github.com/pratikjshah/symbol-browser/wiki/Getting-started-with-Symbols-Browser) 40 | * [Create custom sections for Symbols](https://github.com/pratikjshah/symbol-browser/wiki/Create-custom-sections-for-Symbols) 41 | * [Understanding Metadata syntax](https://github.com/pratikjshah/symbol-browser/wiki/Understanding-Metadata-syntax) 42 | * [Sample Metadata code](https://github.com/pratikjshah/symbol-browser/wiki/Understanding-Metadata-syntax) 43 | 44 |
45 | 46 | ## See it in action 47 | Symbol Browser Features image 48 | 49 |
50 | 51 | ## FAQ 52 | 53 |
54 |

55 | 56 | Example Sketch Library 57 | 58 | | 59 | 60 | Getting Started with Symbol Browser 61 | 62 | | 63 | 64 | Create custom Symbol groups 65 | 66 |

67 |
68 | 69 |
70 | 71 |
What is a Sticker? 72 |

73 | 74 | A sticker is nothing but a specially tagged layer item. 75 | 76 | This can be shape/text layer, group, artboard or even symbol instance. You can use Sticker as a component of your UI Kit which you repeatedly use and want to save time re-creating it. 77 | 78 | Check a syntax [cheatsheet for Stickers](https://github.com/pratikjshah/symbol-browser/wiki/Getting-started-with-Symbols-Browser#steps-to-get-started) to explore what all you can do! 79 | 80 |

81 |
82 | 83 |
How do I add my custom stickers? 84 |

85 | 86 | To add any layer as your Sticker, you just have to "specially" tag it. Take look at below image to see how you can tag an artboard, symbol instances and any layer or group. 87 | 88 | Sketch Symbol Browser 89 | 90 | This tagging is a **suffix** which looks like this 91 | 92 |


 93 | To tag a layer with Main Category
 94 | Layer_Name @MyStickers
 95 | 
 96 | OR
 97 | 
 98 | To tag a layer under Sub Category
 99 | Layer_Name @MyStickers.InfoCards
100 | 
101 | 
102 | You can tag multiple layers with the same category.
103 | 
104 | 
105 | 106 | 107 | *Note: Here MyStickers and InfoCards are the defined categories.* 108 | 109 | Know more about *"How to define categories?"* in next question. 110 | 111 |

112 |
113 | 114 |
How to define Sticker categories? 115 |

116 | 117 | Sticker categories are the logical sections you create to better distribute and logically group Stickers. 118 | You can currently have 2 levels of category. 119 | 120 | Sketch Symbol Browser 121 | 122 | ```yaml 123 | #To define Parent Category 124 | 125 | !StickerSection @Section1 # categoryId 126 | title: My Stickers # Optional, if not provided uses categoryId, provides readable name 127 | description: 'A description' # Optional, Supports basic HTML tags 128 | 129 | ``` 130 | 131 | ```yaml 132 | #To define Sub Category 133 | 134 | !StickerSection @Section1.SubSection # append subCatId to categoryId with . 135 | title: Info Cards # Optional, if not provided uses SubCatId 136 | description: 'A description' # Optional, Supports basic HTML tags 137 | 138 | ``` 139 | 140 | Check out Cheatsheet for Stickers for more details. 141 | 142 |

143 |
144 | 145 |
Why is it taking so long for indexing? 146 |

147 | 148 | Time required to index your Sketch Library is directly proportional to the size and number of symbols it has. But don't worry! This is a one time activity. 149 | 150 | *If you have suggestions on how can this be optimized, feel free to raise a pull request.* 151 | 152 |

153 |
154 | 155 |
My Library symbol update is not reflecting in Symbol Browser! 156 |

157 | 158 | The plugin checks for the Sketch Library modification time and keeps indexing the change when you Open a new document or add a new Sketch Library. 159 | 160 | But in case you want to *force plugin to index again*, you can go to plugin menu and click `🧹 Clear Symbol Index` to remove cached symbols. So after this when you one the Symbol Browser, it will re-index Sketch Libraries. 161 | 162 | ![🧹 Clear Symbol Index](https://github.com/pratikjshah/symbol-browser/blob/master/art/clear-symbol-index.png?raw=true "🧹 Clear Symbol Index") 163 | 164 |

165 |
166 | 167 |
How is this plugin different from 'Stickers'? 168 |

169 | 170 | **Symbol Browser** is a forked version of Roman Nurik's [Sticker](https://github.com/romannurik/Sketch-Stickers) project. 171 | The goal of this sketch plugin is to provide additional features such as showing Sketch Library symbols along with the Stickers you have tagged. 172 | 173 |

174 |
175 | 176 |

177 | 178 | 179 | 180 | #### Contributing 181 | 182 | Lots of room for improvement, let's build it together. Report an [`issue`](https://github.com/pratikjshah/symbol-browser/issues) or request for an exciting [`feature`](https://github.com/pratikjshah/symbol-browser/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22). 183 | 184 | #### Credits and Acknowledgement 185 | 186 | - Sketch [Developers API](https://developer.sketch.com/reference/api/) 187 | - Roman Nurik for [Stickers](https://github.com/romannurik/Sketch-Stickers) 188 | 189 |
190 | 191 | 192 | ## About Author 193 | 194 | Symbol Browser is developed by [Pratik Shah](http://pratikshah.website). 195 | -------------------------------------------------------------------------------- /_/backups/Avatar Library by Drawer.sketch: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/_/backups/Avatar Library by Drawer.sketch -------------------------------------------------------------------------------- /_/backups/test-library.sketch: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/_/backups/test-library.sketch -------------------------------------------------------------------------------- /_/backups/wm-gdp-library.sketch: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/_/backups/wm-gdp-library.sketch -------------------------------------------------------------------------------- /_/test/Avatar Library by Drawer.sketch: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/_/test/Avatar Library by Drawer.sketch -------------------------------------------------------------------------------- /_/test/test-library.sketch: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/_/test/test-library.sketch -------------------------------------------------------------------------------- /_/test/wm-gdp-library.sketch: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/_/test/wm-gdp-library.sketch -------------------------------------------------------------------------------- /appcast.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 🔄 Symbol Browser 5 | https://raw.githubusercontent.com/pratikjshah/symbol-browser/master/appcast.xml 6 | Better way to browse your Design System and UI Sticker sheet 7 | en 8 | 9 | v3.5.2 10 | 11 | Fix for Sketch 66 13 | ]]> 14 | 15 | Thu, 21 May 2020 2:54:24 GMT 16 | 20 | 21 | 22 | v3.5.1 23 | 24 | Major Update 26 | ]]> 27 | 28 | Tue, 5 May 2020 20:54:24 GMT 29 | 33 | 34 | 35 | v2.1.1 36 | 37 | Initial Build 39 | ]]> 40 | 41 | Mon, 10 Jun 2019 20:54:24 GMT 42 | 46 | 47 | 48 | v2.1.0 49 | 50 | Initial Build 52 | ]]> 53 | 54 | Sat, 25 May 2019 18:54:24 GMT 55 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /art/add-custom-stickers.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/art/add-custom-stickers.png -------------------------------------------------------------------------------- /art/add-documentation.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/art/add-documentation.mp4 -------------------------------------------------------------------------------- /art/add-stickers.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/art/add-stickers.png -------------------------------------------------------------------------------- /art/clear-symbol-index.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/art/clear-symbol-index.png -------------------------------------------------------------------------------- /art/define-categories.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/art/define-categories.png -------------------------------------------------------------------------------- /art/endless-dropdowns.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/art/endless-dropdowns.mp4 -------------------------------------------------------------------------------- /art/layout-altered.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/art/layout-altered.png -------------------------------------------------------------------------------- /art/layout-combined.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/art/layout-combined.png -------------------------------------------------------------------------------- /art/layout-default.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/art/layout-default.png -------------------------------------------------------------------------------- /art/search-in-symbol-browser.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/art/search-in-symbol-browser.mp4 -------------------------------------------------------------------------------- /art/symbol-browser-features.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/art/symbol-browser-features.gif -------------------------------------------------------------------------------- /art/symbol-browser-features.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/art/symbol-browser-features.mp4 -------------------------------------------------------------------------------- /art/symbol-browser-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/art/symbol-browser-logo.png -------------------------------------------------------------------------------- /art/symbol-browser-post-thumbnail.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/art/symbol-browser-post-thumbnail.png -------------------------------------------------------------------------------- /art/tag-stickers-and-symbols.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/art/tag-stickers-and-symbols.png -------------------------------------------------------------------------------- /art/understand-layout.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/art/understand-layout.png -------------------------------------------------------------------------------- /assets/icon-menu.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/assets/icon-menu.png -------------------------------------------------------------------------------- /assets/logo-dark.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/logo-light.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/newbg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/assets/newbg.png -------------------------------------------------------------------------------- /assets/plugin-call.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import pluginCall from 'sketch-module-web-view/client'; 18 | window['pluginCall'] = pluginCall; 19 | -------------------------------------------------------------------------------- /assets/sketch-file-outlined.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/sketch-file.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/symbol-browser.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/assets/symbol-browser.png -------------------------------------------------------------------------------- /assets/user.config: -------------------------------------------------------------------------------- 1 | {"localUpdateTime":1549004646054,"localVersion":"2.1.1","isUpdateAvailable":false,"name":"Symbol Browser"} -------------------------------------------------------------------------------- /examples/Example Sketch Library.sketch: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/examples/Example Sketch Library.sketch -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "symbol-browser", 3 | "description": "Better way to browse your Design System and UI Sticker sheet", 4 | "version": "3.5.1", 5 | "engines": { 6 | "sketch": ">=54.0" 7 | }, 8 | "skpm": { 9 | "name": "🔄 Symbol Browser", 10 | "manifest": "src/manifest.json", 11 | "main": "symbol-browser.sketchplugin", 12 | "assets": [ 13 | "assets/**/*", 14 | "!assets/**/*.js", 15 | "web-dist/**/*", 16 | "!web-dist/plugin-call.js" 17 | ] 18 | }, 19 | "scripts": { 20 | "build": "./skpm-build-with-child.js web", 21 | "watch": "./skpm-build-with-child.js web --watch", 22 | "postinstall": "npm run build && skpm-link" 23 | }, 24 | "resources": [ 25 | "assets/**/*.js" 26 | ], 27 | "repository": { 28 | "type": "git", 29 | "url": "https://github.com/pratikjshah/symbol-browser.git" 30 | }, 31 | "license": "Apache-2.0", 32 | "bugs": { 33 | "url": "https://github.com/pratikjshah/symbol-browser/issues" 34 | }, 35 | "homepage": "https://github.com/pratikjshah/symbol-browser#readme", 36 | "author": "Pratik Shah ", 37 | "dependencies": { 38 | "@skpm/events": "^0.2.0", 39 | "@skpm/fs": "^0.2.4", 40 | "@skpm/path": "^0.1.4", 41 | "@skpm/timers": "^0.2.0", 42 | "babel-code-frame": "^6.26.0", 43 | "babel-polyfill": "^6.26.0", 44 | "css-loader": "^2.1.1", 45 | "event-emitter": "^0.3.5", 46 | "express": "^4.16.4", 47 | "extract-loader": "^3.1.0", 48 | "html-loader": "^0.5.5", 49 | "image-webpack-loader": "^4.6.0", 50 | "jquery": "^3.4.0", 51 | "js-yaml": "^3.13.1", 52 | "json-loader": "^0.5.7", 53 | "mocha-js-delegate": "^0.2.0", 54 | "node-sass": "^4.12.0", 55 | "node-sass-asset-functions": "^0.1.0", 56 | "resolve-url-loader": "^3.1.0", 57 | "sass-loader": "^7.1.0", 58 | "sketch-module-web-view": "git://github.com/pratikjshah/sketch-module-wk-web-view.git", 59 | "svg-sprite-loader": "^4.1.6", 60 | "vue": "^2.6.10", 61 | "webpack-cli": "^3.3.1", 62 | "webpack-dev-server": "^3.3.1" 63 | }, 64 | "devDependencies": { 65 | "@skpm/builder": "^0.6.0", 66 | "file-loader": "^3.0.1" 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /skpm-build-with-child.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | const {spawn} = require('child_process'); 3 | const process = require('process'); 4 | 5 | run(); 6 | 7 | async function run() { 8 | let watchMode = process.argv.includes('--watch'); 9 | const web = require('./web'); 10 | 11 | if (!watchMode) { 12 | await web.build(); 13 | await skpmBuild(); 14 | } else { 15 | let firstRun = true; 16 | // watch changes to the web app 17 | web.watch((err, stats) => { 18 | skpmBuild(firstRun ? ['--watch'] : []); 19 | firstRun = false; 20 | }); 21 | } 22 | } 23 | 24 | 25 | function skpmBuild(args) { 26 | return new Promise((resolve, reject) => { 27 | const skpmBuild = spawn('skpm-build', args); 28 | skpmBuild.stdout.pipe(process.stdout); 29 | skpmBuild.stderr.pipe(process.stderr); 30 | skpmBuild.on('close', (code) => resolve()); 31 | }); 32 | } 33 | -------------------------------------------------------------------------------- /src/color-util.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Returns true if every color in the array of SVG colors is already 3 | * in the document. 4 | */ 5 | export function areAllLibraryColorsInDocument(libSvgColors, document) { 6 | let assets = document.documentData().assets(); 7 | let libMSColors = libSvgColors.map(c => svgColorToMSColor(c)); 8 | 9 | // collect all colors currently in this doc that aren't in the 10 | // target colors and save them, to add back at the end 11 | let existingColors = assets.colorAssets 12 | ? Array.from(assets.colorAssets()).map(ca => ca.color()) 13 | : Array.from(assets.colors()); 14 | let libColorsInDoc = libMSColors 15 | .filter(libColor => existingColors.find(docColor => docColor.isEqual(libColor))); 16 | return libColorsInDoc.length == libMSColors.length; 17 | } 18 | 19 | 20 | /** 21 | * Adds all the colors in the given array of SVG colors to the document's 22 | * colors. 23 | */ 24 | export function addLibraryColorsToDocument(libSvgColors, document) { 25 | // TODO: error out on Sketch 53 26 | let assets = document.documentData().assets(); 27 | let libMSColors = libSvgColors.map(c => svgColorToMSColor(c)); 28 | 29 | // collect all colors currently in this doc that aren't in the 30 | // target colors and save them, to add back at the end 31 | let existingColorsToKeep = Array.from(assets.colors()) 32 | .filter(color => 33 | libMSColors.reduce( 34 | (keep, libColor) => keep && !color.isEqual(libColor), true)); 35 | 36 | assets.removeAllColors(); 37 | 38 | libMSColors.forEach(color => assets.addColor(color)); 39 | existingColorsToKeep.forEach(color => assets.addColor(color)); 40 | } 41 | 42 | 43 | /** 44 | * Converts an SVG/CSS color string like '#fff' or 'rgba(...)' 45 | * to an MSColor 46 | */ 47 | export function svgColorToMSColor(color) { 48 | let ic = MSImmutableColor.colorWithSVGString(color); 49 | return MSColor.alloc().initWithRed_green_blue_alpha_( 50 | ic.red(), ic.green(), ic.blue(), ic.alpha()); 51 | } 52 | 53 | 54 | /** 55 | * Converts an MSColor to an SVG/CSS color string. 56 | */ 57 | export function msColorToSVGColor(color) { 58 | let r = Math.round(255 * color.red()); 59 | let g = Math.round(255 * color.green()); 60 | let b = Math.round(255 * color.blue()); 61 | let a = Number(Number(color.alpha()).toFixed(2)); 62 | return `rgba(${r}, ${g}, ${b}, ${a})`; 63 | } -------------------------------------------------------------------------------- /src/commands.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Pratik Shah 3 | * 4 | * Below code has been modified by Pratik Shah. Original by Roman Nurik 5 | * 6 | * http://pratikshah.website 7 | * 8 | * This is Licensed under the MIT License. 9 | * Along with previous the Apache License, Version 2.0 (the "License"); 10 | * 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | 23 | if (!global._babelPolyfill) { 24 | require('babel-polyfill'); 25 | } 26 | 27 | import {StickersUI} from './stickers-ui.js'; 28 | import * as util from './util'; 29 | import * as handler from './handler'; 30 | 31 | export function onShowStickers(context) { 32 | handler.init(context); 33 | let window = new StickersUI(context); 34 | window.showHide(); 35 | handler.trackEvent("Stickers", "onShowHideStickers", 1); 36 | } 37 | 38 | export function onClearCache(context) { 39 | handler.init(context); 40 | util.rmdirRecursive(util.getPluginCachePath()); 41 | context.document.showMessage(`✅ Symbol index cleared`); 42 | handler.trackEvent("Stickers", "onClearCache", 1); 43 | } 44 | -------------------------------------------------------------------------------- /src/handler.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Pratik Shah 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import sketch from 'sketch' 18 | 19 | var globalContext; 20 | var remoteManifestUrl = "https://raw.githubusercontent.com/pratikjshah/symbol-browser/master/symbol-browser.sketchplugin/Contents/Sketch/manifest.json"; 21 | var localDataPath; 22 | var userConfig; 23 | var pluginRoot; 24 | var hasResponseCame = false; 25 | const timeout = require('@skpm/timers'); 26 | var UI = require('sketch/ui'); 27 | var Settings = require('sketch/settings'); 28 | 29 | // ===== Menu action handlers ======================== 30 | 31 | export function onAction(context) { 32 | // console.log("Action: " + context.action); 33 | } 34 | 35 | export function onOpenDocument(context) { 36 | globalContext = context; 37 | init(context); 38 | networkRequest(remoteManifestUrl, manageDailyUpdateCheck); 39 | trackEvent("onAction", "onOpenDocument", 1); 40 | } 41 | 42 | export function checkForUpdate(context) { 43 | init(context); 44 | networkRequest(remoteManifestUrl, manageManualUpdate); 45 | trackEvent("checkForUpdate", "manualCheckForUpdate", 1); 46 | // context.document.showMessage("remoteManifest: " + remoteManifest.version); 47 | } 48 | 49 | // ===== Other functions ========================== 50 | 51 | export function openDocumentation(context) { 52 | init(context); 53 | openUrlInBrowser("http://symbol-browser.pratikshah.website/#faq"); 54 | } 55 | 56 | export function openSampleFile(context) { 57 | init(context); 58 | // openUrlInBrowser("https://sketch.cloud/s/DVnWq"); 59 | openUrlInBrowser("https://www.sketch.com/s/f577ec9e-127a-4c5a-bd26-22ba9ddb64f5"); 60 | } 61 | 62 | export function reportIssue(context) { 63 | init(context); 64 | openUrlInBrowser("https://github.com/pratikjshah/symbol-browser/issues"); 65 | } 66 | 67 | export function aboutPratikShah(context) { 68 | init(context); 69 | openUrlInBrowser("http://pratikshah.website"); 70 | } 71 | 72 | export function manageDailyUpdateCheck(remoteManifest) { 73 | var isDailyCheck = true; 74 | manageUpdate(remoteManifest, isDailyCheck); 75 | } 76 | 77 | export function manageManualUpdate(remoteManifest) { 78 | var isDailyCheck = false; 79 | manageUpdate(remoteManifest, isDailyCheck); 80 | } 81 | 82 | export function manageUpdate(remoteManifest, isDailyCheck) { 83 | // console.log("userConfig.localVersion: "+ userConfig.localVersion + " | remoteManifest.version: " + remoteManifest.version); 84 | 85 | /*if (userConfig.localVersion != remoteManifest.version) { 86 | showMsg(userConfig.name + ": "+ userConfig.localVersion + " is out of date! Please check for updates."); 87 | }*/ 88 | 89 | var localVersion = globalContext.plugin.version(); 90 | if (remoteManifest.version) { 91 | if (localVersion === remoteManifest.version) { 92 | if(!isDailyCheck) { 93 | // globalContext.document.showMessage("🤘Yo🤘! You are using the latest version of " + remoteManifest.name); 94 | UI.message("🤘Yo🤘! You are using the latest version of " + remoteManifest.name); 95 | Settings.setSettingForKey('hasUpdates', false); 96 | // console.log("🤘Yo🤘! You are using the latest version of " + remoteManifest.name); 97 | // localStorage.setItem("hasUpdates", false); 98 | } 99 | setUpdateCheckDayOnTomorrow(); 100 | } else { 101 | // globalContext.document.showMessage("Hey👋! New version of " + remoteManifest.name + " is available!"); 102 | UI.message("Hey👋! New version of " + remoteManifest.name + " is available!"); 103 | Settings.setSettingForKey('hasUpdates', true); 104 | // localStorage.setItem("hasUpdates", true); 105 | // console.log("Hey👋! New version of " + remoteManifest.name + " is available!"); 106 | //showAvailableUpdateDialog(); 107 | setUpdateCheckDayOnTomorrow(); 108 | } 109 | } else { 110 | //globalContext.document.showMessage("can not check:"); 111 | //showAvailableUpdateDialog(); 112 | setUpdateCheckDayOnTomorrow(); 113 | } 114 | } 115 | 116 | function setUpdateCheckDayOnTomorrow() { 117 | var newTime = new Date(); 118 | newTime.setDate(newTime.getDate() + 1); 119 | userConfig.localUpdateTime = newTime.getTime(); 120 | saveLocalData(userConfig, localDataPath); 121 | } 122 | 123 | // ===== Dialog functions ========================== 124 | 125 | function showAvailableUpdateDialog() { 126 | var window = createDownloadWindow(); 127 | var alert = window[0]; 128 | // When “Ok” is clicked 129 | var response = alert.runModal(); 130 | if (response == "1000") { 131 | //globalContext.document.showMessage("Go to download"); 132 | openUrlInBrowser("https://github.com/pratikjshah/symbol-browser/releases/latest/download/symbol-browser.sketchplugin.zip"); 133 | } else { 134 | //globalContext.document.showMessage("Check later"); 135 | setUpdateCheckDayOnTomorrow(); 136 | } 137 | } 138 | 139 | // ===== Helper functions ========================== 140 | 141 | export function init(context) { 142 | globalContext = context; 143 | pluginRoot = globalContext.scriptPath.stringByDeletingLastPathComponent().stringByDeletingLastPathComponent().stringByDeletingLastPathComponent(); 144 | localDataPath = pluginRoot + "/Contents/Resources/user.config"; 145 | userConfig = readLocalData(localDataPath); 146 | 147 | var newTime = new Date(); 148 | if (userConfig.localUpdateTime < newTime.getTime()) { 149 | trackEvent("checkForUpdate", "dailyCheckForUpdate", 1); 150 | networkRequest(remoteManifestUrl, manageDailyUpdateCheck); 151 | } 152 | /*var remoteManifest = getRemoteJson(remoteManifestUrl); 153 | if (userConfig.localVersion != remoteManifest.version) { 154 | showMsg(userConfig.name + ": "+ userConfig.localVersion + " is out of date! Please check for updates."); 155 | } 156 | setUpdateCheckDayOnTomorrow();*/ 157 | } 158 | 159 | export function showMsg(msg) { 160 | // globalContext.document.showMessage(msg); 161 | console.log("in showMsg"); 162 | console.log(msg); 163 | } 164 | 165 | export function openUrlInBrowser(url) { 166 | NSWorkspace.sharedWorkspace().openURL(NSURL.URLWithString(url)); 167 | trackEvent("openUrlInBrowser", url, 1); 168 | } 169 | 170 | export function saveLocalData(data, path) { 171 | /*var string = [NSString stringWithFormat: "%@", JSON.stringify(data)]; 172 | [string writeToFile: path atomically: true encoding: NSUTF8StringEncoding error: nil];*/ 173 | data = JSON.stringify(data); 174 | var text = NSString.stringWithFormat("%@", data); 175 | var file = NSString.stringWithFormat("%@", path); 176 | return text.writeToFile_atomically_encoding_error(file, true, NSUTF8StringEncoding, null); 177 | } 178 | 179 | export function readLocalData(path) { 180 | if(NSFileManager.defaultManager().fileExistsAtPath(path)){ 181 | var string = NSString.stringWithContentsOfFile_encoding_error(path,4, nil); 182 | string = string.replace(/(\r\n|\n|\r)/gm,""); 183 | var data = JSON.parse(string); 184 | return data; 185 | } 186 | } 187 | 188 | export function networkRequest(url, callBackFun) { 189 | 190 | /* 191 | 192 | // console.log("in networkRequest: \n" + url + " \n " + callBackFun); 193 | 194 | return fetch(url) 195 | .then(function (response) { 196 | if (!response.ok) { 197 | throw Error(response.statusText); 198 | } 199 | return response; 200 | }) 201 | .then(function (response) { 202 | return response.json(); 203 | }) 204 | .then(function (result) { 205 | console.log('Response Params: \n url: ' + url + " \n callBackFun: " + callBackFun); 206 | console.log(result); 207 | if(callBackFun !== 'undefined') { 208 | callBackFun(result); 209 | } 210 | return result; 211 | }) 212 | .catch(function (error) { 213 | console.log('Params: \n url: ' + url + " \n callBackFun: " + callBackFun); 214 | console.log('Looks like there was a problem: \n', error); 215 | }); 216 | 217 | */ 218 | 219 | try { 220 | var url = NSURL.URLWithString(""+url); 221 | var data = NSData.dataWithContentsOfURL(url); 222 | var json = NSJSONSerialization.JSONObjectWithData_options_error(data, 0, nil); 223 | // log("parsed data / json"); 224 | // log(json); 225 | // console.log('Params: \n url: ' + url + " \n callBackFun: " + callBackFun); 226 | callBackFun(json); 227 | } catch(e) { 228 | log("Exception: " + e); 229 | } 230 | } 231 | 232 | export function trackEvent(action, label, value) { 233 | /* 234 | var kUUIDKey = 'google.analytics.uuid' 235 | var uuid = NSUserDefaults.standardUserDefaults().objectForKey(kUUIDKey) 236 | if (!uuid) { 237 | uuid = NSUUID.UUID().UUIDString() 238 | NSUserDefaults.standardUserDefaults().setObject_forKey(uuid, kUUIDKey) 239 | } 240 | 241 | var tid = "UA-64818389-8"; 242 | var cid = uuid; 243 | var ds = "Sketch-" + NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString"); 244 | var baseURL = "https://www.google-analytics.com/debug/collect?v=1&ds=" + ds + "&t=event&tid=" + tid + "&cid=" + cid; 245 | baseURL = "https://www.google-analytics.com/collect?v=1&ds=" + ds + "&t=event&tid=" + tid + "&cid=" + cid; 246 | var version = context.plugin.version().UTF8String(); 247 | 248 | var trackingURL = baseURL + "&ec=SketchSymbolBrowser-" + version + "&ea=" + action + "&el=" + label + "&ev=" + value; 249 | // networkRequest(trackingURL); 250 | */ 251 | 252 | // console.log("globalContext"); 253 | // console.log(globalContext); 254 | 255 | var trackingID = "UA-64818389-8"; 256 | var userDefaults = NSUserDefaults.standardUserDefaults(); 257 | 258 | var uuidKey = "google.analytics.uuid"; 259 | var uuid = userDefaults.objectForKey(uuidKey); 260 | if (!uuid) { 261 | uuid = NSUUID.UUID().UUIDString(); 262 | userDefaults.setObject_forKey(uuid, uuidKey); 263 | userDefaults.synchronize(); 264 | } 265 | 266 | var appName = encodeURI(globalContext.plugin.name()), 267 | appId = globalContext.plugin.identifier(), 268 | appVersion = globalContext.plugin.version(); 269 | 270 | var url = "https://www.google-analytics.com/collect?v=1"; 271 | // Tracking ID 272 | url += "&tid=" + trackingID; 273 | // Source 274 | url += "&ds=sketch" + MSApplicationMetadata.metadata().appVersion; 275 | // Client ID 276 | url += "&cid=" + uuid; 277 | // User GEO location 278 | url += "&geoid=" + NSLocale.currentLocale().countryCode(); 279 | // User language 280 | url += "&ul=" + NSLocale.currentLocale().localeIdentifier().toLowerCase(); 281 | // pageview, screenview, event, transaction, item, social, exception, timing 282 | url += "&t=event"; 283 | // App Name 284 | url += "&an=" + appName; 285 | // App ID 286 | url += "&aid=" + appId; 287 | // App Version 288 | url += "&av=" + appVersion; 289 | // Event category 290 | url += "&ec=" + encodeURI("SketchSymbolBrowser-" + appVersion); 291 | // Event action 292 | // url += "&ea=" + encodeURI(eventAction); 293 | url += "&ea=" + encodeURI(action); 294 | // Event label 295 | // if (eventLabel) { 296 | // url += "&el=" + encodeURI(eventLabel); 297 | // } 298 | url += "&el=" + encodeURI(label); 299 | // Event value 300 | // if (eventValue) { 301 | // url += "&ev=" + encodeURI(eventValue); 302 | // } 303 | url += "&ev=" + encodeURI(value); 304 | 305 | // console.log("new ga url: " + url); 306 | 307 | var session = NSURLSession.sharedSession(); 308 | var task = session.dataTaskWithURL(NSURL.URLWithString(NSString.stringWithString(url))); 309 | task.resume(); 310 | } -------------------------------------------------------------------------------- /src/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": " 🔄 Symbol Browser", 3 | "description": "Better way to browse your Design System and UI Sticker sheet", 4 | "icon": "symbol-browser.png", 5 | "author": "Pratik Shah", 6 | "email": "hello@pratikshah.website", 7 | "appcast": "https://raw.githubusercontent.com/pratikjshah/symbol-browser/master/appcast.xml", 8 | "homepage": "http://symbol-browser.pratikshah.website/", 9 | "version": "3.5.2", 10 | "identifier" : "website.pratikshah.symbol-browser", 11 | "compatibleVersion": "52", 12 | "bundleVersion": "1", 13 | 14 | "commands": [ 15 | { 16 | "script" : "./handler.js", 17 | "handlers": { 18 | "actions": { 19 | "OpenDocument": "onOpenDocument" 20 | } 21 | }, 22 | "name" : "onOpenDocument", 23 | "identifier" : "onOpenDocument" 24 | }, 25 | { 26 | "script" : "./commands.js", 27 | "handlers": { 28 | "run": "onShowStickers" 29 | }, 30 | "name" : "🔍 View Design System", 31 | "shortcut": "cmd shift d", 32 | "identifier" : "show_stickers", 33 | "description" : "Show or hide Design System window.", 34 | "icon" : "icon-menu.png" 35 | }, 36 | { 37 | "script" : "./commands.js", 38 | "handlers": { 39 | "run": "onClearCache" 40 | }, 41 | "name" : "🧹 Clear Symbol Index", 42 | "identifier" : "clear_cache", 43 | "description" : "Clear the Symbol index for troubleshooting purposes.", 44 | "icon" : "icon-menu.png" 45 | }, 46 | { 47 | "script": "./handler.js", 48 | "handler": "openDocumentation", 49 | "shortcut": "", 50 | "name": "Create custom Symbol groups", 51 | "identifier": "openDocumentation", 52 | "description" : "View Symtax guide for adding Custom sections", 53 | "icon" : "icon-menu.png" 54 | }, 55 | { 56 | "script": "./handler.js", 57 | "handler": "openSampleFile", 58 | "shortcut": "", 59 | "name": "Example Sketch Library", 60 | "identifier": "openSampleFile", 61 | "description" : "Get Example Sketch Library and see what's possible!", 62 | "icon" : "icon-menu.png" 63 | }, 64 | { 65 | "script": "./handler.js", 66 | "handler": "reportIssue", 67 | "shortcut": "", 68 | "name": "Report issue", 69 | "identifier": "reportIssue" 70 | }, 71 | { 72 | "script": "./handler.js", 73 | "handler": "checkForUpdate", 74 | "shortcut": "", 75 | "name": "Check for Plugin update", 76 | "identifier": "checkForUpdate" 77 | }, 78 | { 79 | "script": "./handler.js", 80 | "handler": "aboutPratikShah", 81 | "shortcut": "", 82 | "name": "About Pratik Shah", 83 | "identifier": "aboutPratikShah" 84 | } 85 | ], 86 | "menu": { 87 | "items": [ 88 | "show_stickers", 89 | "-", 90 | "openSampleFile", 91 | "openDocumentation", 92 | "-", 93 | "clear_cache", 94 | "-", 95 | { 96 | "title": "More", 97 | "items": [ 98 | "reportIssue", 99 | "checkForUpdate", 100 | "-", 101 | "aboutPratikShah" 102 | ] 103 | } 104 | ], 105 | "title": " 🔄 Symbol Browser" 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/stickers-ui.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import path from '@skpm/path'; 18 | import fs from '@skpm/fs'; 19 | import BrowserWindow from 'sketch-module-web-view'; 20 | 21 | import * as libraries from './util-libraries'; 22 | import * as util from './util'; 23 | import * as colorUtil from './color-util'; 24 | 25 | import {makeStickerIndexForLibraries} from './sticker-index'; 26 | 27 | const THREAD_DICT_KEY = 'stickers.BrowserWindow'; 28 | // const UI_MODE = 'cover'; 29 | const UI_MODE = 'modal'; 30 | // MSTheme.sharedTheme().isDark() 31 | const DARK_MODE = (NSAppKitVersionNumber >= 1671 && 32 | 'Dark' === String(NSUserDefaults.standardUserDefaults().stringForKey('AppleInterfaceStyle'))); 33 | 34 | const BUILD_SKETCH_53_BETA_1 = 71402; 35 | 36 | export class StickersUI { 37 | constructor(context) { 38 | this.context = context; 39 | } 40 | 41 | /** 42 | * Shows or hides the Stickers window (if already shown). 43 | * The state is stored in the main thread's threadDictionary. 44 | */ 45 | showHide() { 46 | let browserWindow = this.getPersistedObj(); 47 | if (browserWindow) { 48 | browserWindow.focus(); 49 | browserWindow.show(); 50 | // browserWindow.moveTop(); 51 | // browserWindow.close(); 52 | // this.setPersistedObj(null); 53 | } else { 54 | this.createAndShow(); 55 | this.context.document.showMessage(`⌛️ Initializing Symbol Browser...`); 56 | } 57 | } 58 | 59 | 60 | getPersistedObj() { 61 | let threadDict = NSThread.mainThread().threadDictionary(); 62 | return threadDict[THREAD_DICT_KEY]; 63 | } 64 | 65 | 66 | setPersistedObj(obj) { 67 | let threadDict = NSThread.mainThread().threadDictionary(); 68 | if (obj) { 69 | threadDict[THREAD_DICT_KEY] = obj; 70 | } else { 71 | threadDict.removeObjectForKey(THREAD_DICT_KEY); 72 | } 73 | } 74 | 75 | 76 | runWebCallback(callbackName, ...args) { 77 | let js = ( 78 | `window['${callbackName}'](` + 79 | args.map(arg => JSON.stringify(arg)).join(', ') + 80 | `);`); 81 | try { 82 | this.webContents.executeJavaScript(js); 83 | } catch (e) { 84 | log(e.message); 85 | log(e); 86 | } 87 | } 88 | 89 | 90 | createAndShow() { 91 | let docWindow = this.context.document.documentWindow(); 92 | 93 | this.browserWindow = new BrowserWindow({ 94 | backgroundColor: '#ffffffff', 95 | identifier: 'stickers.web', 96 | width: 1200, 97 | height: 800, 98 | show: false, 99 | frame: UI_MODE == 'modal', 100 | modal: UI_MODE == 'modal', 101 | hasShadow: UI_MODE == 'modal', 102 | title: 'Symbol Browser', 103 | acceptsFirstMouse: true, 104 | }); 105 | 106 | this.webContents = this.browserWindow.webContents; 107 | this.setupWebAPI(); 108 | 109 | this.browserWindow.on('closed', () => { 110 | this.setPersistedObj(null); 111 | coscript.setShouldKeepAround(false); 112 | }); 113 | 114 | // this.browserWindow.on('blur', () => this.browserWindow.close()); 115 | 116 | if (UI_MODE == 'cover') { 117 | this.browserWindow.setResizable(false); 118 | this.browserWindow._panel.setFrame_display_animate_(docWindow.frame(), false, false); 119 | this.browserWindow._panel.setHidesOnDeactivate(false); 120 | } 121 | if (UI_MODE == 'modal') { 122 | this.browserWindow.setResizable(true); 123 | // this.browserWindow._panel.setFrame_display_animate_(docWindow.frame(), false, false); 124 | this.browserWindow._panel.setHidesOnDeactivate(false); 125 | } 126 | this.browserWindow.once('ready-to-show', () => { 127 | this.browserWindow.show(); 128 | if (UI_MODE == 'cover') { 129 | docWindow.addChildWindow_ordered_(this.browserWindow._panel, NSWindowAbove); 130 | } 131 | if (UI_MODE == 'modal') { 132 | // docWindow.addChildWindow_ordered_(this.browserWindow._panel, NSWindowAbove); 133 | } 134 | }); 135 | 136 | this.browserWindow.loadURL(String( 137 | this.context.plugin.urlForResourceNamed('index.html') + 138 | `?uiMode=${UI_MODE}&darkMode=${DARK_MODE ? 1 : 0}`)); 139 | 140 | this.setPersistedObj(this.browserWindow); 141 | } 142 | 143 | 144 | setupWebAPI() { 145 | let libraryIndexesById = {}; 146 | this.webContents.on('loadStickerIndex', (callbackName, progressCallbackName) => { 147 | // trigger the creation of the sticker index 148 | makeStickerIndexForLibraries( 149 | {onProgress: progress => this.runWebCallback(progressCallbackName, progress)}) 150 | .then(stickerIndex => { 151 | stickerIndex.libraries.forEach(libraryIndex => { 152 | libraryIndex.colorsAvailable = libraryIndex.colors && libraryIndex.colors.length; 153 | if (MSArchiveHeader.metadataForNewHeader().build >= BUILD_SKETCH_53_BETA_1) { 154 | // no need to do this in Sketch 53 155 | libraryIndex.colorsAvailable = false; 156 | } 157 | if (libraryIndex.colorsAvailable) { 158 | libraryIndex.colorsAdded = colorUtil.areAllLibraryColorsInDocument( 159 | libraryIndex.colors, this.context.document); 160 | } 161 | libraryIndexesById[libraryIndex.id] = libraryIndex; 162 | }); 163 | this.runWebCallback(callbackName, stickerIndex); 164 | }) 165 | .catch(e => log(e.message)); 166 | }); 167 | 168 | this.webContents.on('openUrl', url => { 169 | NSWorkspace.sharedWorkspace().openURL(NSURL.URLWithString(url)); 170 | }); 171 | 172 | // add a handler for a call from web content's javascript 173 | this.webContents.on('close', () => this.browserWindow.close()); 174 | 175 | this.webContents.on('requestLayerImageUrl', (stickerId, callbackName) => { 176 | let imagePath = this.getStickerCachedImagePath(stickerId); 177 | // let url = nsImageToDataUri(NSImage.alloc().initWithContentsOfFile(imagePath)); 178 | let url = 'file://' + imagePath; 179 | this.runWebCallback(callbackName, stickerId, url); 180 | }); 181 | 182 | // add a handler for a call from web content's javascript 183 | this.webContents.on('startDragging', (stickerId, rect) => { 184 | try { 185 | let [libraryId, layerId] = stickerId.split(/\./, 2); 186 | let archiveVersion = libraryIndexesById[libraryId].archiveVersion; 187 | this.startDragging(libraryId, archiveVersion, stickerId, rect, this.browserWindow._webview); 188 | } catch (e) { 189 | // TODO: do this everywhere somehow 190 | log(e.message); 191 | log(e); 192 | } 193 | if (UI_MODE == 'cover') { 194 | this.browserWindow.close(); 195 | } 196 | if (UI_MODE == 'modal') { 197 | // this.browserWindow.close(); 198 | } 199 | }); 200 | 201 | // add a handler for a call from web content's javascript 202 | this.webContents.on('addLibraryColors', (libraryId) => { 203 | try { 204 | let library = libraryIndexesById[libraryId]; 205 | colorUtil.addLibraryColorsToDocument(library.colors, this.context.document); 206 | } catch (e) { 207 | // TODO: do this everywhere somehow 208 | log(e.message); 209 | log(e); 210 | } 211 | }) 212 | } 213 | 214 | /** 215 | * Triggers the beginning of a drag operation on the given sticker ID 216 | */ 217 | startDragging(libraryId, archiveVersion, stickerId, rect, srcView) { 218 | let library = libraries.getLibraryById(libraryId, {onlyEnabled: true}); 219 | let image = NSImage.alloc().initWithContentsOfFile(this.getStickerCachedImagePath(stickerId)); 220 | 221 | // deserialize layer 222 | let serializedLayerJson = fs.readFileSync( 223 | this.getStickerCachedContentPath(stickerId), {encoding: 'utf8'}); 224 | // let decodedImmutableObj = MSJSONDataUnarchiver 225 | // .unarchiveObjectWithString_asVersion_corruptionDetected_error( 226 | // serializedLayerJson, archiveVersion || 999, null, null); 227 | let unarchiveFn = ( // method was renamed in Sketch 64 -- extra 'd') 228 | MSJSONDataUnarchiver.unarchivedObjectWithString_asVersion_corruptionDetected_error || 229 | MSJSONDataUnarchiver.unarchiveObjectWithString_asVersion_corruptionDetected_error); 230 | let decodedImmutableObj = unarchiveFn(serializedLayerJson, archiveVersion || 999, null, null); 231 | let layer = decodedImmutableObj.newMutableCounterpart(); 232 | 233 | // create a dummy document and import the layer into it, so that 234 | // foreign symbols can be created in it and sent along with the layer 235 | // to the pasteboard 236 | let dummyDocData = MSDocumentData.alloc().init(); 237 | dummyDocData.addBlankPage().addLayer(layer); 238 | 239 | // import any symbols and shared styles used in library (either from the library itself or 240 | // other libraries referenced from the library... i.e. nested libraries) 241 | // if(layer.class() == 'MSSymbolMaster') { 242 | // libraries.replaceSymbolsWithInstance(dummyDocData, layer, library); 243 | // } else { 244 | // libraries.replaceSymbolsAndSharedStylesInLayerWithLibrary(dummyDocData, layer, library); 245 | // } 246 | 247 | libraries.replaceSymbolsAndSharedStylesInLayerWithLibrary(dummyDocData, layer, library); 248 | 249 | // initiate cocoa drag operation 250 | // let pbItem = NSPasteboardItem.new(); 251 | // pbItem.setData_forType_( 252 | // image.TIFFRepresentation(), 253 | // NSPasteboardTypePNG); 254 | let dragItem = NSDraggingItem.alloc().initWithPasteboardWriter(image); 255 | // pbItem.release(); 256 | dragItem.setDraggingFrame_contents_( 257 | NSMakeRect(rect.x, rect.y, rect.width, rect.height), 258 | image); 259 | let mouse = NSEvent.mouseLocation(); 260 | let event = NSEvent.eventWithCGEvent(CGEventCreateMouseEvent( 261 | null, 262 | kCGEventLeftMouseDown, 263 | CGPointMake( 264 | mouse.x - srcView.window().frame().origin.x, 265 | NSHeight(NSScreen.screens().firstObject().frame()) 266 | - mouse.y + srcView.window().frame().origin.y), 267 | kCGMouseButtonLeft)); 268 | let draggingSession = srcView.beginDraggingSessionWithItems_event_source_( 269 | NSArray.arrayWithObject(dragItem.autorelease()), event, srcView); 270 | draggingSession.setAnimatesToStartingPositionsOnCancelOrFail(false); 271 | draggingSession.setDraggingFormation(NSDraggingFormationNone); 272 | 273 | // copy to pasteboard 274 | let dpb = NSPasteboard.pasteboardWithName(NSDragPboard); 275 | dpb.clearContents(); 276 | try { 277 | let newPbLayers = MSPasteboardLayers.pasteboardLayersWithLayers([layer]); 278 | MSPasteboardManager.writePasteboardLayers_toPasteboard(newPbLayers, dpb); 279 | } catch (err) { 280 | throw err; 281 | } 282 | } 283 | 284 | 285 | getStickerCachedImagePath(stickerId) { 286 | let [libraryId, layerId] = stickerId.split(/\./, 2); 287 | return path.join(util.getPluginCachePath(), libraryId, layerId + '.png'); 288 | } 289 | 290 | 291 | getStickerCachedContentPath(stickerId) { 292 | let [libraryId, layerId] = stickerId.split(/\./, 2); 293 | return path.join(util.getPluginCachePath(), libraryId, layerId + '.json'); 294 | } 295 | } -------------------------------------------------------------------------------- /src/util-libraries.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import * as util from './util'; 18 | 19 | 20 | /** 21 | * Returns the MSAssetLibrary / MSUserAssetLibrary with the given library ID 22 | * (which is a UUID) 23 | */ 24 | export function getLibraryById(libraryId, {onlyEnabled = false} = {}) { 25 | return util.arrayFromNSArray(getLibrariesController().libraries()) 26 | .filter(lib => onlyEnabled ? !!lib.enabled() : true) 27 | .find(lib => String(lib.libraryID()) == String(libraryId)); 28 | } 29 | 30 | 31 | /** 32 | * Adds the given .sketch file as a library in Sketch. 33 | */ 34 | export function addLibrary(context, librarySketchFilePath) { 35 | getLibrariesController().addAssetLibraryAtURL(NSURL.fileURLWithPath(librarySketchFilePath)); 36 | getLibrariesController().notifyLibraryChange( 37 | getLibrariesController().userLibraries().firstObject()); // notify change on any lib 38 | } 39 | 40 | export function replaceSymbolsAndSharedStylesInLayerWithLibrary( 41 | parentDocument, parentLayer, library) { 42 | 43 | if (parentLayer.children) { 44 | let maybeImportForeignObjectWithId = objectId => { 45 | // TODO: is this valid/useful? 46 | // let existing = parentDocument.documentData().foreignSymbols() 47 | // .find(fs => String(fs.symbolMaster().symbolID()) == String(symbolId)); 48 | // if (existing) { 49 | // return existing; 50 | // } 51 | 52 | let objectInLibrary = ( 53 | library.document().symbolWithID(objectId) || 54 | library.document().textStyleWithID(objectId) || 55 | library.document().layerStyleWithID(objectId)); 56 | if (objectInLibrary) { 57 | let foreignObject = objectInLibrary.foreignObject(); 58 | 59 | if (foreignObject) { 60 | // the shared obj in the target library is a foreign obj from yet 61 | // another library, try to import it from the other library, and if 62 | // unavailable, grab the MSForeignObject and add it to the target 63 | // document directly 64 | let nestedLibrary = getLibraryById(foreignObject.libraryID(), {onlyEnabled: true}); 65 | if (nestedLibrary) { 66 | let objectInNestedLibrary = ( 67 | nestedLibrary.document().symbolWithID(foreignObject.remoteShareID()) || 68 | nestedLibrary.document().textStyleWithID(foreignObject.remoteShareID()) || 69 | nestedLibrary.document().layerStyleWithID(foreignObject.remoteShareID()) || 70 | objectInLibrary /* worst case, just try to import the object in the outer lib */); 71 | return importObjectFromLibrary(objectInNestedLibrary, nestedLibrary, 72 | parentDocument.documentData()); 73 | } else { 74 | if (objectInLibrary instanceof MSSymbolMaster) { 75 | // TODO: investigate what other dependencies we may need to bring in 76 | // when calling addForeignXX() on a foreign object from another doc. 77 | // likely we need to add other foreign objects that this one relies on 78 | parentDocument.documentData().addForeignSymbol(foreignObject); 79 | return foreignObject; 80 | } /*else if (objectInLibrary instanceof MSTextStyle) { 81 | parentDocument.documentData().addForeignTextStyle(foreignObject); 82 | } else if (objectInLibrary instanceof MSLayerStyle) { 83 | parentDocument.documentData().addForeignLayerStyle(foreignObject); 84 | }*/ 85 | } 86 | } 87 | 88 | // the symbol in the target library is local to the library, import it 89 | // from the library 90 | return importObjectFromLibrary(objectInLibrary, library, 91 | parentDocument.documentData()); 92 | } 93 | 94 | return null; 95 | }; 96 | 97 | // Deep import is necessary when importing override symbols that themselves have overrides 98 | // This method returns a mapping from local to foreign ID 99 | let deepImportOverrides = (overridesDict) => { 100 | let localToForeignIdMap = {}; 101 | for (let k in overridesDict) { 102 | let foreignObject = maybeImportForeignObjectWithId(overridesDict[k]); 103 | if (foreignObject) { 104 | // swap out the symbol ID that's local to the library for the symbol ID 105 | // for the foreign symbol in the new document linked to the library 106 | localToForeignIdMap[String(overridesDict[k])] = String(foreignObject.localShareID()); 107 | } 108 | 109 | localToForeignIdMap = Object.assign( 110 | localToForeignIdMap, 111 | deepImportOverrides(overridesDict[k])); 112 | } 113 | return localToForeignIdMap; 114 | }; 115 | 116 | let allSymbolInstances = util.getAllLayersMatchingPredicate( 117 | parentLayer, NSPredicate.predicateWithFormat('className == %@', 'MSSymbolInstance')); 118 | allSymbolInstances.forEach(symbolInstance => { 119 | let symbolId = symbolInstance.symbolID(); 120 | let foreignSymbol = maybeImportForeignObjectWithId(symbolId); 121 | if (foreignSymbol) { 122 | symbolInstance.changeInstanceToSymbol(foreignSymbol.symbolMaster()); 123 | replaceSymbolsAndSharedStylesInLayerWithLibrary( 124 | parentDocument, foreignSymbol.symbolMaster(), library); 125 | } 126 | 127 | let overrides = util.dictFromNSDict(symbolInstance.overrides()); 128 | let localToForeignSharedObjectIdMap = deepImportOverrides(overrides); 129 | 130 | symbolInstance.updateOverridesWithObjectIDMap(localToForeignSharedObjectIdMap); 131 | }); 132 | 133 | let allLayersWithSharedStyle = util.getAllLayersMatchingPredicate( 134 | parentLayer, NSPredicate.predicateWithFormat('sharedStyleID != nil')); 135 | allLayersWithSharedStyle.forEach(layerWithSharedStyle => { 136 | let styleId = layerWithSharedStyle.sharedStyleID(); 137 | let foreignSharedStyle = maybeImportForeignObjectWithId(styleId); 138 | if (foreignSharedStyle) { 139 | if (layerWithSharedStyle instanceof MSTextLayer) { 140 | // preserve formatted string value before setting shared style (which resets 141 | // character-level formatting) 142 | let aStr = layerWithSharedStyle.attributedStringValue(); 143 | layerWithSharedStyle.setSharedStyle(foreignSharedStyle.localSharedStyle()); 144 | layerWithSharedStyle.setAttributedStringValue(aStr); 145 | } else { // inherits MSStyledLayer 146 | let style = layerWithSharedStyle.style().copy(); 147 | layerWithSharedStyle.setSharedStyle(foreignSharedStyle.localSharedStyle()); 148 | layerWithSharedStyle.setStyle(style); 149 | } 150 | } 151 | }); 152 | } 153 | } 154 | 155 | 156 | /** 157 | * Compatibility layer for importForeignSymbol_fromLibrary_intoDocument, 158 | * removed in Sketch 50. 159 | * 160 | * @param {MSModelObject} libraryObject The object (e.g. symbol master, style) in library to import 161 | * @param {MSAssetLibrary} library The library to import from 162 | * @param {MSDocumentData} parentDocumentData The document data to import into 163 | * @returns {MSForeignObject} 164 | */ 165 | function importObjectFromLibrary(libraryObject, library, parentDocumentData) { 166 | let librariesController = getLibrariesController(); 167 | let shareableObjectReference = MSShareableObjectReference.referenceForShareableObject_inLibrary( 168 | libraryObject, library); 169 | return librariesController.importShareableObjectReference_intoDocument( 170 | shareableObjectReference, parentDocumentData); 171 | } 172 | 173 | 174 | /** 175 | * Returns an MSDocument for the library with the given ID (cached). 176 | * Note: this operation may take a while. 177 | */ 178 | export function docForLibraryId(libraryId) { 179 | docForLibraryId.__cache__ = docForLibraryId.__cache__ || {}; 180 | if (!(libraryId in docForLibraryId.__cache__)) { 181 | let library = Array.from(getLibrariesController().libraries()) 182 | .find(lib => String(lib.libraryID()) == libraryId); 183 | if (!library) { 184 | return null; 185 | } 186 | 187 | docForLibraryId.__cache__[libraryId] = utils.loadDocFromSketchFile( 188 | String(library.locationOnDisk().path())); 189 | } 190 | 191 | return docForLibraryId.__cache__[libraryId]; 192 | } 193 | 194 | 195 | /** 196 | * Gets the app instance's MSAssetLibraryController 197 | */ 198 | function getLibrariesController() { 199 | return AppController.sharedInstance().librariesController(); 200 | } 201 | -------------------------------------------------------------------------------- /src/util-progress-reporter.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import EventEmitter from '@skpm/events'; 18 | 19 | export class ProgressReporter extends EventEmitter { 20 | constructor(total = 0) { 21 | super(); 22 | this.total_ = total; 23 | this.counter = 0; 24 | this.childReporters = []; 25 | } 26 | 27 | get total() { 28 | return this.total_; 29 | } 30 | 31 | set total(total) { 32 | this.total_ = total; 33 | this.emitProgress(); 34 | } 35 | 36 | get progress() { 37 | if (!this.total && !this.childReporters.length) { 38 | return 0; 39 | } 40 | 41 | return (this.childReporters.reduce((acc, child) => acc + child.progress, 0) + this.counter) / 42 | (this.total + this.childReporters.length); 43 | } 44 | 45 | increment() { 46 | ++this.counter; 47 | this.emitProgress(); 48 | } 49 | 50 | forceProgress(progress) { 51 | if (this.childReporters.length) { 52 | throw new Error('Cannot force progress when there are child reporters'); 53 | } 54 | 55 | if (!this.total) { 56 | this.total = 1; 57 | } 58 | 59 | this.counter = progress * this.total; 60 | this.emitProgress(); 61 | } 62 | 63 | makeChildren(numChildren) { 64 | let newChildren = Array(numChildren).fill(0).map(a => { 65 | let childReporter = new ProgressReporter(); 66 | childReporter.on('progress', () => this.emitProgress()); 67 | return childReporter; 68 | }); 69 | this.childReporters = this.childReporters.concat(newChildren); 70 | this.emitProgress(); 71 | return newChildren; 72 | } 73 | 74 | emitProgress() { 75 | this.emit('progress', this.progress); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/util.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import path from '@skpm/path'; 18 | 19 | 20 | /** 21 | * Performs a depth-first traversal of the layer tree, starting 22 | * at the provided root layer. 23 | */ 24 | export function walkLayerTree(rootLayer, visitFunction, {reverse} = {reverse: false}) { 25 | let visit_ = layer => { 26 | // visit this layer 27 | visitFunction(layer); 28 | 29 | // visit children 30 | let subLayers; 31 | if ('layers' in layer) { 32 | subLayers = arrayFromNSArray(layer.layers()); 33 | } else if ('artboards' in layer) { 34 | subLayers = arrayFromNSArray(layer.artboards()); 35 | } else { 36 | return; 37 | } 38 | 39 | if (reverse) { 40 | subLayers.reverse(); 41 | } 42 | 43 | subLayers.forEach(subLayer => visit_(subLayer)); 44 | }; 45 | 46 | visit_(rootLayer); 47 | } 48 | 49 | 50 | /** 51 | * Converts an NSArray to a JS array 52 | */ 53 | export function arrayFromNSArray(nsArray) { 54 | // TODO: this may no longer be needed... as of recent versions of sketch 55 | // NSArray seems to be array-like. or at least replace with Array.from(nsarray) 56 | let arr = []; 57 | let count = nsArray.count(); 58 | for (let i = 0; i < count; i++) { 59 | arr.push(nsArray.objectAtIndex(i)); 60 | } 61 | return arr; 62 | } 63 | 64 | 65 | /** 66 | * Convert an NSDictionary-type object to a JS dict. 67 | * As of Sketch 50.2, this is needed for some cases of symbol instance overrides 68 | */ 69 | export function dictFromNSDict(nsDict) { 70 | let dict = {}; 71 | for (let key in nsDict) { 72 | dict[key] = nsDict[key]; 73 | } 74 | return dict; 75 | } 76 | 77 | 78 | /** 79 | * Returns the first layer matching the given NSPredicate 80 | * 81 | * @param {MSDocument|MSLayerGroup} parent The document or layer group to search. 82 | * @param {NSPredicate} predicate Search predicate 83 | */ 84 | export function getAllLayersMatchingPredicate(parent, predicate) { 85 | if (parent instanceof MSDocument) { 86 | // MSDocument 87 | return parent.pages().reduce( 88 | (acc, page) => acc.concat(getAllLayersMatchingPredicate(page, predicate)), 89 | []); 90 | } 91 | 92 | // assume MSLayerGroup 93 | return Array.from(parent.children().filteredArrayUsingPredicate(predicate)); 94 | } 95 | 96 | 97 | /** 98 | * Returns the first layer matching the given NSPredicate 99 | * 100 | * @param {MSDocument|MSLayerGroup} parent The document or layer group to search. 101 | * @param {NSPredicate} predicate Search predicate 102 | */ 103 | export function getFirstLayerMatchingPredicate(parent, predicate) { 104 | if (parent instanceof MSDocument) { 105 | // MSDocument 106 | let results; 107 | for (page of Array.from(parent.pages())) { 108 | let firstInPage = getFirstLayerMatchingPredicate(page, predicate); 109 | if (firstInPage) { 110 | return firstInPage; 111 | } 112 | } 113 | return null; 114 | } 115 | 116 | // assume MSLayerGroup 117 | return getAllLayersMatchingPredicate(parent, predicate)[0] || null; 118 | } 119 | 120 | 121 | /** 122 | * Finds the layer with the given objectID in the given document. 123 | */ 124 | export function getLayerById(document, layerId) { 125 | return getFirstLayerMatchingPredicate(document, 126 | NSPredicate.predicateWithFormat('objectID == %@', layerId)); 127 | } 128 | 129 | 130 | /** 131 | * Copied from @skpm/fs with intermediate directories. 132 | */ 133 | export function mkdirpSync(path, mode) { 134 | mode = mode || 0o777; 135 | let err = MOPointer.alloc().init(); 136 | let fileManager = NSFileManager.defaultManager(); 137 | fileManager.createDirectoryAtPath_withIntermediateDirectories_attributes_error(path, true, { 138 | NSFilePosixPermissions: mode 139 | }, err); 140 | 141 | if (err.value() !== null) { 142 | throw new Error(err.value()); 143 | } 144 | } 145 | 146 | 147 | /** 148 | * Returns an MSDocument for the given .sketch file path. May take 149 | * a long time! 150 | */ 151 | export function loadDocFromSketchFile(filePath) { 152 | let doc = MSDocument.new(); 153 | doc.readDocumentFromURL_ofType_error_( 154 | NSURL.fileURLWithPath(filePath), 155 | 'com.bohemiancoding.sketch.drawing', 156 | null); 157 | 158 | return doc; 159 | } 160 | 161 | 162 | /** 163 | * Returns an NSImage for the given layer in the given document. 164 | */ 165 | export function getLayerImage(document, layer) { 166 | let tempPath = NSTemporaryDirectory().stringByAppendingPathComponent( 167 | NSUUID.UUID().UUIDString() + '.png'); 168 | captureLayerImage(document, layer, tempPath); 169 | return NSImage.alloc().initWithContentsOfFile(tempPath); 170 | } 171 | 172 | 173 | /** 174 | * Saves the given layer in the given document to a PNG file at the given path. 175 | */ 176 | export function captureLayerImage(document, layer, destPath) { 177 | let air = layer.absoluteInfluenceRect(); 178 | let rect = NSMakeRect(air.origin.x, air.origin.y, air.size.width, air.size.height); 179 | // let exportRequest = MSExportRequest.exportRequestsFromLayerAncestry_inRect_( 180 | // MSImmutableLayerAncestry.ancestryWithMSLayer_(layer), 181 | // rect // we pass this to avoid trimming 182 | // ).firstObject(); 183 | // exportRequest.format = 'png'; 184 | // exportRequest.scale = 2; 185 | let exportRequest = MSExportRequest.exportRequestFromExportFormat_layer_inRect_useIDForName_( 186 | MSExportFormat.formatWithScale_name_fileFormat_(2.0, 'temp.png', 'png'), 187 | layer, 188 | rect, // avoid trimming 189 | true); 190 | 191 | if (!(layer instanceof MSArtboardGroup || layer instanceof MSSymbolMaster)) { 192 | exportRequest.includeArtboardBackground = false; 193 | } 194 | // exportRequest.shouldTrim = false; 195 | document.saveArtboardOrSlice_toFile_(exportRequest, destPath); 196 | } 197 | 198 | 199 | /** 200 | * Converts an NSImage to a data URL string (png). 201 | */ 202 | export function nsImageToDataUri(image) { 203 | let data = image.TIFFRepresentation(); 204 | let bitmap = NSBitmapImageRep.imageRepWithData(data); 205 | data = bitmap.representationUsingType_properties_(NSPNGFileType, null); 206 | let base64 = 'data:image/png;base64,' + data.base64EncodedStringWithOptions(0); 207 | return base64; 208 | } 209 | 210 | 211 | /** 212 | * Returns the system cache path for the plugin. 213 | */ 214 | export function getPluginCachePath() { 215 | let cachePath = String(NSFileManager.defaultManager().URLsForDirectory_inDomains_( 216 | NSCachesDirectory, 217 | NSUserDomainMask)[0].path()); 218 | let pluginCacheKey = String(__command.pluginBundle().identifier()); // TODO: escape if needed 219 | return path.join(cachePath, pluginCacheKey); 220 | } 221 | 222 | 223 | /** 224 | * Deletes the given file or directory recursively (i.e. it and its 225 | * subfolders). 226 | */ 227 | export function rmdirRecursive(path) { 228 | NSFileManager.defaultManager().removeItemAtPath_error_(path, null); 229 | } 230 | 231 | 232 | /** 233 | * Give the CPU some breathing room. 234 | */ 235 | export function unpeg() { 236 | return new Promise((resolve, reject) => { 237 | setTimeout(() => resolve(), 0); 238 | }); 239 | } 240 | 241 | 242 | /** 243 | * Profile the running time of a method 244 | */ 245 | export function _profile(fnOrPromise, tag = '') { 246 | tag = tag ? ` [${tag}]` : ''; 247 | let t = Number(new Date()); 248 | 249 | let finish = () => { 250 | t = Number(new Date()) - t; 251 | log(`profile${tag}: ${t}ms`); 252 | }; 253 | 254 | if (fnOrPromise instanceof Promise) { 255 | fnOrPromise.then(() => finish()); 256 | return fnOrPromise; 257 | } else { 258 | fnOrPromise(); 259 | finish(); 260 | } 261 | } 262 | 263 | 264 | /** 265 | * Returns the name of the given document, if it has one. 266 | * 267 | * @param {MSDocument} document 268 | */ 269 | export function getDocumentName(document) { 270 | let fileURL = document.fileURL(); 271 | if (fileURL) { 272 | fileURL = String(fileURL.path()); 273 | return path.basename(fileURL).replace(/\.[^.]+$/, ''); // strip extension 274 | } 275 | 276 | return null; 277 | } 278 | 279 | 280 | /** 281 | * Remove duplicate objects from Array 282 | */ 283 | export function getUniqueItems(arr, key) { 284 | const unique = arr 285 | .map(e => e[key]) 286 | // store the keys of the unique objects 287 | .map((e, i, final) => final.indexOf(e) === i && i) 288 | 289 | // eliminate the dead keys & store unique objects 290 | .filter(e => arr[e]).map(e => arr[e]); 291 | 292 | return unique; 293 | } -------------------------------------------------------------------------------- /symbol-browser.sketchplugin.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/symbol-browser.sketchplugin.zip -------------------------------------------------------------------------------- /symbol-browser.sketchplugin/Contents/Resources/icon-menu.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/symbol-browser.sketchplugin/Contents/Resources/icon-menu.png -------------------------------------------------------------------------------- /symbol-browser.sketchplugin/Contents/Resources/logo-dark.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /symbol-browser.sketchplugin/Contents/Resources/logo-light.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /symbol-browser.sketchplugin/Contents/Resources/newbg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/symbol-browser.sketchplugin/Contents/Resources/newbg.png -------------------------------------------------------------------------------- /symbol-browser.sketchplugin/Contents/Resources/plugin-call.js: -------------------------------------------------------------------------------- 1 | /******/ (function(modules) { // webpackBootstrap 2 | /******/ // The module cache 3 | /******/ var installedModules = {}; 4 | /******/ 5 | /******/ // The require function 6 | /******/ function __webpack_require__(moduleId) { 7 | /******/ 8 | /******/ // Check if module is in cache 9 | /******/ if(installedModules[moduleId]) { 10 | /******/ return installedModules[moduleId].exports; 11 | /******/ } 12 | /******/ // Create a new module (and put it into the cache) 13 | /******/ var module = installedModules[moduleId] = { 14 | /******/ i: moduleId, 15 | /******/ l: false, 16 | /******/ exports: {} 17 | /******/ }; 18 | /******/ 19 | /******/ // Execute the module function 20 | /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); 21 | /******/ 22 | /******/ // Flag the module as loaded 23 | /******/ module.l = true; 24 | /******/ 25 | /******/ // Return the exports of the module 26 | /******/ return module.exports; 27 | /******/ } 28 | /******/ 29 | /******/ 30 | /******/ // expose the modules object (__webpack_modules__) 31 | /******/ __webpack_require__.m = modules; 32 | /******/ 33 | /******/ // expose the module cache 34 | /******/ __webpack_require__.c = installedModules; 35 | /******/ 36 | /******/ // define getter function for harmony exports 37 | /******/ __webpack_require__.d = function(exports, name, getter) { 38 | /******/ if(!__webpack_require__.o(exports, name)) { 39 | /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); 40 | /******/ } 41 | /******/ }; 42 | /******/ 43 | /******/ // define __esModule on exports 44 | /******/ __webpack_require__.r = function(exports) { 45 | /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { 46 | /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); 47 | /******/ } 48 | /******/ Object.defineProperty(exports, '__esModule', { value: true }); 49 | /******/ }; 50 | /******/ 51 | /******/ // create a fake namespace object 52 | /******/ // mode & 1: value is a module id, require it 53 | /******/ // mode & 2: merge all properties of value into the ns 54 | /******/ // mode & 4: return value when already ns object 55 | /******/ // mode & 8|1: behave like require 56 | /******/ __webpack_require__.t = function(value, mode) { 57 | /******/ if(mode & 1) value = __webpack_require__(value); 58 | /******/ if(mode & 8) return value; 59 | /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; 60 | /******/ var ns = Object.create(null); 61 | /******/ __webpack_require__.r(ns); 62 | /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); 63 | /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); 64 | /******/ return ns; 65 | /******/ }; 66 | /******/ 67 | /******/ // getDefaultExport function for compatibility with non-harmony modules 68 | /******/ __webpack_require__.n = function(module) { 69 | /******/ var getter = module && module.__esModule ? 70 | /******/ function getDefault() { return module['default']; } : 71 | /******/ function getModuleExports() { return module; }; 72 | /******/ __webpack_require__.d(getter, 'a', getter); 73 | /******/ return getter; 74 | /******/ }; 75 | /******/ 76 | /******/ // Object.prototype.hasOwnProperty.call 77 | /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; 78 | /******/ 79 | /******/ // __webpack_public_path__ 80 | /******/ __webpack_require__.p = ""; 81 | /******/ 82 | /******/ 83 | /******/ // Load entry module and return exports 84 | /******/ return __webpack_require__(__webpack_require__.s = "./assets/plugin-call.js"); 85 | /******/ }) 86 | /************************************************************************/ 87 | /******/ ({ 88 | 89 | /***/ "./assets/plugin-call.js": 90 | /*!*******************************!*\ 91 | !*** ./assets/plugin-call.js ***! 92 | \*******************************/ 93 | /*! no exports provided */ 94 | /***/ (function(module, __webpack_exports__, __webpack_require__) { 95 | 96 | "use strict"; 97 | __webpack_require__.r(__webpack_exports__); 98 | /* harmony import */ var sketch_module_web_view_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! sketch-module-web-view/client */ "./node_modules/sketch-module-web-view/client.js"); 99 | /* harmony import */ var sketch_module_web_view_client__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(sketch_module_web_view_client__WEBPACK_IMPORTED_MODULE_0__); 100 | /* 101 | * Copyright 2018 Google Inc. 102 | * 103 | * Licensed under the Apache License, Version 2.0 (the "License"); 104 | * you may not use this file except in compliance with the License. 105 | * You may obtain a copy of the License at 106 | * 107 | * http://www.apache.org/licenses/LICENSE-2.0 108 | * 109 | * Unless required by applicable law or agreed to in writing, software 110 | * distributed under the License is distributed on an "AS IS" BASIS, 111 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 112 | * See the License for the specific language governing permissions and 113 | * limitations under the License. 114 | */ 115 | 116 | window['pluginCall'] = sketch_module_web_view_client__WEBPACK_IMPORTED_MODULE_0___default.a; 117 | 118 | /***/ }), 119 | 120 | /***/ "./node_modules/sketch-module-web-view/client.js": 121 | /*!*******************************************************!*\ 122 | !*** ./node_modules/sketch-module-web-view/client.js ***! 123 | \*******************************************************/ 124 | /*! no static exports found */ 125 | /***/ (function(module, exports, __webpack_require__) { 126 | 127 | var CONSTANTS = __webpack_require__(/*! ./lib/constants */ "./node_modules/sketch-module-web-view/lib/constants.js") 128 | 129 | module.exports = function(actionName) { 130 | if (!actionName) { 131 | throw new Error('missing action name') 132 | } 133 | window.webkit.messageHandlers[CONSTANTS.JS_BRIDGE].postMessage( 134 | JSON.stringify([].slice.call(arguments))) 135 | } 136 | 137 | 138 | /***/ }), 139 | 140 | /***/ "./node_modules/sketch-module-web-view/lib/constants.js": 141 | /*!**************************************************************!*\ 142 | !*** ./node_modules/sketch-module-web-view/lib/constants.js ***! 143 | \**************************************************************/ 144 | /*! no static exports found */ 145 | /***/ (function(module, exports) { 146 | 147 | module.exports = { 148 | JS_BRIDGE: '__skpm_sketchBridge', 149 | } 150 | 151 | 152 | /***/ }) 153 | 154 | /******/ }); 155 | //# sourceMappingURL=plugin-call.js.map -------------------------------------------------------------------------------- /symbol-browser.sketchplugin/Contents/Resources/plugin-call.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./assets/plugin-call.js","webpack:///./node_modules/sketch-module-web-view/client.js","webpack:///./node_modules/sketch-module-web-view/lib/constants.js"],"names":["window","pluginCall"],"mappings":";AAAA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,kDAA0C,gCAAgC;AAC1E;AACA;;AAEA;AACA;AACA;AACA,gEAAwD,kBAAkB;AAC1E;AACA,yDAAiD,cAAc;AAC/D;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAyC,iCAAiC;AAC1E,wHAAgH,mBAAmB,EAAE;AACrI;AACA;;AAEA;AACA;AACA;AACA,mCAA2B,0BAA0B,EAAE;AACvD,yCAAiC,eAAe;AAChD;AACA;AACA;;AAEA;AACA,8DAAsD,+DAA+D;;AAErH;AACA;;;AAGA;AACA;;;;;;;;;;;;;AClFA;AAAA;AAAA;AAAA;;;;;;;;;;;;;;;AAgBA;AACAA,MAAM,CAAC,YAAD,CAAN,GAAuBC,oEAAvB,C;;;;;;;;;;;ACjBA,gBAAgB,mBAAO,CAAC,+EAAiB;;AAEzC;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;ACRA;AACA;AACA","file":"plugin-call.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = \"./assets/plugin-call.js\");\n","/*\n * Copyright 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport pluginCall from 'sketch-module-web-view/client';\nwindow['pluginCall'] = pluginCall;\n","var CONSTANTS = require('./lib/constants')\n\nmodule.exports = function(actionName) {\n if (!actionName) {\n throw new Error('missing action name')\n }\n window.webkit.messageHandlers[CONSTANTS.JS_BRIDGE].postMessage(\n JSON.stringify([].slice.call(arguments)))\n}\n","module.exports = {\n JS_BRIDGE: '__skpm_sketchBridge',\n}\n"],"sourceRoot":""} -------------------------------------------------------------------------------- /symbol-browser.sketchplugin/Contents/Resources/sketch-file-outlined.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /symbol-browser.sketchplugin/Contents/Resources/sketch-file.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /symbol-browser.sketchplugin/Contents/Resources/symbol-browser.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pratikjshah/symbol-browser/22c21b15f912e13ab66c71a9194df8e03eac00f8/symbol-browser.sketchplugin/Contents/Resources/symbol-browser.png -------------------------------------------------------------------------------- /symbol-browser.sketchplugin/Contents/Resources/user.config: -------------------------------------------------------------------------------- 1 | {"localUpdateTime":1549004646054,"localVersion":"2.1.1","isUpdateAvailable":false,"name":"Symbol Browser"} -------------------------------------------------------------------------------- /symbol-browser.sketchplugin/Contents/Sketch/handler.js: -------------------------------------------------------------------------------- 1 | var that = this; 2 | function __skpm_run (key, context) { 3 | that.context = context; 4 | 5 | var exports = 6 | /******/ (function(modules) { // webpackBootstrap 7 | /******/ // The module cache 8 | /******/ var installedModules = {}; 9 | /******/ 10 | /******/ // The require function 11 | /******/ function __webpack_require__(moduleId) { 12 | /******/ 13 | /******/ // Check if module is in cache 14 | /******/ if(installedModules[moduleId]) { 15 | /******/ return installedModules[moduleId].exports; 16 | /******/ } 17 | /******/ // Create a new module (and put it into the cache) 18 | /******/ var module = installedModules[moduleId] = { 19 | /******/ i: moduleId, 20 | /******/ l: false, 21 | /******/ exports: {} 22 | /******/ }; 23 | /******/ 24 | /******/ // Execute the module function 25 | /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); 26 | /******/ 27 | /******/ // Flag the module as loaded 28 | /******/ module.l = true; 29 | /******/ 30 | /******/ // Return the exports of the module 31 | /******/ return module.exports; 32 | /******/ } 33 | /******/ 34 | /******/ 35 | /******/ // expose the modules object (__webpack_modules__) 36 | /******/ __webpack_require__.m = modules; 37 | /******/ 38 | /******/ // expose the module cache 39 | /******/ __webpack_require__.c = installedModules; 40 | /******/ 41 | /******/ // define getter function for harmony exports 42 | /******/ __webpack_require__.d = function(exports, name, getter) { 43 | /******/ if(!__webpack_require__.o(exports, name)) { 44 | /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); 45 | /******/ } 46 | /******/ }; 47 | /******/ 48 | /******/ // define __esModule on exports 49 | /******/ __webpack_require__.r = function(exports) { 50 | /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { 51 | /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); 52 | /******/ } 53 | /******/ Object.defineProperty(exports, '__esModule', { value: true }); 54 | /******/ }; 55 | /******/ 56 | /******/ // create a fake namespace object 57 | /******/ // mode & 1: value is a module id, require it 58 | /******/ // mode & 2: merge all properties of value into the ns 59 | /******/ // mode & 4: return value when already ns object 60 | /******/ // mode & 8|1: behave like require 61 | /******/ __webpack_require__.t = function(value, mode) { 62 | /******/ if(mode & 1) value = __webpack_require__(value); 63 | /******/ if(mode & 8) return value; 64 | /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; 65 | /******/ var ns = Object.create(null); 66 | /******/ __webpack_require__.r(ns); 67 | /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); 68 | /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); 69 | /******/ return ns; 70 | /******/ }; 71 | /******/ 72 | /******/ // getDefaultExport function for compatibility with non-harmony modules 73 | /******/ __webpack_require__.n = function(module) { 74 | /******/ var getter = module && module.__esModule ? 75 | /******/ function getDefault() { return module['default']; } : 76 | /******/ function getModuleExports() { return module; }; 77 | /******/ __webpack_require__.d(getter, 'a', getter); 78 | /******/ return getter; 79 | /******/ }; 80 | /******/ 81 | /******/ // Object.prototype.hasOwnProperty.call 82 | /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; 83 | /******/ 84 | /******/ // __webpack_public_path__ 85 | /******/ __webpack_require__.p = ""; 86 | /******/ 87 | /******/ 88 | /******/ // Load entry module and return exports 89 | /******/ return __webpack_require__(__webpack_require__.s = "./src/handler.js"); 90 | /******/ }) 91 | /************************************************************************/ 92 | /******/ ({ 93 | 94 | /***/ "./node_modules/@skpm/timers/immediate.js": 95 | /*!************************************************!*\ 96 | !*** ./node_modules/@skpm/timers/immediate.js ***! 97 | \************************************************/ 98 | /*! no static exports found */ 99 | /***/ (function(module, exports, __webpack_require__) { 100 | 101 | /* globals coscript, sketch */ 102 | var timeout = __webpack_require__(/*! ./timeout */ "./node_modules/@skpm/timers/timeout.js") 103 | 104 | function setImmediate(func, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) { 105 | return timeout.setTimeout(func, 0, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) 106 | } 107 | 108 | function clearImmediate(id) { 109 | return timeout.clearTimeout(id) 110 | } 111 | 112 | module.exports = { 113 | setImmediate: setImmediate, 114 | clearImmediate: clearImmediate 115 | } 116 | 117 | 118 | /***/ }), 119 | 120 | /***/ "./node_modules/@skpm/timers/index.js": 121 | /*!********************************************!*\ 122 | !*** ./node_modules/@skpm/timers/index.js ***! 123 | \********************************************/ 124 | /*! no static exports found */ 125 | /***/ (function(module, exports, __webpack_require__) { 126 | 127 | var timeout = __webpack_require__(/*! ./timeout */ "./node_modules/@skpm/timers/timeout.js") 128 | var interval = __webpack_require__(/*! ./interval */ "./node_modules/@skpm/timers/interval.js") 129 | var immediate = __webpack_require__(/*! ./immediate */ "./node_modules/@skpm/timers/immediate.js") 130 | 131 | module.exports = { 132 | setTimeout: timeout.setTimeout, 133 | clearTimeout: timeout.clearTimeout, 134 | setImmediate: immediate.setImmediate, 135 | clearImmediate: immediate.clearImmediate, 136 | setInterval: interval.setInterval, 137 | clearInterval: interval.clearInterval 138 | } 139 | 140 | 141 | /***/ }), 142 | 143 | /***/ "./node_modules/@skpm/timers/interval.js": 144 | /*!***********************************************!*\ 145 | !*** ./node_modules/@skpm/timers/interval.js ***! 146 | \***********************************************/ 147 | /*! no static exports found */ 148 | /***/ (function(module, exports) { 149 | 150 | /* globals coscript, sketch */ 151 | var fibers = [] 152 | 153 | var setInterval = function (func, delay, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) { 154 | // fibers takes care of keeping coscript around 155 | var id = fibers.length 156 | fibers.push(coscript.scheduleWithRepeatingInterval_jsFunction( 157 | (delay || 0) / 1000, 158 | function () { 159 | func(param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) 160 | } 161 | )) 162 | return id 163 | } 164 | 165 | var clearInterval = function (id) { 166 | var interval = fibers[id] 167 | if (interval) { 168 | interval.cancel() // fibers takes care of keeping coscript around 169 | fibers[id] = undefined // garbage collect the fiber 170 | } 171 | } 172 | 173 | module.exports = { 174 | setInterval: setInterval, 175 | clearInterval: clearInterval 176 | } 177 | 178 | 179 | /***/ }), 180 | 181 | /***/ "./node_modules/@skpm/timers/timeout.js": 182 | /*!**********************************************!*\ 183 | !*** ./node_modules/@skpm/timers/timeout.js ***! 184 | \**********************************************/ 185 | /*! no static exports found */ 186 | /***/ (function(module, exports) { 187 | 188 | /* globals coscript */ 189 | var fibers = [] 190 | 191 | var setTimeout = function (func, delay, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) { 192 | // fibers takes care of keeping coscript around 193 | var id = fibers.length 194 | fibers.push(coscript.scheduleWithInterval_jsFunction( 195 | (delay || 0) / 1000, 196 | function () { 197 | func(param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) 198 | } 199 | )) 200 | return id 201 | } 202 | 203 | var clearTimeout = function (id) { 204 | var timeout = fibers[id] 205 | if (timeout) { 206 | timeout.cancel() // fibers takes care of keeping coscript around 207 | fibers[id] = undefined // garbage collect the fiber 208 | } 209 | } 210 | 211 | module.exports = { 212 | setTimeout: setTimeout, 213 | clearTimeout: clearTimeout 214 | } 215 | 216 | 217 | /***/ }), 218 | 219 | /***/ "./src/handler.js": 220 | /*!************************!*\ 221 | !*** ./src/handler.js ***! 222 | \************************/ 223 | /*! exports provided: onAction, onOpenDocument, checkForUpdate, openDocumentation, openSampleFile, reportIssue, aboutPratikShah, manageDailyUpdateCheck, manageManualUpdate, manageUpdate, init, showMsg, openUrlInBrowser, saveLocalData, readLocalData, networkRequest, trackEvent */ 224 | /***/ (function(module, __webpack_exports__, __webpack_require__) { 225 | 226 | "use strict"; 227 | __webpack_require__.r(__webpack_exports__); 228 | /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "onAction", function() { return onAction; }); 229 | /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "onOpenDocument", function() { return onOpenDocument; }); 230 | /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "checkForUpdate", function() { return checkForUpdate; }); 231 | /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "openDocumentation", function() { return openDocumentation; }); 232 | /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "openSampleFile", function() { return openSampleFile; }); 233 | /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reportIssue", function() { return reportIssue; }); 234 | /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "aboutPratikShah", function() { return aboutPratikShah; }); 235 | /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "manageDailyUpdateCheck", function() { return manageDailyUpdateCheck; }); 236 | /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "manageManualUpdate", function() { return manageManualUpdate; }); 237 | /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "manageUpdate", function() { return manageUpdate; }); 238 | /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "init", function() { return init; }); 239 | /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "showMsg", function() { return showMsg; }); 240 | /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "openUrlInBrowser", function() { return openUrlInBrowser; }); 241 | /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "saveLocalData", function() { return saveLocalData; }); 242 | /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readLocalData", function() { return readLocalData; }); 243 | /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "networkRequest", function() { return networkRequest; }); 244 | /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "trackEvent", function() { return trackEvent; }); 245 | /* harmony import */ var sketch__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! sketch */ "sketch"); 246 | /* harmony import */ var sketch__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(sketch__WEBPACK_IMPORTED_MODULE_0__); 247 | /* 248 | * Copyright 2019 Pratik Shah 249 | * 250 | * Licensed under the Apache License, Version 2.0 (the "License"); 251 | * you may not use this file except in compliance with the License. 252 | * You may obtain a copy of the License at 253 | * 254 | * http://www.apache.org/licenses/LICENSE-2.0 255 | * 256 | * Unless required by applicable law or agreed to in writing, software 257 | * distributed under the License is distributed on an "AS IS" BASIS, 258 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 259 | * See the License for the specific language governing permissions and 260 | * limitations under the License. 261 | */ 262 | 263 | var globalContext; 264 | var remoteManifestUrl = "https://raw.githubusercontent.com/pratikjshah/symbol-browser/master/symbol-browser.sketchplugin/Contents/Sketch/manifest.json"; 265 | var localDataPath; 266 | var userConfig; 267 | var pluginRoot; 268 | var hasResponseCame = false; 269 | 270 | var timeout = __webpack_require__(/*! @skpm/timers */ "./node_modules/@skpm/timers/index.js"); 271 | 272 | var UI = __webpack_require__(/*! sketch/ui */ "sketch/ui"); 273 | 274 | var Settings = __webpack_require__(/*! sketch/settings */ "sketch/settings"); // ===== Menu action handlers ======================== 275 | 276 | 277 | function onAction(context) {// console.log("Action: " + context.action); 278 | } 279 | function onOpenDocument(context) { 280 | globalContext = context; 281 | init(context); 282 | networkRequest(remoteManifestUrl, manageDailyUpdateCheck); 283 | trackEvent("onAction", "onOpenDocument", 1); 284 | } 285 | function checkForUpdate(context) { 286 | init(context); 287 | networkRequest(remoteManifestUrl, manageManualUpdate); 288 | trackEvent("checkForUpdate", "manualCheckForUpdate", 1); // context.document.showMessage("remoteManifest: " + remoteManifest.version); 289 | } // ===== Other functions ========================== 290 | 291 | function openDocumentation(context) { 292 | init(context); 293 | openUrlInBrowser("http://symbol-browser.pratikshah.website/#faq"); 294 | } 295 | function openSampleFile(context) { 296 | init(context); // openUrlInBrowser("https://sketch.cloud/s/DVnWq"); 297 | 298 | openUrlInBrowser("https://www.sketch.com/s/f577ec9e-127a-4c5a-bd26-22ba9ddb64f5"); 299 | } 300 | function reportIssue(context) { 301 | init(context); 302 | openUrlInBrowser("https://github.com/pratikjshah/symbol-browser/issues"); 303 | } 304 | function aboutPratikShah(context) { 305 | init(context); 306 | openUrlInBrowser("http://pratikshah.website"); 307 | } 308 | function manageDailyUpdateCheck(remoteManifest) { 309 | var isDailyCheck = true; 310 | manageUpdate(remoteManifest, isDailyCheck); 311 | } 312 | function manageManualUpdate(remoteManifest) { 313 | var isDailyCheck = false; 314 | manageUpdate(remoteManifest, isDailyCheck); 315 | } 316 | function manageUpdate(remoteManifest, isDailyCheck) { 317 | // console.log("userConfig.localVersion: "+ userConfig.localVersion + " | remoteManifest.version: " + remoteManifest.version); 318 | 319 | /*if (userConfig.localVersion != remoteManifest.version) { 320 | showMsg(userConfig.name + ": "+ userConfig.localVersion + " is out of date! Please check for updates."); 321 | }*/ 322 | var localVersion = globalContext.plugin.version(); 323 | 324 | if (remoteManifest.version) { 325 | if (localVersion === remoteManifest.version) { 326 | if (!isDailyCheck) { 327 | // globalContext.document.showMessage("🤘Yo🤘! You are using the latest version of " + remoteManifest.name); 328 | UI.message("🤘Yo🤘! You are using the latest version of " + remoteManifest.name); 329 | Settings.setSettingForKey('hasUpdates', false); // console.log("🤘Yo🤘! You are using the latest version of " + remoteManifest.name); 330 | // localStorage.setItem("hasUpdates", false); 331 | } 332 | 333 | setUpdateCheckDayOnTomorrow(); 334 | } else { 335 | // globalContext.document.showMessage("Hey👋! New version of " + remoteManifest.name + " is available!"); 336 | UI.message("Hey👋! New version of " + remoteManifest.name + " is available!"); 337 | Settings.setSettingForKey('hasUpdates', true); // localStorage.setItem("hasUpdates", true); 338 | // console.log("Hey👋! New version of " + remoteManifest.name + " is available!"); 339 | //showAvailableUpdateDialog(); 340 | 341 | setUpdateCheckDayOnTomorrow(); 342 | } 343 | } else { 344 | //globalContext.document.showMessage("can not check:"); 345 | //showAvailableUpdateDialog(); 346 | setUpdateCheckDayOnTomorrow(); 347 | } 348 | } 349 | 350 | function setUpdateCheckDayOnTomorrow() { 351 | var newTime = new Date(); 352 | newTime.setDate(newTime.getDate() + 1); 353 | userConfig.localUpdateTime = newTime.getTime(); 354 | saveLocalData(userConfig, localDataPath); 355 | } // ===== Dialog functions ========================== 356 | 357 | 358 | function showAvailableUpdateDialog() { 359 | var window = createDownloadWindow(); 360 | var alert = window[0]; // When “Ok” is clicked 361 | 362 | var response = alert.runModal(); 363 | 364 | if (response == "1000") { 365 | //globalContext.document.showMessage("Go to download"); 366 | openUrlInBrowser("https://github.com/pratikjshah/symbol-browser/releases/latest/download/symbol-browser.sketchplugin.zip"); 367 | } else { 368 | //globalContext.document.showMessage("Check later"); 369 | setUpdateCheckDayOnTomorrow(); 370 | } 371 | } // ===== Helper functions ========================== 372 | 373 | 374 | function init(context) { 375 | globalContext = context; 376 | pluginRoot = globalContext.scriptPath.stringByDeletingLastPathComponent().stringByDeletingLastPathComponent().stringByDeletingLastPathComponent(); 377 | localDataPath = pluginRoot + "/Contents/Resources/user.config"; 378 | userConfig = readLocalData(localDataPath); 379 | var newTime = new Date(); 380 | 381 | if (userConfig.localUpdateTime < newTime.getTime()) { 382 | trackEvent("checkForUpdate", "dailyCheckForUpdate", 1); 383 | networkRequest(remoteManifestUrl, manageDailyUpdateCheck); 384 | } 385 | /*var remoteManifest = getRemoteJson(remoteManifestUrl); 386 | if (userConfig.localVersion != remoteManifest.version) { 387 | showMsg(userConfig.name + ": "+ userConfig.localVersion + " is out of date! Please check for updates."); 388 | } 389 | setUpdateCheckDayOnTomorrow();*/ 390 | 391 | } 392 | function showMsg(msg) { 393 | // globalContext.document.showMessage(msg); 394 | console.log("in showMsg"); 395 | console.log(msg); 396 | } 397 | function openUrlInBrowser(url) { 398 | NSWorkspace.sharedWorkspace().openURL(NSURL.URLWithString(url)); 399 | trackEvent("openUrlInBrowser", url, 1); 400 | } 401 | function saveLocalData(data, path) { 402 | /*var string = [NSString stringWithFormat: "%@", JSON.stringify(data)]; 403 | [string writeToFile: path atomically: true encoding: NSUTF8StringEncoding error: nil];*/ 404 | data = JSON.stringify(data); 405 | var text = NSString.stringWithFormat("%@", data); 406 | var file = NSString.stringWithFormat("%@", path); 407 | return text.writeToFile_atomically_encoding_error(file, true, NSUTF8StringEncoding, null); 408 | } 409 | function readLocalData(path) { 410 | if (NSFileManager.defaultManager().fileExistsAtPath(path)) { 411 | var string = NSString.stringWithContentsOfFile_encoding_error(path, 4, nil); 412 | string = string.replace(/(\r\n|\n|\r)/gm, ""); 413 | var data = JSON.parse(string); 414 | return data; 415 | } 416 | } 417 | function networkRequest(url, callBackFun) { 418 | /* 419 | // console.log("in networkRequest: \n" + url + " \n " + callBackFun); 420 | return fetch(url) 421 | .then(function (response) { 422 | if (!response.ok) { 423 | throw Error(response.statusText); 424 | } 425 | return response; 426 | }) 427 | .then(function (response) { 428 | return response.json(); 429 | }) 430 | .then(function (result) { 431 | console.log('Response Params: \n url: ' + url + " \n callBackFun: " + callBackFun); 432 | console.log(result); 433 | if(callBackFun !== 'undefined') { 434 | callBackFun(result); 435 | } 436 | return result; 437 | }) 438 | .catch(function (error) { 439 | console.log('Params: \n url: ' + url + " \n callBackFun: " + callBackFun); 440 | console.log('Looks like there was a problem: \n', error); 441 | }); 442 | */ 443 | try { 444 | var url = NSURL.URLWithString("" + url); 445 | var data = NSData.dataWithContentsOfURL(url); 446 | var json = NSJSONSerialization.JSONObjectWithData_options_error(data, 0, nil); // log("parsed data / json"); 447 | // log(json); 448 | // console.log('Params: \n url: ' + url + " \n callBackFun: " + callBackFun); 449 | 450 | callBackFun(json); 451 | } catch (e) { 452 | log("Exception: " + e); 453 | } 454 | } 455 | function trackEvent(action, label, value) { 456 | /* 457 | var kUUIDKey = 'google.analytics.uuid' 458 | var uuid = NSUserDefaults.standardUserDefaults().objectForKey(kUUIDKey) 459 | if (!uuid) { 460 | uuid = NSUUID.UUID().UUIDString() 461 | NSUserDefaults.standardUserDefaults().setObject_forKey(uuid, kUUIDKey) 462 | } 463 | var tid = "UA-64818389-8"; 464 | var cid = uuid; 465 | var ds = "Sketch-" + NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString"); 466 | var baseURL = "https://www.google-analytics.com/debug/collect?v=1&ds=" + ds + "&t=event&tid=" + tid + "&cid=" + cid; 467 | baseURL = "https://www.google-analytics.com/collect?v=1&ds=" + ds + "&t=event&tid=" + tid + "&cid=" + cid; 468 | var version = context.plugin.version().UTF8String(); 469 | var trackingURL = baseURL + "&ec=SketchSymbolBrowser-" + version + "&ea=" + action + "&el=" + label + "&ev=" + value; 470 | // networkRequest(trackingURL); 471 | */ 472 | // console.log("globalContext"); 473 | // console.log(globalContext); 474 | var trackingID = "UA-64818389-8"; 475 | var userDefaults = NSUserDefaults.standardUserDefaults(); 476 | var uuidKey = "google.analytics.uuid"; 477 | var uuid = userDefaults.objectForKey(uuidKey); 478 | 479 | if (!uuid) { 480 | uuid = NSUUID.UUID().UUIDString(); 481 | userDefaults.setObject_forKey(uuid, uuidKey); 482 | userDefaults.synchronize(); 483 | } 484 | 485 | var appName = encodeURI(globalContext.plugin.name()), 486 | appId = globalContext.plugin.identifier(), 487 | appVersion = globalContext.plugin.version(); 488 | var url = "https://www.google-analytics.com/collect?v=1"; // Tracking ID 489 | 490 | url += "&tid=" + trackingID; // Source 491 | 492 | url += "&ds=sketch" + MSApplicationMetadata.metadata().appVersion; // Client ID 493 | 494 | url += "&cid=" + uuid; // User GEO location 495 | 496 | url += "&geoid=" + NSLocale.currentLocale().countryCode(); // User language 497 | 498 | url += "&ul=" + NSLocale.currentLocale().localeIdentifier().toLowerCase(); // pageview, screenview, event, transaction, item, social, exception, timing 499 | 500 | url += "&t=event"; // App Name 501 | 502 | url += "&an=" + appName; // App ID 503 | 504 | url += "&aid=" + appId; // App Version 505 | 506 | url += "&av=" + appVersion; // Event category 507 | 508 | url += "&ec=" + encodeURI("SketchSymbolBrowser-" + appVersion); // Event action 509 | // url += "&ea=" + encodeURI(eventAction); 510 | 511 | url += "&ea=" + encodeURI(action); // Event label 512 | // if (eventLabel) { 513 | // url += "&el=" + encodeURI(eventLabel); 514 | // } 515 | 516 | url += "&el=" + encodeURI(label); // Event value 517 | // if (eventValue) { 518 | // url += "&ev=" + encodeURI(eventValue); 519 | // } 520 | 521 | url += "&ev=" + encodeURI(value); // console.log("new ga url: " + url); 522 | 523 | var session = NSURLSession.sharedSession(); 524 | var task = session.dataTaskWithURL(NSURL.URLWithString(NSString.stringWithString(url))); 525 | task.resume(); 526 | } 527 | 528 | /***/ }), 529 | 530 | /***/ "sketch": 531 | /*!*************************!*\ 532 | !*** external "sketch" ***! 533 | \*************************/ 534 | /*! no static exports found */ 535 | /***/ (function(module, exports) { 536 | 537 | module.exports = require("sketch"); 538 | 539 | /***/ }), 540 | 541 | /***/ "sketch/settings": 542 | /*!**********************************!*\ 543 | !*** external "sketch/settings" ***! 544 | \**********************************/ 545 | /*! no static exports found */ 546 | /***/ (function(module, exports) { 547 | 548 | module.exports = require("sketch/settings"); 549 | 550 | /***/ }), 551 | 552 | /***/ "sketch/ui": 553 | /*!****************************!*\ 554 | !*** external "sketch/ui" ***! 555 | \****************************/ 556 | /*! no static exports found */ 557 | /***/ (function(module, exports) { 558 | 559 | module.exports = require("sketch/ui"); 560 | 561 | /***/ }) 562 | 563 | /******/ }); 564 | if (key === 'default' && typeof exports === 'function') { 565 | exports(context); 566 | } else { 567 | exports[key](context); 568 | } 569 | } 570 | that['onOpenDocument'] = __skpm_run.bind(this, 'onOpenDocument'); 571 | that['onRun'] = __skpm_run.bind(this, 'default'); 572 | that['openDocumentation'] = __skpm_run.bind(this, 'openDocumentation'); 573 | that['openSampleFile'] = __skpm_run.bind(this, 'openSampleFile'); 574 | that['reportIssue'] = __skpm_run.bind(this, 'reportIssue'); 575 | that['checkForUpdate'] = __skpm_run.bind(this, 'checkForUpdate'); 576 | that['aboutPratikShah'] = __skpm_run.bind(this, 'aboutPratikShah') 577 | 578 | //# sourceMappingURL=handler.js.map -------------------------------------------------------------------------------- /symbol-browser.sketchplugin/Contents/Sketch/handler.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"sources":["webpack://exports/webpack/bootstrap","webpack://exports/./node_modules/@skpm/timers/immediate.js","webpack://exports/./node_modules/@skpm/timers/index.js","webpack://exports/./node_modules/@skpm/timers/interval.js","webpack://exports/./node_modules/@skpm/timers/timeout.js","webpack://exports/./src/handler.js","webpack://exports/external \"sketch\"","webpack://exports/external \"sketch/settings\"","webpack://exports/external \"sketch/ui\""],"names":["globalContext","remoteManifestUrl","localDataPath","userConfig","pluginRoot","hasResponseCame","timeout","require","UI","Settings","onAction","context","onOpenDocument","init","networkRequest","manageDailyUpdateCheck","trackEvent","checkForUpdate","manageManualUpdate","openDocumentation","openUrlInBrowser","openSampleFile","reportIssue","aboutPratikShah","remoteManifest","isDailyCheck","manageUpdate","localVersion","plugin","version","message","name","setSettingForKey","setUpdateCheckDayOnTomorrow","newTime","Date","setDate","getDate","localUpdateTime","getTime","saveLocalData","showAvailableUpdateDialog","window","createDownloadWindow","alert","response","runModal","scriptPath","stringByDeletingLastPathComponent","readLocalData","showMsg","msg","console","log","url","NSWorkspace","sharedWorkspace","openURL","NSURL","URLWithString","data","path","JSON","stringify","text","NSString","stringWithFormat","file","writeToFile_atomically_encoding_error","NSUTF8StringEncoding","NSFileManager","defaultManager","fileExistsAtPath","string","stringWithContentsOfFile_encoding_error","nil","replace","parse","callBackFun","NSData","dataWithContentsOfURL","json","NSJSONSerialization","JSONObjectWithData_options_error","e","action","label","value","trackingID","userDefaults","NSUserDefaults","standardUserDefaults","uuidKey","uuid","objectForKey","NSUUID","UUID","UUIDString","setObject_forKey","synchronize","appName","encodeURI","appId","identifier","appVersion","MSApplicationMetadata","metadata","NSLocale","currentLocale","countryCode","localeIdentifier","toLowerCase","session","NSURLSession","sharedSession","task","dataTaskWithURL","stringWithString","resume"],"mappings":";;;;;;AAAA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,kDAA0C,gCAAgC;AAC1E;AACA;;AAEA;AACA;AACA;AACA,gEAAwD,kBAAkB;AAC1E;AACA,yDAAiD,cAAc;AAC/D;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAyC,iCAAiC;AAC1E,wHAAgH,mBAAmB,EAAE;AACrI;AACA;;AAEA;AACA;AACA;AACA,mCAA2B,0BAA0B,EAAE;AACvD,yCAAiC,eAAe;AAChD;AACA;AACA;;AAEA;AACA,8DAAsD,+DAA+D;;AAErH;AACA;;;AAGA;AACA;;;;;;;;;;;;AClFA;AACA,cAAc,mBAAO,CAAC,yDAAW;;AAEjC;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;;;;;;;;;;;ACdA,cAAc,mBAAO,CAAC,yDAAW;AACjC,eAAe,mBAAO,CAAC,2DAAY;AACnC,gBAAgB,mBAAO,CAAC,6DAAa;;AAErC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;ACXA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;;;;;;;;;;;AC1BA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;;;;;;;;;;;;AC1BA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;;;;;;;;;;;;;AAgBA;AAEA,IAAIA,aAAJ;AACA,IAAIC,iBAAiB,GAAG,+HAAxB;AACA,IAAIC,aAAJ;AACA,IAAIC,UAAJ;AACA,IAAIC,UAAJ;AACA,IAAIC,eAAe,GAAG,KAAtB;;AACA,IAAMC,OAAO,GAAGC,mBAAO,CAAC,0DAAD,CAAvB;;AACA,IAAIC,EAAE,GAAGD,mBAAO,CAAC,4BAAD,CAAhB;;AACA,IAAIE,QAAQ,GAAGF,mBAAO,CAAC,wCAAD,CAAtB,C,CAEA;;;AAEO,SAASG,QAAT,CAAkBC,OAAlB,EAA2B,CACjC;AACA;AAEM,SAASC,cAAT,CAAwBD,OAAxB,EAAiC;AACtCX,eAAa,GAAGW,OAAhB;AACDE,MAAI,CAACF,OAAD,CAAJ;AACGG,gBAAc,CAACb,iBAAD,EAAoBc,sBAApB,CAAd;AACAC,YAAU,CAAC,UAAD,EAAa,gBAAb,EAA+B,CAA/B,CAAV;AACH;AAEM,SAASC,cAAT,CAAwBN,OAAxB,EAAiC;AACvCE,MAAI,CAACF,OAAD,CAAJ;AACGG,gBAAc,CAACb,iBAAD,EAAoBiB,kBAApB,CAAd;AACAF,YAAU,CAAC,gBAAD,EAAmB,sBAAnB,EAA2C,CAA3C,CAAV,CAHoC,CAIpC;AACH,C,CAED;;AAEO,SAASG,iBAAT,CAA2BR,OAA3B,EAAoC;AAC1CE,MAAI,CAACF,OAAD,CAAJ;AACGS,kBAAgB,CAAC,+CAAD,CAAhB;AACH;AAEM,SAASC,cAAT,CAAwBV,OAAxB,EAAiC;AACvCE,MAAI,CAACF,OAAD,CAAJ,CADuC,CAEpC;;AACAS,kBAAgB,CAAC,+DAAD,CAAhB;AACH;AAEM,SAASE,WAAT,CAAqBX,OAArB,EAA8B;AACpCE,MAAI,CAACF,OAAD,CAAJ;AACGS,kBAAgB,CAAC,sDAAD,CAAhB;AACH;AAEM,SAASG,eAAT,CAAyBZ,OAAzB,EAAkC;AACxCE,MAAI,CAACF,OAAD,CAAJ;AACAS,kBAAgB,CAAC,2BAAD,CAAhB;AACA;AAEM,SAASL,sBAAT,CAAgCS,cAAhC,EAAgD;AACtD,MAAIC,YAAY,GAAG,IAAnB;AACAC,cAAY,CAACF,cAAD,EAAiBC,YAAjB,CAAZ;AACA;AAEM,SAASP,kBAAT,CAA4BM,cAA5B,EAA4C;AAClD,MAAIC,YAAY,GAAG,KAAnB;AACAC,cAAY,CAACF,cAAD,EAAiBC,YAAjB,CAAZ;AACA;AAEM,SAASC,YAAT,CAAsBF,cAAtB,EAAsCC,YAAtC,EAAoD;AAC1D;;AAEA;;;AAIG,MAAIE,YAAY,GAAG3B,aAAa,CAAC4B,MAAd,CAAqBC,OAArB,EAAnB;;AACA,MAAIL,cAAc,CAACK,OAAnB,EAA4B;AACxB,QAAIF,YAAY,KAAKH,cAAc,CAACK,OAApC,EAA6C;AAC5C,UAAG,CAACJ,YAAJ,EAAkB;AACjB;AACEjB,UAAE,CAACsB,OAAH,CAAW,iDAAiDN,cAAc,CAACO,IAA3E;AACAtB,gBAAQ,CAACuB,gBAAT,CAA0B,YAA1B,EAAwC,KAAxC,EAHe,CAIf;AACA;AACF;;AACAC,iCAA2B;AAC5B,KATD,MASO;AACL;AACAzB,QAAE,CAACsB,OAAH,CAAW,2BAA2BN,cAAc,CAACO,IAA1C,GAAiD,gBAA5D;AACAtB,cAAQ,CAACuB,gBAAT,CAA0B,YAA1B,EAAwC,IAAxC,EAHK,CAIL;AACA;AACA;;AACAC,iCAA2B;AAC5B;AACJ,GAnBD,MAmBO;AACL;AACA;AACAA,+BAA2B;AAC5B;AACJ;;AAED,SAASA,2BAAT,GAAuC;AACrC,MAAIC,OAAO,GAAG,IAAIC,IAAJ,EAAd;AACAD,SAAO,CAACE,OAAR,CAAgBF,OAAO,CAACG,OAAR,KAAoB,CAApC;AACAlC,YAAU,CAACmC,eAAX,GAA6BJ,OAAO,CAACK,OAAR,EAA7B;AACAC,eAAa,CAACrC,UAAD,EAAaD,aAAb,CAAb;AACD,C,CAED;;;AAEA,SAASuC,yBAAT,GAAqC;AACnC,MAAIC,MAAM,GAAGC,oBAAoB,EAAjC;AACA,MAAIC,KAAK,GAAGF,MAAM,CAAC,CAAD,CAAlB,CAFmC,CAGnC;;AACA,MAAIG,QAAQ,GAAGD,KAAK,CAACE,QAAN,EAAf;;AACA,MAAID,QAAQ,IAAI,MAAhB,EAAwB;AACtB;AACAzB,oBAAgB,CAAC,wGAAD,CAAhB;AACD,GAHD,MAGO;AACL;AACAa,+BAA2B;AAC5B;AACF,C,CAED;;;AAEO,SAASpB,IAAT,CAAcF,OAAd,EAAuB;AAC7BX,eAAa,GAAGW,OAAhB;AACAP,YAAU,GAAGJ,aAAa,CAAC+C,UAAd,CAAyBC,iCAAzB,GAA6DA,iCAA7D,GAAiGA,iCAAjG,EAAb;AACA9C,eAAa,GAAGE,UAAU,GAAG,iCAA7B;AACAD,YAAU,GAAG8C,aAAa,CAAC/C,aAAD,CAA1B;AAEA,MAAIgC,OAAO,GAAG,IAAIC,IAAJ,EAAd;;AACA,MAAIhC,UAAU,CAACmC,eAAX,GAA6BJ,OAAO,CAACK,OAAR,EAAjC,EAAoD;AACnDvB,cAAU,CAAC,gBAAD,EAAmB,qBAAnB,EAA0C,CAA1C,CAAV;AACAF,kBAAc,CAACb,iBAAD,EAAoBc,sBAApB,CAAd;AACA;AACD;;;;;;AAKA;AAEM,SAASmC,OAAT,CAAiBC,GAAjB,EAAsB;AAC5B;AACCC,SAAO,CAACC,GAAR,CAAY,YAAZ;AACAD,SAAO,CAACC,GAAR,CAAYF,GAAZ;AACD;AAEM,SAAS/B,gBAAT,CAA0BkC,GAA1B,EAA+B;AAClCC,aAAW,CAACC,eAAZ,GAA8BC,OAA9B,CAAsCC,KAAK,CAACC,aAAN,CAAoBL,GAApB,CAAtC;AACAtC,YAAU,CAAC,kBAAD,EAAqBsC,GAArB,EAA0B,CAA1B,CAAV;AACH;AAEM,SAASd,aAAT,CAAuBoB,IAAvB,EAA6BC,IAA7B,EAAmC;AACzC;;AAEAD,MAAI,GAAGE,IAAI,CAACC,SAAL,CAAeH,IAAf,CAAP;AACA,MAAII,IAAI,GAAGC,QAAQ,CAACC,gBAAT,CAA0B,IAA1B,EAAgCN,IAAhC,CAAX;AACA,MAAIO,IAAI,GAAGF,QAAQ,CAACC,gBAAT,CAA0B,IAA1B,EAAgCL,IAAhC,CAAX;AACA,SAAOG,IAAI,CAACI,qCAAL,CAA2CD,IAA3C,EAAiD,IAAjD,EAAuDE,oBAAvD,EAA6E,IAA7E,CAAP;AACA;AAEM,SAASpB,aAAT,CAAuBY,IAAvB,EAA6B;AAClC,MAAGS,aAAa,CAACC,cAAd,GAA+BC,gBAA/B,CAAgDX,IAAhD,CAAH,EAAyD;AACvD,QAAIY,MAAM,GAAGR,QAAQ,CAACS,uCAAT,CAAiDb,IAAjD,EAAsD,CAAtD,EAAyDc,GAAzD,CAAb;AACAF,UAAM,GAAGA,MAAM,CAACG,OAAP,CAAe,gBAAf,EAAgC,EAAhC,CAAT;AACA,QAAIhB,IAAI,GAAGE,IAAI,CAACe,KAAL,CAAWJ,MAAX,CAAX;AACA,WAAOb,IAAP;AACD;AACF;AAEM,SAAS9C,cAAT,CAAwBwC,GAAxB,EAA6BwB,WAA7B,EAA0C;AAE/C;;;;;;;;;;;;;;;;;;;;;;;;;AA6BE,MAAI;AACF,QAAIxB,GAAG,GAAGI,KAAK,CAACC,aAAN,CAAoB,KAAGL,GAAvB,CAAV;AACA,QAAIM,IAAI,GAAGmB,MAAM,CAACC,qBAAP,CAA6B1B,GAA7B,CAAX;AACA,QAAI2B,IAAI,GAAGC,mBAAmB,CAACC,gCAApB,CAAqDvB,IAArD,EAA2D,CAA3D,EAA8De,GAA9D,CAAX,CAHE,CAIF;AACA;AACA;;AACAG,eAAW,CAACG,IAAD,CAAX;AACD,GARD,CAQE,OAAMG,CAAN,EAAS;AACT/B,OAAG,CAAC,gBAAgB+B,CAAjB,CAAH;AACD;AACJ;AAEM,SAASpE,UAAT,CAAoBqE,MAApB,EAA4BC,KAA5B,EAAmCC,KAAnC,EAA0C;AAC7C;;;;;;;;;;;;;;;;AAmBA;AACA;AAEA,MAAIC,UAAU,GAAG,eAAjB;AACA,MAAIC,YAAY,GAAGC,cAAc,CAACC,oBAAf,EAAnB;AAEA,MAAIC,OAAO,GAAG,uBAAd;AACA,MAAIC,IAAI,GAAGJ,YAAY,CAACK,YAAb,CAA0BF,OAA1B,CAAX;;AACA,MAAI,CAACC,IAAL,EAAW;AACPA,QAAI,GAAGE,MAAM,CAACC,IAAP,GAAcC,UAAd,EAAP;AACAR,gBAAY,CAACS,gBAAb,CAA8BL,IAA9B,EAAoCD,OAApC;AACAH,gBAAY,CAACU,WAAb;AACH;;AAED,MAAIC,OAAO,GAAGC,SAAS,CAACrG,aAAa,CAAC4B,MAAd,CAAqBG,IAArB,EAAD,CAAvB;AAAA,MACIuE,KAAK,GAAGtG,aAAa,CAAC4B,MAAd,CAAqB2E,UAArB,EADZ;AAAA,MAEIC,UAAU,GAAGxG,aAAa,CAAC4B,MAAd,CAAqBC,OAArB,EAFjB;AAIA,MAAIyB,GAAG,GAAG,8CAAV,CAtC6C,CAuC7C;;AACAA,KAAG,IAAI,UAAUkC,UAAjB,CAxC6C,CAyC7C;;AACAlC,KAAG,IAAI,eAAemD,qBAAqB,CAACC,QAAtB,GAAiCF,UAAvD,CA1C6C,CA2C7C;;AACAlD,KAAG,IAAI,UAAUuC,IAAjB,CA5C6C,CA6C7C;;AACAvC,KAAG,IAAI,YAAYqD,QAAQ,CAACC,aAAT,GAAyBC,WAAzB,EAAnB,CA9C6C,CA+C7C;;AACAvD,KAAG,IAAI,SAASqD,QAAQ,CAACC,aAAT,GAAyBE,gBAAzB,GAA4CC,WAA5C,EAAhB,CAhD6C,CAiD7C;;AACAzD,KAAG,IAAI,UAAP,CAlD6C,CAmD7C;;AACAA,KAAG,IAAI,SAAS8C,OAAhB,CApD6C,CAqD7C;;AACA9C,KAAG,IAAI,UAAUgD,KAAjB,CAtD6C,CAuD7C;;AACAhD,KAAG,IAAI,SAASkD,UAAhB,CAxD6C,CAyD7C;;AACAlD,KAAG,IAAI,SAAS+C,SAAS,CAAC,yBAAyBG,UAA1B,CAAzB,CA1D6C,CA2D7C;AACA;;AACAlD,KAAG,IAAI,SAAS+C,SAAS,CAAChB,MAAD,CAAzB,CA7D6C,CA8D7C;AACA;AACA;AACA;;AACA/B,KAAG,IAAI,SAAS+C,SAAS,CAACf,KAAD,CAAzB,CAlE6C,CAmE7C;AACA;AACA;AACA;;AACAhC,KAAG,IAAI,SAAS+C,SAAS,CAACd,KAAD,CAAzB,CAvE6C,CAyE7C;;AAEA,MAAIyB,OAAO,GAAGC,YAAY,CAACC,aAAb,EAAd;AACA,MAAIC,IAAI,GAAGH,OAAO,CAACI,eAAR,CAAwB1D,KAAK,CAACC,aAAN,CAAoBM,QAAQ,CAACoD,gBAAT,CAA0B/D,GAA1B,CAApB,CAAxB,CAAX;AACA6D,MAAI,CAACG,MAAL;AACH,C;;;;;;;;;;;ACrTD,mC;;;;;;;;;;;ACAA,4C;;;;;;;;;;;ACAA,sC","file":"handler.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = \"./src/handler.js\");\n","/* globals coscript, sketch */\nvar timeout = require('./timeout')\n\nfunction setImmediate(func, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) {\n return timeout.setTimeout(func, 0, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10)\n}\n\nfunction clearImmediate(id) {\n return timeout.clearTimeout(id)\n}\n\nmodule.exports = {\n setImmediate: setImmediate,\n clearImmediate: clearImmediate\n}\n","var timeout = require('./timeout')\nvar interval = require('./interval')\nvar immediate = require('./immediate')\n\nmodule.exports = {\n setTimeout: timeout.setTimeout,\n clearTimeout: timeout.clearTimeout,\n setImmediate: immediate.setImmediate,\n clearImmediate: immediate.clearImmediate,\n setInterval: interval.setInterval,\n clearInterval: interval.clearInterval\n}\n","/* globals coscript, sketch */\nvar fibers = []\n\nvar setInterval = function (func, delay, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) {\n // fibers takes care of keeping coscript around\n var id = fibers.length\n fibers.push(coscript.scheduleWithRepeatingInterval_jsFunction(\n (delay || 0) / 1000,\n function () {\n func(param1, param2, param3, param4, param5, param6, param7, param8, param9, param10)\n }\n ))\n return id\n}\n\nvar clearInterval = function (id) {\n var interval = fibers[id]\n if (interval) {\n interval.cancel() // fibers takes care of keeping coscript around\n fibers[id] = undefined // garbage collect the fiber\n }\n}\n\nmodule.exports = {\n setInterval: setInterval,\n clearInterval: clearInterval\n}\n","/* globals coscript */\nvar fibers = []\n\nvar setTimeout = function (func, delay, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) {\n // fibers takes care of keeping coscript around\n var id = fibers.length\n fibers.push(coscript.scheduleWithInterval_jsFunction(\n (delay || 0) / 1000,\n function () {\n func(param1, param2, param3, param4, param5, param6, param7, param8, param9, param10)\n }\n ))\n return id\n}\n\nvar clearTimeout = function (id) {\n var timeout = fibers[id]\n if (timeout) {\n timeout.cancel() // fibers takes care of keeping coscript around\n fibers[id] = undefined // garbage collect the fiber\n }\n}\n\nmodule.exports = {\n setTimeout: setTimeout,\n clearTimeout: clearTimeout\n}\n","/*\n * Copyright 2019 Pratik Shah\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport sketch from 'sketch'\n\nvar globalContext;\nvar remoteManifestUrl = \"https://raw.githubusercontent.com/pratikjshah/symbol-browser/master/symbol-browser.sketchplugin/Contents/Sketch/manifest.json\";\nvar localDataPath;\nvar userConfig;\nvar pluginRoot;\nvar hasResponseCame = false;\nconst timeout = require('@skpm/timers');\nvar UI = require('sketch/ui');\nvar Settings = require('sketch/settings');\n\n// ===== Menu action handlers ========================\n\nexport function onAction(context) {\n\t// console.log(\"Action: \" + context.action);\n}\n\nexport function onOpenDocument(context) {\n globalContext = context;\n\tinit(context);\n networkRequest(remoteManifestUrl, manageDailyUpdateCheck);\n trackEvent(\"onAction\", \"onOpenDocument\", 1);\n}\n\nexport function checkForUpdate(context) {\n\tinit(context);\n networkRequest(remoteManifestUrl, manageManualUpdate);\n trackEvent(\"checkForUpdate\", \"manualCheckForUpdate\", 1);\n // context.document.showMessage(\"remoteManifest: \" + remoteManifest.version);\n}\n\n// ===== Other functions ==========================\n\nexport function openDocumentation(context) {\n\tinit(context);\n openUrlInBrowser(\"http://symbol-browser.pratikshah.website/#faq\");\n}\n\nexport function openSampleFile(context) {\n\tinit(context);\n // openUrlInBrowser(\"https://sketch.cloud/s/DVnWq\");\n openUrlInBrowser(\"https://www.sketch.com/s/f577ec9e-127a-4c5a-bd26-22ba9ddb64f5\");\n}\n\nexport function reportIssue(context) {\n\tinit(context);\n openUrlInBrowser(\"https://github.com/pratikjshah/symbol-browser/issues\");\n}\n\nexport function aboutPratikShah(context) {\n\tinit(context);\n\topenUrlInBrowser(\"http://pratikshah.website\");\n}\n\nexport function manageDailyUpdateCheck(remoteManifest) {\n\tvar isDailyCheck = true;\n\tmanageUpdate(remoteManifest, isDailyCheck);\n}\n\nexport function manageManualUpdate(remoteManifest) {\n\tvar isDailyCheck = false;\n\tmanageUpdate(remoteManifest, isDailyCheck);\n}\n\nexport function manageUpdate(remoteManifest, isDailyCheck) {\n\t// console.log(\"userConfig.localVersion: \"+ userConfig.localVersion + \" | remoteManifest.version: \" + remoteManifest.version);\n\n\t/*if (userConfig.localVersion != remoteManifest.version) {\n\t\tshowMsg(userConfig.name + \": \"+ userConfig.localVersion + \" is out of date! Please check for updates.\");\n\t}*/\n\n var localVersion = globalContext.plugin.version();\n if (remoteManifest.version) {\n if (localVersion === remoteManifest.version) {\n \tif(!isDailyCheck) {\n \t\t// globalContext.document.showMessage(\"🤘Yo🤘! You are using the latest version of \" + remoteManifest.name);\n UI.message(\"🤘Yo🤘! You are using the latest version of \" + remoteManifest.name);\n Settings.setSettingForKey('hasUpdates', false);\n // console.log(\"🤘Yo🤘! You are using the latest version of \" + remoteManifest.name);\n // localStorage.setItem(\"hasUpdates\", false);\n \t}\n setUpdateCheckDayOnTomorrow();\n } else {\n // globalContext.document.showMessage(\"Hey👋! New version of \" + remoteManifest.name + \" is available!\");\n UI.message(\"Hey👋! New version of \" + remoteManifest.name + \" is available!\");\n Settings.setSettingForKey('hasUpdates', true);\n // localStorage.setItem(\"hasUpdates\", true);\n // console.log(\"Hey👋! New version of \" + remoteManifest.name + \" is available!\");\n //showAvailableUpdateDialog();\n setUpdateCheckDayOnTomorrow();\n }\n } else {\n //globalContext.document.showMessage(\"can not check:\");\n //showAvailableUpdateDialog();\n setUpdateCheckDayOnTomorrow();\n }\n}\n\nfunction setUpdateCheckDayOnTomorrow() {\n var newTime = new Date();\n newTime.setDate(newTime.getDate() + 1);\n userConfig.localUpdateTime = newTime.getTime();\n saveLocalData(userConfig, localDataPath);\n}\n\n// ===== Dialog functions ==========================\n\nfunction showAvailableUpdateDialog() {\n var window = createDownloadWindow();\n var alert = window[0];\n // When “Ok” is clicked\n var response = alert.runModal();\n if (response == \"1000\") {\n //globalContext.document.showMessage(\"Go to download\");\n openUrlInBrowser(\"https://github.com/pratikjshah/symbol-browser/releases/latest/download/symbol-browser.sketchplugin.zip\");\n } else {\n //globalContext.document.showMessage(\"Check later\");\n setUpdateCheckDayOnTomorrow();\n }\n}\n\n// ===== Helper functions ==========================\n\nexport function init(context) {\n\tglobalContext = context;\n\tpluginRoot = globalContext.scriptPath.stringByDeletingLastPathComponent().stringByDeletingLastPathComponent().stringByDeletingLastPathComponent();\n\tlocalDataPath = pluginRoot + \"/Contents/Resources/user.config\";\n\tuserConfig = readLocalData(localDataPath);\n\n\tvar newTime = new Date();\n\tif (userConfig.localUpdateTime < newTime.getTime()) {\n\t\ttrackEvent(\"checkForUpdate\", \"dailyCheckForUpdate\", 1);\n\t\tnetworkRequest(remoteManifestUrl, manageDailyUpdateCheck);\n\t}\n\t/*var remoteManifest = getRemoteJson(remoteManifestUrl);\n\tif (userConfig.localVersion != remoteManifest.version) {\n\tshowMsg(userConfig.name + \": \"+ userConfig.localVersion + \" is out of date! Please check for updates.\");\n\t}\n\tsetUpdateCheckDayOnTomorrow();*/\n}\n\nexport function showMsg(msg) {\n\t// globalContext.document.showMessage(msg);\n console.log(\"in showMsg\");\n console.log(msg);\n}\n\nexport function openUrlInBrowser(url) {\n NSWorkspace.sharedWorkspace().openURL(NSURL.URLWithString(url));\n trackEvent(\"openUrlInBrowser\", url, 1);\n}\n\nexport function saveLocalData(data, path) {\n\t/*var string = [NSString stringWithFormat: \"%@\", JSON.stringify(data)];\n\t[string writeToFile: path atomically: true encoding: NSUTF8StringEncoding error: nil];*/\n\tdata = JSON.stringify(data);\n\tvar text = NSString.stringWithFormat(\"%@\", data);\n\tvar file = NSString.stringWithFormat(\"%@\", path);\n\treturn text.writeToFile_atomically_encoding_error(file, true, NSUTF8StringEncoding, null);\n}\n\nexport function readLocalData(path) {\n if(NSFileManager.defaultManager().fileExistsAtPath(path)){\n var string = NSString.stringWithContentsOfFile_encoding_error(path,4, nil);\n string = string.replace(/(\\r\\n|\\n|\\r)/gm,\"\");\n var data = JSON.parse(string);\n return data;\n }\n}\n\nexport function networkRequest(url, callBackFun) {\n\n /*\n\n\t// console.log(\"in networkRequest: \\n\" + url + \" \\n \" + callBackFun);\n\n\treturn fetch(url)\n\t .then(function (response) {\n\t\t\t if (!response.ok) {\n\t\t\t throw Error(response.statusText);\n\t\t\t }\n\t\t\t return response;\n\t\t\t})\n\t .then(function (response) {\n\t\t\t return response.json();\n\t\t\t})\n\t .then(function (result) {\n\t\t\t console.log('Response Params: \\n url: ' + url + \" \\n callBackFun: \" + callBackFun);\n\t\t\t console.log(result);\n\t\t\t if(callBackFun !== 'undefined') {\n\t\t\t \tcallBackFun(result);\n\t\t\t }\n\t\t\t return result;\n\t\t\t})\n\t .catch(function (error) {\n\t\t\t console.log('Params: \\n url: ' + url + \" \\n callBackFun: \" + callBackFun);\n\t\t\t console.log('Looks like there was a problem: \\n', error);\n\t\t\t});\n\n */\n\n try {\n var url = NSURL.URLWithString(\"\"+url);\n var data = NSData.dataWithContentsOfURL(url);\n var json = NSJSONSerialization.JSONObjectWithData_options_error(data, 0, nil);\n // log(\"parsed data / json\");\n // log(json);\n // console.log('Params: \\n url: ' + url + \" \\n callBackFun: \" + callBackFun);\n callBackFun(json);\n } catch(e) {\n log(\"Exception: \" + e);\n }\n}\n\nexport function trackEvent(action, label, value) {\n /*\n var kUUIDKey = 'google.analytics.uuid'\n var uuid = NSUserDefaults.standardUserDefaults().objectForKey(kUUIDKey)\n if (!uuid) {\n uuid = NSUUID.UUID().UUIDString()\n NSUserDefaults.standardUserDefaults().setObject_forKey(uuid, kUUIDKey)\n }\n\n var tid = \"UA-64818389-8\";\n var cid = uuid;\n var ds = \"Sketch-\" + NSBundle.mainBundle().objectForInfoDictionaryKey(\"CFBundleShortVersionString\");\n var baseURL = \"https://www.google-analytics.com/debug/collect?v=1&ds=\" + ds + \"&t=event&tid=\" + tid + \"&cid=\" + cid;\n baseURL = \"https://www.google-analytics.com/collect?v=1&ds=\" + ds + \"&t=event&tid=\" + tid + \"&cid=\" + cid;\n var version = context.plugin.version().UTF8String();\n\n var trackingURL = baseURL + \"&ec=SketchSymbolBrowser-\" + version + \"&ea=\" + action + \"&el=\" + label + \"&ev=\" + value;\n // networkRequest(trackingURL);\n */\n\n // console.log(\"globalContext\");\n // console.log(globalContext);\n\n var trackingID = \"UA-64818389-8\";\n var userDefaults = NSUserDefaults.standardUserDefaults();\n\n var uuidKey = \"google.analytics.uuid\";\n var uuid = userDefaults.objectForKey(uuidKey);\n if (!uuid) {\n uuid = NSUUID.UUID().UUIDString();\n userDefaults.setObject_forKey(uuid, uuidKey);\n userDefaults.synchronize();\n }\n\n var appName = encodeURI(globalContext.plugin.name()),\n appId = globalContext.plugin.identifier(),\n appVersion = globalContext.plugin.version();\n\n var url = \"https://www.google-analytics.com/collect?v=1\";\n // Tracking ID\n url += \"&tid=\" + trackingID;\n // Source\n url += \"&ds=sketch\" + MSApplicationMetadata.metadata().appVersion;\n // Client ID\n url += \"&cid=\" + uuid;\n // User GEO location\n url += \"&geoid=\" + NSLocale.currentLocale().countryCode();\n // User language\n url += \"&ul=\" + NSLocale.currentLocale().localeIdentifier().toLowerCase();\n // pageview, screenview, event, transaction, item, social, exception, timing\n url += \"&t=event\";\n // App Name\n url += \"&an=\" + appName;\n // App ID\n url += \"&aid=\" + appId;\n // App Version\n url += \"&av=\" + appVersion;\n // Event category\n url += \"&ec=\" + encodeURI(\"SketchSymbolBrowser-\" + appVersion);\n // Event action\n // url += \"&ea=\" + encodeURI(eventAction);\n url += \"&ea=\" + encodeURI(action);\n // Event label\n // if (eventLabel) {\n // url += \"&el=\" + encodeURI(eventLabel);\n // }\n url += \"&el=\" + encodeURI(label);\n // Event value\n // if (eventValue) {\n // url += \"&ev=\" + encodeURI(eventValue);\n // }\n url += \"&ev=\" + encodeURI(value);\n\n // console.log(\"new ga url: \" + url);\n\n var session = NSURLSession.sharedSession();\n var task = session.dataTaskWithURL(NSURL.URLWithString(NSString.stringWithString(url)));\n task.resume();\n}","module.exports = require(\"sketch\");","module.exports = require(\"sketch/settings\");","module.exports = require(\"sketch/ui\");"],"sourceRoot":""} -------------------------------------------------------------------------------- /symbol-browser.sketchplugin/Contents/Sketch/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": " 🔄 Symbol Browser", 3 | "description": "Better way to browse your Design System and UI Sticker sheet", 4 | "icon": "symbol-browser.png", 5 | "author": "Pratik Shah", 6 | "email": "hello@pratikshah.website", 7 | "appcast": "https://raw.githubusercontent.com/pratikjshah/symbol-browser/master/appcast.xml", 8 | "homepage": "http://symbol-browser.pratikshah.website/", 9 | "version": "3.5.2", 10 | "identifier": "website.pratikshah.symbol-browser", 11 | "compatibleVersion": "52", 12 | "bundleVersion": "1", 13 | "commands": [ 14 | { 15 | "script": "handler.js", 16 | "handlers": { 17 | "actions": { 18 | "OpenDocument": "onOpenDocument" 19 | } 20 | }, 21 | "name": "onOpenDocument", 22 | "identifier": "onOpenDocument" 23 | }, 24 | { 25 | "script": "commands.js", 26 | "handlers": { 27 | "run": "onShowStickers" 28 | }, 29 | "name": "🔍 View Design System", 30 | "shortcut": "cmd shift d", 31 | "identifier": "show_stickers", 32 | "description": "Show or hide Design System window.", 33 | "icon": "icon-menu.png" 34 | }, 35 | { 36 | "script": "commands.js", 37 | "handlers": { 38 | "run": "onClearCache" 39 | }, 40 | "name": "🧹 Clear Symbol Index", 41 | "identifier": "clear_cache", 42 | "description": "Clear the Symbol index for troubleshooting purposes.", 43 | "icon": "icon-menu.png" 44 | }, 45 | { 46 | "script": "handler.js", 47 | "handler": "openDocumentation", 48 | "shortcut": "", 49 | "name": "Create custom Symbol groups", 50 | "identifier": "openDocumentation", 51 | "description": "View Symtax guide for adding Custom sections", 52 | "icon": "icon-menu.png" 53 | }, 54 | { 55 | "script": "handler.js", 56 | "handler": "openSampleFile", 57 | "shortcut": "", 58 | "name": "Example Sketch Library", 59 | "identifier": "openSampleFile", 60 | "description": "Get Example Sketch Library and see what's possible!", 61 | "icon": "icon-menu.png" 62 | }, 63 | { 64 | "script": "handler.js", 65 | "handler": "reportIssue", 66 | "shortcut": "", 67 | "name": "Report issue", 68 | "identifier": "reportIssue" 69 | }, 70 | { 71 | "script": "handler.js", 72 | "handler": "checkForUpdate", 73 | "shortcut": "", 74 | "name": "Check for Plugin update", 75 | "identifier": "checkForUpdate" 76 | }, 77 | { 78 | "script": "handler.js", 79 | "handler": "aboutPratikShah", 80 | "shortcut": "", 81 | "name": "About Pratik Shah", 82 | "identifier": "aboutPratikShah" 83 | } 84 | ], 85 | "menu": { 86 | "items": [ 87 | "show_stickers", 88 | "-", 89 | "openSampleFile", 90 | "openDocumentation", 91 | "-", 92 | "clear_cache", 93 | "-", 94 | { 95 | "title": "More", 96 | "items": [ 97 | "reportIssue", 98 | "checkForUpdate", 99 | "-", 100 | "aboutPratikShah" 101 | ] 102 | } 103 | ], 104 | "title": " 🔄 Symbol Browser" 105 | }, 106 | "disableCocoaScriptPreprocessor": true 107 | } -------------------------------------------------------------------------------- /web/index.js: -------------------------------------------------------------------------------- 1 | const webpack = require('webpack'); 2 | const process = require('process'); 3 | 4 | 5 | module.exports = { 6 | build: () => new Promise((resolve, reject) => { 7 | makeInstance().run((err, stats) => { 8 | printWebpackStats(err, stats); 9 | resolve(); 10 | }); 11 | }), 12 | watch: (cb) => { 13 | makeInstance().watch({}, (err, stats) => { 14 | printWebpackStats(err, stats); 15 | if (cb) { 16 | cb(err, stats); 17 | } 18 | }); 19 | }, 20 | }; 21 | 22 | 23 | function makeInstance() { 24 | let oldcwd = process.cwd(); 25 | process.chdir(__dirname); 26 | let config = require('./webpack.config.js'); 27 | let inst = webpack(config); 28 | process.chdir(oldcwd); 29 | return inst; 30 | } 31 | 32 | function printWebpackStats(err, stats) { 33 | if (err) { 34 | console.error(err); 35 | } 36 | if (stats) { 37 | console.log(stats.toString({ 38 | modules: false, 39 | colors: true, 40 | })); 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /web/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "symbol-browser", 3 | "version": "3.5.1", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "start:dev": "webpack-dev-server", 8 | "build": "NODE_ENV=production webpack-cli", 9 | "watch": "NODE_ENV=production webpack-cli --watch" 10 | }, 11 | "private": true, 12 | "license": "Apache-2.0", 13 | "devDependencies": { 14 | "css-loader": "^0.28.11", 15 | "extract-loader": "^2.0.1", 16 | "file-loader": "^1.1.11", 17 | "html-loader": "^0.5.5", 18 | "image-webpack-loader": "^4.2.0", 19 | "json-loader": "^0.5.7", 20 | "node-sass": "^4.8.3", 21 | "node-sass-asset-functions": "^0.1.0", 22 | "sass-loader": "^7.0.1", 23 | "resolve-url-loader": "^3.0.0", 24 | "svg-sprite-loader": "^4.1.3", 25 | "webpack-cli": "^2.0.14", 26 | "webpack-dev-server": "^3.1.3" 27 | }, 28 | "dependencies": { 29 | "event-emitter": "^0.3.5", 30 | "jquery": "^3.3.1", 31 | "vue": "^2.5.16" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /web/src/.gitignore: -------------------------------------------------------------------------------- 1 | _stub-sticker-index.json -------------------------------------------------------------------------------- /web/src/_stub-sticker-index.json.readme.md: -------------------------------------------------------------------------------- 1 | To make rapid development on the web page easier (outside of Sketch, preview in the brower): 2 | 3 | 1. Run the plugin with actual stickers in one of your libraries. 4 | 5 | 2. Grab the relevant `index.json` file from `~/Library/Caches///index.json`. 6 | This is the cached sticker index. That file should look something like: 7 | 8 | ``` 9 | { 10 | "sections": [ 11 | ... 12 | ], 13 | } 14 | ``` 15 | 16 | 3. Copy the file into this folder and rename it to `_stub-sticker-index.json`. 17 | 18 | 4. Wrap the contents in: 19 | 20 | ``` 21 | { 22 | "libraries": [ 23 | 24 | ] 25 | } 26 | ``` -------------------------------------------------------------------------------- /web/src/client.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | const ee = require('event-emitter'); 18 | 19 | let __layerImages__ = {}; 20 | let __layerImageResolves__ = {}; 21 | 22 | class StickersClient { 23 | getStickerImageUrl(stickerId) { 24 | return new Promise((resolve, reject) => { 25 | if (__layerImages__[stickerId]) { 26 | resolve(__layerImages__[stickerId]); 27 | } else if (__layerImageResolves__[stickerId]) { 28 | // already sent request to client, just tack on this resolve() fn 29 | __layerImageResolves__[stickerId].push(resolve); 30 | } else { 31 | // no request for this layer sent yet 32 | __layerImageResolves__[stickerId] = [resolve]; 33 | pluginCall('requestLayerImageUrl', stickerId, '__onLayerImageAvailable__'); 34 | } 35 | }); 36 | } 37 | 38 | __onLayerImageAvailable__(stickerId, url) { 39 | __layerImages__[stickerId] = url; 40 | (__layerImageResolves__[stickerId] || []).forEach(resolve => resolve(url)); 41 | } 42 | 43 | init() { 44 | pluginCall('loadStickerIndex', '__onLoadComplete__', '__onLoadProgress__'); 45 | } 46 | 47 | close() { 48 | pluginCall('close'); 49 | } 50 | 51 | openUrl(url) { 52 | pluginCall('openUrl', url); 53 | } 54 | 55 | startDragging(stickerId, rect) { 56 | pluginCall('startDragging', stickerId, rect); 57 | } 58 | 59 | addLibraryColors(libraryId) { 60 | pluginCall('addLibraryColors', libraryId); 61 | } 62 | }; 63 | 64 | ee(StickersClient.prototype); 65 | 66 | let instance = new StickersClient(); 67 | 68 | window.__onLayerImageAvailable__ = instance.__onLayerImageAvailable__.bind(instance); 69 | 70 | window.__onLoadProgress__ = f => { 71 | instance.emit('load-progress', f); 72 | }; 73 | 74 | window.__onLoadComplete__ = stickerIndex => { 75 | instance.stickerIndex = stickerIndex; 76 | instance.emit('load-progress', 1); 77 | instance.emit('loaded', stickerIndex); 78 | }; 79 | 80 | 81 | module.exports = instance; -------------------------------------------------------------------------------- /web/src/components/button/button.scss: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | @mixin button($size: small, 18 | $level: secondary, 19 | $color: var(--theme-color-button), 20 | $colorHover: var(--theme-color-button-hover), 21 | $colorActive: var(--theme-color-button-active), 22 | $colorFg: var(--theme-color-button-fg)) { 23 | --color: #{$color}; 24 | display: flex; 25 | align-items: center; 26 | color: var(--color); 27 | font-weight: 500; 28 | text-decoration: none; 29 | border-radius: 4px; 30 | border: 0; 31 | cursor: pointer; 32 | outline: 0; 33 | 34 | @if $size == small { 35 | @include type-body-3; 36 | padding: 6px 12px; 37 | 38 | .svg-icon { 39 | width: 20px; 40 | height: 20px; 41 | } 42 | } 43 | @else if $size == large { 44 | @include type-body-1; 45 | padding: 10px 16px; 46 | } 47 | 48 | .svg-icon:first-child:not(:last-child) { 49 | margin-right: 4px; 50 | } 51 | .svg-icon:last-child:not(:first-child) { 52 | margin-left: 4px; 53 | } 54 | 55 | @if $level == secondary { 56 | box-shadow: 0 0 0 1px var(--color) inset; 57 | background-color: transparent; 58 | 59 | &:hover, 60 | &:focus, 61 | &:active { 62 | color: $colorFg; 63 | background-color: var(--color); 64 | } 65 | 66 | &:focus, 67 | &:active { 68 | --color: #{$colorHover}; 69 | } 70 | } 71 | @else if $level == flat { 72 | background-color: transparent; 73 | 74 | &:hover { 75 | --color: #{$colorHover}; 76 | } 77 | 78 | &:focus, 79 | &:active { 80 | --color: #{$colorActive}; 81 | } 82 | } 83 | @else if $level == primary { 84 | color: $colorFg; 85 | background-color: var(--color); 86 | 87 | &:hover { 88 | --color: #{$colorHover}; 89 | } 90 | 91 | &:focus, 92 | &:active { 93 | --color: #{$colorActive}; 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /web/src/components/zerostate/zerostate.scss: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | @import '../button/button'; 18 | 19 | .zero-state { 20 | display: flex; 21 | flex-direction: column; 22 | align-items: center; 23 | justify-content: center; 24 | padding: 96px 0; 25 | flex: 1 0 auto; 26 | 27 | &__text { 28 | @include type-headline-2; 29 | color: var(--theme-color-fg-tertiary); 30 | margin-top: 40px; 31 | max-width: 400px; 32 | text-align: center; 33 | 34 | em { 35 | font-style: normal; 36 | font-weight: 500; 37 | color: var(--theme-color-fg-primary); 38 | } 39 | } 40 | 41 | &__link { 42 | @include button(large, primary); 43 | margin-top: 24px; 44 | } 45 | } 46 | 47 | @mixin zero-state-image($name) { 48 | .zero-state__image { 49 | $src: #{'./images/' + $name + '@2x.png'}; 50 | background-image: url($src); 51 | background-size: cover; 52 | background-position: 50% 50%; 53 | width: 100%; 54 | max-width: image-width($src) / 2; 55 | height: image-height($src) / 2; 56 | 57 | body[is-dark-theme] & { 58 | $src: #{'./images/' + $name + '-dark@2x.png'}; 59 | background-image: url($src); 60 | max-width: image-width($src) / 2; 61 | height: image-height($src) / 2; 62 | } 63 | } 64 | } -------------------------------------------------------------------------------- /web/src/icons/add_circle_outline.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /web/src/icons/arrow_back_ios.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /web/src/icons/check.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /web/src/icons/search.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /web/src/index.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // trigger copying of related assets 18 | require('file-loader?name=[name].[ext]!./index.html'); 19 | 20 | // libraries 21 | import * as $ from 'jquery'; 22 | import Vue from 'vue'; 23 | 24 | import ElementVisibility from './lib/element-visibility'; 25 | import StickersClient from './client'; 26 | 27 | 28 | // load icons 29 | const requireAll = r => r.keys().map(r); 30 | requireAll(require.context('!svg-sprite-loader!./icons/', false, /.*\.svg$/)) 31 | .map(m => m.default) 32 | .reduce((acc, icon) => ({ 33 | ...acc, 34 | [icon.id]: icon 35 | }), {}); 36 | 37 | 38 | // consts 39 | const MAX_DRAW_WIDTH = 300; 40 | const MAX_DRAW_HEIGHT = 400; 41 | 42 | 43 | var typingTimer = null; 44 | var doneTypingInterval = 1000; 45 | 46 | 47 | // page controller 48 | class StickersPage { 49 | constructor() { 50 | this.setupCoreUi(); 51 | this.setupStickersUi(); 52 | StickersClient.init(); 53 | StickersClient.on('load-progress', f => this.vue.indexLoadProgress = f); 54 | StickersClient.once('loaded', rawStickerIndex => { 55 | this.vue.stickerIndex = this.processRawStickerIndex(rawStickerIndex); 56 | this.vue.$nextTick(() => { 57 | // $('.header-area__search-field').focus(); 58 | if($('*[data-key="'+localStorage.getItem('activeLibrary')+'"]') == null) { 59 | $('*[data-key="all"]').click(); 60 | } else { 61 | $('*[data-key="'+localStorage.getItem('activeLibrary')+'"]').click(); 62 | } 63 | this.loadVisibleStickers(); 64 | if(localStorage.getItem('hasUpdates') !== null && localStorage.getItem('hasUpdates') == true) { 65 | $(document.body).addClass('hasUpdates'); 66 | } 67 | }); 68 | }); 69 | } 70 | 71 | processRawStickerIndex(stickerIndex) { 72 | 73 | stickerIndex.libraries = stickerIndex.libraries 74 | .filter(lib => !!lib.sections.length); 75 | 76 | if(stickerIndex.libraries.length <= 1) { 77 | $(document.body).addClass('hide-navigation'); 78 | } 79 | 80 | for (let library of stickerIndex.libraries) { 81 | for (let section of library.sections) { 82 | section.rows = []; 83 | let currentRow = null; 84 | 85 | let newRow = () => { 86 | currentRow = {items: []}; 87 | section.rows.push(currentRow); 88 | }; 89 | 90 | for (let item of section.items) { 91 | if (item.layout == 'row') { 92 | newRow(); 93 | currentRow.items.push(item); 94 | newRow(); 95 | } else { 96 | if (!currentRow) { 97 | newRow(); 98 | } 99 | currentRow.items.push(item); 100 | } 101 | } 102 | } 103 | } 104 | 105 | return stickerIndex; 106 | } 107 | 108 | setupCoreUi() { 109 | $(document.body).attr('ui-mode', 110 | (window.location.search.match(/uiMode=(\w+)/) || [])[1] || 'cover'); 111 | 112 | if (window.location.search.match(/darkMode=1/)) { 113 | $(document.body).attr('is-dark-theme', '1'); 114 | } 115 | 116 | $(document).on('contextmenu', e => e.preventDefault()); 117 | $(document).on('click', 'a[href]', ev => { 118 | let url = $(ev.target).attr('href'); 119 | StickersClient.openUrl(url); 120 | ev.preventDefault(); 121 | }); 122 | 123 | // setupSearchHistoryList(); 124 | 125 | var me = this; 126 | 127 | this.vueGlobal = new Vue({ 128 | data: { 129 | searchText: '', 130 | anyResults: false 131 | }, 132 | }); 133 | 134 | Vue.prototype.$globals = this.vueGlobal; 135 | 136 | function hiliteReplacer_() { 137 | return Array.from(arguments).slice(1, -2) 138 | .map((s, i) => i % 2 == 0 139 | ? `${s}` 140 | : s) 141 | .join(''); 142 | } 143 | 144 | Vue.component('hilitext', { 145 | template: `
`, 146 | props: ['text'], 147 | methods: { 148 | highlight: (text, query) => { 149 | if (!query) { 150 | return text; 151 | } 152 | 153 | return String(text || '').replace(this.regexForSearchText(query), hiliteReplacer_); 154 | } 155 | } 156 | }); 157 | 158 | Vue.component('svg-icon', { 159 | template: ``, 160 | props: ['glyph'], 161 | }); 162 | 163 | Vue.component('sticker', { 164 | props: ['sticker', 'parentSection'], 165 | template: '#sticker-template', 166 | computed: { 167 | drawSize() { 168 | return me.calcDrawSize(this.sticker); 169 | } 170 | }, 171 | }); 172 | 173 | this.vue = new Vue({ 174 | el: '.root', 175 | data: { 176 | indexLoadProgress: 0, 177 | stickerIndex: null, 178 | }, 179 | methods: { 180 | addLibraryColors(library) { 181 | StickersClient.addLibraryColors(library.id); 182 | library.colorsAdded = true; 183 | }, 184 | closeWindow() { 185 | // StickersClient.close(); 186 | }, 187 | onSearchKeydown(ev) { 188 | if (ev.keyCode == 27) { 189 | if (ev.target.value) { 190 | ev.preventDefault(); 191 | me.vueGlobal.searchText = ''; 192 | me.updateSearch(); 193 | } 194 | } 195 | // clearTimeout(typingTimer); 196 | }, 197 | onSearchKeyup(ev) { 198 | // clearTimeout(typingTimer); 199 | // typingTimer = setTimeout( function() { 200 | // updateSearchHistory(me.vueGlobal.searchText) 201 | // }, doneTypingInterval); 202 | }, 203 | onSearchInput(ev) { 204 | $(window).scrollTop(0); 205 | me.updateSearch(); 206 | // clearTimeout(ev._timer); 207 | // ev._timer = setTimeout(()=>{ 208 | // me.updateSearchHistory(); 209 | // }, 500); 210 | }, 211 | }, 212 | }); 213 | } 214 | 215 | regexForSearchText(query) { 216 | return new RegExp((query || '') 217 | .replace(/^\s+|\s+$/g, '') 218 | .split(/\s+/) 219 | .map(s => `(${s})`) 220 | .join('(.*?)'), 'ig'); 221 | } 222 | 223 | updateSearch() { 224 | 225 | let query = this.vueGlobal.searchText; 226 | localStorage.setItem("query", query); 227 | 228 | // TODO: move this to a watcher in vueGlobal 229 | this.vue.$nextTick(() => { 230 | const re = this.regexForSearchText(query); 231 | 232 | // if(query.length < 1) { 233 | // console.log("Clear search and go back to selected tab"); 234 | // } 235 | 236 | 237 | const findIn = s => this.vueGlobal.searchText ? (s || '').search(re) >= 0 : true; 238 | 239 | const visitItem = item => { 240 | let found = false; 241 | if (item.items) { 242 | // section 243 | for (const subItem of item.items) { 244 | if (visitItem(subItem)) { 245 | found = true; 246 | } 247 | } 248 | if (findIn(item.title) || findIn(item.description)) { 249 | found = true; 250 | visitUnhide(item); 251 | } 252 | 253 | } else { 254 | // sticker 255 | found = findIn(item.name); 256 | } 257 | 258 | item._hide = !found; 259 | return found; 260 | }; 261 | 262 | const visitUnhide = item => { 263 | if (item.items) { 264 | for (const subItem of item.items) { 265 | visitUnhide(subItem); 266 | } 267 | } 268 | 269 | item._hide = false; 270 | }; 271 | 272 | let anyResults = false; 273 | let selectedLibraries = this.vue.stickerIndex.libraries; 274 | let searchableLibraries; 275 | let activeLibrary = localStorage.getItem('activeLibrary'); 276 | localStorage.setItem("beforeSearchActiveLibrary", activeLibrary); 277 | 278 | // console.log("selectedLibraries"); 279 | // console.log(selectedLibraries); 280 | // console.log("activeLibrary"); 281 | // console.log(activeLibrary); 282 | 283 | if (activeLibrary !== 'all') { 284 | searchableLibraries = selectedLibraries.filter(obj => { 285 | return obj.id == activeLibrary 286 | }); 287 | } else { 288 | searchableLibraries = selectedLibraries; 289 | } 290 | 291 | for (const library of searchableLibraries) { 292 | let foundInLibrary = false; 293 | for (const section of library.sections) { 294 | let found; 295 | for (const row of section.rows) { 296 | if (visitItem(row)) { 297 | found = true; 298 | } 299 | } 300 | if (findIn(section.title) || findIn(section.description)) { 301 | found = true; 302 | for (const row of section.rows) { 303 | visitUnhide(row); 304 | } 305 | } 306 | section._hide = !found; 307 | anyResults = anyResults || found; 308 | foundInLibrary = foundInLibrary || found; 309 | } 310 | library._hide = !foundInLibrary; 311 | } 312 | 313 | if (typeof anyResults === 'undefined') { 314 | anyResults = false; 315 | } 316 | 317 | this.vueGlobal.anyResults = anyResults; 318 | 319 | this.vue.$forceUpdate(); 320 | $(document.body).toggleClass('has-active-search', (!!this.vueGlobal.searchText && anyResults)); 321 | $(document.body).toggleClass('no-search-results', !anyResults); 322 | this.vue.$nextTick(() => { 323 | this.loadVisibleStickers(); 324 | }); 325 | }); 326 | } 327 | 328 | calcDrawSize(sticker) { 329 | // fit the sticker into a max width and height, keeping its aspect ratio 330 | let size = { width: sticker.width, height: sticker.height }; 331 | if (size.width > MAX_DRAW_WIDTH) { 332 | size.height = size.height * MAX_DRAW_WIDTH / size.width; 333 | size.width = MAX_DRAW_WIDTH; 334 | } 335 | if (size.height > MAX_DRAW_HEIGHT) { 336 | size.width = size.width * MAX_DRAW_HEIGHT / size.height; 337 | size.height = MAX_DRAW_HEIGHT; 338 | } 339 | return size; 340 | } 341 | 342 | setupStickersUi() { 343 | $(document).on('mousedown', '.sticker__thumb', ev => { 344 | let stickerId = $(ev.target).parents('.sticker').attr('data-sticker-id'); 345 | let rect = $(ev.target).get(0).getBoundingClientRect(); 346 | rect = { 347 | x: rect.left, 348 | y: rect.top, 349 | width: rect.right - rect.left, 350 | height: rect.bottom - rect.top 351 | }; 352 | StickersClient.startDragging(stickerId, rect); 353 | }); 354 | 355 | if(localStorage.getItem('activeLibrary') == null) { 356 | localStorage.setItem("activeLibrary", 'all'); 357 | } 358 | 359 | if(localStorage.getItem('beforeSearchActiveLibrary') == null) { 360 | localStorage.setItem("beforeSearchActiveLibrary", 'all'); 361 | } 362 | 363 | $(document).on('click', '.library-tab', ev => { 364 | $(ev.target).addClass('active'); 365 | $(ev.target).siblings().removeClass('active'); 366 | 367 | var key = $(ev.target).attr('data-key'); 368 | var libraryContainer = '.sticker-library-container'; 369 | 370 | localStorage.setItem("activeLibrary", key); 371 | 372 | if(key === 'all') { 373 | $(libraryContainer).show(); 374 | } else { 375 | $('#' + key + libraryContainer).show(); 376 | $('#' + key + libraryContainer).siblings().hide(); 377 | } 378 | window.scrollTo({top: 0, behavior: 'smooth'}); 379 | 380 | //$('.autocomplete').focus(); 381 | if($(document.body).hasClass('no-search-results')) { 382 | $(document.body).removeClass('no-search-results'); 383 | } 384 | // this.vueGlobal.searchText = $('.header-area__search-field').value; 385 | this.updateSearch(); 386 | 387 | }); 388 | 389 | this.setupStickerImageLoading(); 390 | } 391 | 392 | setupStickerImageLoading() { 393 | this.loadVisibleStickers(); 394 | $(window).on('DOMContentLoaded load resize', () => this.loadVisibleStickers()); 395 | window.addEventListener('scroll', () => this.loadVisibleStickers(), true); // true == capture (all elements) 396 | } 397 | 398 | loadVisibleStickers() { 399 | this.fetchedImages = this.fetchedImages || new Set(); 400 | $('.sticker').each((index, el) => { 401 | let $el = $(el); 402 | let stickerId = $el.attr('data-sticker-id'); 403 | if ($el.attr('data-loaded')) { 404 | return; 405 | } 406 | 407 | if (!ElementVisibility.isElementInViewport(el)) { 408 | return; 409 | } 410 | 411 | this.fetchedImages.add(stickerId); 412 | StickersClient.getStickerImageUrl(stickerId).then(url => { 413 | $el.find('.sticker__thumb').attr('src', url).one('load', () => { 414 | $el.attr('data-loaded', true); 415 | }); 416 | }); 417 | }); 418 | } 419 | } 420 | 421 | function updateSearchHistory(searchTerm) { 422 | // console.log("searchText: " + searchTerm); 423 | var localHistory = []; 424 | if (localStorage.getItem("searchHistory") !== null) { 425 | localHistory = JSON.parse(localStorage.getItem("searchHistory")); 426 | } 427 | if((!localHistory.includes(searchTerm)) && searchTerm.length > 3) { 428 | localHistory.push(searchTerm); 429 | addItemToSearchHistoryList(searchTerm); 430 | } 431 | localStorage.setItem("searchHistory", JSON.stringify(localHistory)); 432 | // $("#log").val(JSON.stringify(localHistory)); 433 | } 434 | 435 | function setupSearchHistoryList() { 436 | /* ======= setting up search history ========== */ 437 | var localHistory = []; 438 | // localStorage.clear(); 439 | if (localStorage.getItem("searchHistory") !== null) { 440 | localHistory = JSON.parse(localStorage.getItem("searchHistory")); 441 | } 442 | localHistory.forEach(function(item){ 443 | addItemToSearchHistoryList(item); 444 | }); 445 | } 446 | 447 | function addItemToSearchHistoryList(item) { 448 | var list = document.getElementById('searchHistory'); 449 | var option = document.createElement('option'); 450 | option.value = item; 451 | list.appendChild(option); 452 | } 453 | 454 | $(window).on('load', () => { 455 | new StickersPage(); 456 | }); -------------------------------------------------------------------------------- /web/src/lib/element-visibility.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import * as jQuery from 'jquery'; 18 | 19 | export default { 20 | /** 21 | * Test if the given element is in th current viewport. 22 | * https://stackoverflow.com/a/7557433 23 | */ 24 | isElementInViewport(el) { 25 | if (el instanceof jQuery) { 26 | el = el.get(0); 27 | } 28 | 29 | const rect = el.getBoundingClientRect(); 30 | 31 | return ( 32 | rect.bottom >= 0 && 33 | rect.right >= 0 && 34 | rect.top <= jQuery(window).height() && 35 | rect.left <= jQuery(window).width()); 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /web/src/lib/embedded-ui.scss: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | *, 18 | *::before, 19 | *::after { 20 | -webkit-user-select: none; 21 | user-select: none; 22 | } 23 | 24 | input, textarea { 25 | -webkit-user-select: auto; 26 | user-select: auto; 27 | } 28 | 29 | html { 30 | cursor: default; 31 | } -------------------------------------------------------------------------------- /web/src/lib/svg-icons.scss: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // defaults 18 | 19 | .svg-icon { 20 | width: 24px; 21 | height: 24px; 22 | fill: currentColor; 23 | } -------------------------------------------------------------------------------- /web/src/plugin-call-stub.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // This is a stub client used during development. 18 | const STUB_STICKER_INDEX = require('./_stub-sticker-index.json'); 19 | 20 | const ACTIONS = { 21 | close() { 22 | }, 23 | 24 | startDragging(id, rect) { 25 | }, 26 | 27 | addLibraryColors(libraryId) { 28 | }, 29 | 30 | requestLayerImageUrl(stickerId, callbackName) { 31 | let sticker = __getStickerById(stickerId); 32 | let canvas = document.createElement('canvas'); 33 | canvas.width = sticker.width * 2; 34 | canvas.height = sticker.height * 2; 35 | let ctx = canvas.getContext('2d'); 36 | ctx.scale(2, 2); 37 | ctx.fillStyle = '#3F51B5'; 38 | ctx.fillRect(0, 0, sticker.width, sticker.height); 39 | ctx.textAlign = 'center'; 40 | ctx.textBaseline = 'middle'; 41 | ctx.font = Math.ceil(Math.max(13, Math.min(sticker.width, sticker.height) / 10)) + 'px Menlo'; 42 | ctx.fillStyle = 'rgba(255,255,255,.6)'; 43 | ctx.fillText(`${sticker.width}x${sticker.height}`, sticker.width / 2, sticker.height / 2); 44 | let url = canvas.toDataURL(); 45 | // let subPath = sticker.imagePath.replace(/.*net.nurik.roman.sketch.stickers/, ''); 46 | // let url = '/real-sticker-cache/' + subPath; 47 | window[callbackName](stickerId, url); 48 | }, 49 | 50 | loadStickerIndex(callbackName, progressCallbackName) { 51 | // window[progressCallbackName](0); 52 | // setTimeout(() => window[progressCallbackName](.3), 100); 53 | // setTimeout(() => window[progressCallbackName](.5), 300); 54 | // setTimeout(() => window[progressCallbackName](.9), 1000); 55 | // setTimeout(() => window[callbackName](STUB_STICKER_INDEX), 1500); 56 | setTimeout(() => window[callbackName](STUB_STICKER_INDEX), 0); 57 | }, 58 | }; 59 | 60 | window['pluginCall'] = function pluginCall(action, ...args) { 61 | console.log(`pluginCall: ${action} with args ${JSON.stringify(args)}`); 62 | ACTIONS[action].apply(null, args); 63 | }; 64 | 65 | 66 | function __getStickerById(id) { 67 | let foundSticker = null; 68 | let findInSection = section => { 69 | (section.items || []).forEach(item => { 70 | if (item.type == 'layer' && item.id == id) { 71 | foundSticker = item; 72 | } else if (item.type == 'section') { 73 | findInSection(item); 74 | } 75 | }); 76 | }; 77 | 78 | for (let library of STUB_STICKER_INDEX.libraries) { 79 | for (let section of library.sections) { 80 | findInSection(section); 81 | } 82 | } 83 | return foundSticker; 84 | } 85 | -------------------------------------------------------------------------------- /web/src/variables.scss: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | $fontStackBody: -apple-system, BlinkMacSystemFont; 18 | 19 | @function make-soft-gradient-color-to-transparent($color) { 20 | @return linear-gradient(to right, 21 | rgba($color, 1.00) 0%, 22 | rgba($color, 0.90) 30%, 23 | rgba($color, 0.67) 60%, 24 | rgba($color, 0.50) 75%, 25 | rgba($color, 0.33) 85%, 26 | rgba($color, 0.00) 100%); 27 | } 28 | 29 | @mixin theme-light { 30 | $__bg: #fff; 31 | $__accent: #3D5AFE; 32 | --theme-color-bg: #{$__bg}; 33 | --theme-color-bg-level-2: #{darken($__bg, 4%)}; 34 | --theme-color-bg-level-3: #{darken($__bg, 10%)}; 35 | --theme-color-bg-floating-header: #{rgba($__bg, .85)}; 36 | --theme-color-fg-primary: #{rgba(#000, .87)}; 37 | --theme-color-fg-secondary: #{rgba(#000, .54)}; 38 | --theme-color-fg-tertiary: #{rgba(#000, .38)}; 39 | --theme-color-thin-border: #{rgba(#000, .12)}; 40 | --theme-color-accent: #{$__accent}; 41 | --theme-color-button: #{$__accent}; 42 | --theme-color-button-hover: #{darken($__accent, 10%)}; 43 | --theme-color-button-active: #{darken($__accent, 20%)}; 44 | --theme-color-button-fg: #fff; 45 | --theme-color-search: #{rgba(#000, .12)}; 46 | --theme-color-search-active: #{rgba(#000, .24)}; 47 | --theme-color-search-highlight: #FBBC04; 48 | --theme-gradient-fade-to-bg: #{make-soft-gradient-color-to-transparent($__bg)}; 49 | } 50 | 51 | @mixin theme-dark { 52 | $__bg: #202124; 53 | $__accent: #202124; 54 | --theme-color-bg: #{$__bg}; 55 | --theme-color-bg-level-2: #{lighten($__bg, 6%)}; 56 | --theme-color-bg-level-3: #{lighten($__bg, 10%)}; 57 | --theme-color-bg-floating-header: #{rgba($__bg, .75)}; 58 | --theme-color-fg-primary: #fff; 59 | --theme-color-fg-secondary: #{rgba(#fff, .7)}; 60 | --theme-color-fg-tertiary: #{rgba(#fff, .5)}; 61 | --theme-color-thin-border: #{rgba(#fff, .2)}; 62 | --theme-color-accent: #{$__accent}; 63 | --theme-color-button: #{lighten($__accent, 10%)}; 64 | --theme-color-button-hover: #{lighten($__accent, 15%)}; 65 | --theme-color-button-active: #{lighten($__accent, 20%)}; 66 | --theme-color-button-fg: #000; 67 | --theme-color-search: #{rgba(#fff, .2)}; 68 | --theme-color-search-active: #{rgba(#fff, .3)}; 69 | --theme-color-search-highlight: #F29900;//#EA8600; 70 | --theme-gradient-fade-to-bg: #{make-soft-gradient-color-to-transparent($__bg)}; 71 | } 72 | 73 | @mixin narrow { 74 | @media only screen and (max-width: 440px) { 75 | @content; 76 | } 77 | } 78 | 79 | @mixin medium { 80 | @media only screen and (max-width: 800px) { 81 | @content; 82 | } 83 | } 84 | 85 | @mixin type-headline-1 { 86 | font-size: 20px; 87 | line-height: 28px; 88 | } 89 | 90 | @mixin type-headline-2 { 91 | font-size: 16px; 92 | line-height: 24px; 93 | } 94 | 95 | @mixin type-body-1 { 96 | font-size: 14px; 97 | line-height: 20px; 98 | } 99 | 100 | @mixin type-body-2 { 101 | font-size: 13px; 102 | line-height: 20px; 103 | } 104 | 105 | @mixin type-body-3 { 106 | font-size: 12px; 107 | line-height: 16px; 108 | } 109 | 110 | @mixin type-body-4 { 111 | font-size: 10px; 112 | line-height: 16px; 113 | } 114 | -------------------------------------------------------------------------------- /web/webpack.config.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | const path = require('path'); 18 | const sassAssetFunctions = require('node-sass-asset-functions'); 19 | const express = require('express'); 20 | const os = require('os'); 21 | 22 | module.exports = { 23 | mode: process.env.NODE_ENV || 'development', 24 | devServer: { 25 | contentBase: path.join(__dirname, '../web-dist'), 26 | compress: true, 27 | port: 9000, 28 | watchContentBase: true, 29 | before(app) { 30 | app.use('/real-sticker-cache', express.static(path.join( 31 | os.homedir(), 'Library/Caches/website.pratikshah.symbol-browser/'))); 32 | } 33 | }, 34 | entry: { 35 | 'plugin-call': [ 36 | './src/plugin-call-stub.js', 37 | ], 38 | 'index': [ 39 | './src/index.js', 40 | 'webpack-dev-server/client?http://localhost:9080/' 41 | ], 42 | }, 43 | output: { 44 | filename: '[name].js', 45 | path: path.resolve(__dirname, '../web-dist') 46 | }, 47 | resolve: { 48 | alias: { 49 | // use full (compiler + runtime) version of vue 50 | vue: 'vue/dist/vue.js' 51 | } 52 | }, 53 | performance: { 54 | hints: false 55 | }, 56 | module: { 57 | rules: [ 58 | { 59 | test: /\.(html)$/, 60 | use: [ 61 | { 62 | loader: 'extract-loader', 63 | }, 64 | { 65 | loader: 'html-loader', 66 | options: { 67 | attrs: [ 68 | 'img:src', 69 | 'link:href' 70 | ], 71 | interpolate: true, 72 | minimize: 'production' === process.env.NODE_ENV, 73 | }, 74 | }, 75 | ] 76 | }, 77 | { 78 | test: /\.(scss)$/, 79 | use: [ 80 | { 81 | loader: 'file-loader', 82 | options: { 83 | name: '[name].css' 84 | } 85 | }, 86 | { 87 | loader: 'extract-loader', 88 | options: { 89 | name: '[name].css' 90 | } 91 | }, 92 | { 93 | loader: 'css-loader', 94 | options: { 95 | minimize: 'production' === process.env.NODE_ENV, 96 | }, 97 | }, 98 | { 99 | loader: 'sass-loader', 100 | options: { 101 | functions: sassAssetFunctions({ 102 | images_path: path.join(__dirname, 'src'), 103 | }), 104 | }, 105 | }, 106 | ] 107 | }, 108 | { 109 | test: /\.(png|svg)$/, 110 | use: [ 111 | { 112 | loader: 'file-loader', 113 | options: { 114 | name: '[name].[ext]' 115 | } 116 | }, 117 | { 118 | loader: 'image-webpack-loader', 119 | } 120 | ] 121 | }, 122 | { 123 | test: /\.(woff2)$/, 124 | use: [ 125 | { 126 | loader: 'file-loader', 127 | options: { 128 | name: '[name].[ext]' 129 | } 130 | }, 131 | ] 132 | }, 133 | ], 134 | } 135 | }; 136 | --------------------------------------------------------------------------------