Giter Site home page Giter Site logo

oscarotero / node-sketch Goto Github PK

View Code? Open in Web Editor NEW
304.0 7.0 23.0 4.07 MB

πŸ’Ž Javascript library to manipulate sketch files

Home Page: https://oscarotero.github.io/node-sketch/

License: MIT License

JavaScript 100.00%
sketch nodejs sketchapp

node-sketch's Introduction

πŸ’Ž node-sketch

Javascript library to manipulate sketch files

Build Status

Install

npm install node-sketch

Example:

const ns = require('node-sketch');

async function run() {
    const sketch = await ns.read(__dirname + '/design.sketch');

    //Search the symbol named 'button'
    const buttonSymbol = sketch.symbolsPage.get('symbolMaster', 'button');

    //Search all instances of a symbol named 'old-button' and replace it with 'button'
    const firstPage = sketch.pages[0];
    
    firstPage
        .getAll('symbolInstance', instance => instance.symbolMaster.name === 'old-button')
        .forEach(instance => instance.symbolMaster = buttonSymbol);

    //Save the result
    sketch.save('modified-design.sketch')
        .then(console.log('File saved!!'));
}

run();

API

Two classes are used to manage sketch files:

Sketch

Represents the sketch file and contains all data (pages, symbols, styles, shapes, etc). Contains the method .save() to create a sketch file with the result.

const ns = require('node-sketch');

ns.read('input.sketch').then(sketch => {
    sketch.document           // document data
    sketch.meta               // meta data
    sketch.user               // user data
    sketch.pages              // array with all pages
    sketch.symbolsPage        // the Symbols page
    sketch.layerStyles        // array with the layer styles
    sketch.textStyles         // array with the text styles
    sketch.colors             // array containing the colors stored in the color palette
    sketch.gradients          // array containing the gradients stored in the gradient palette
    sketch.symbols            // array with all symbols stored in the document

    sketch.foreignSymbols     // array with the symbols loaded from external libraries
    sketch.foreignLayerStyles // array with the layer styles loaded from external libraries
    sketch.foreignTextStyles  // array with the text styles loaded from external libraries

    sketch.save('output.sketch');
});

Node

It's the base class used by all other elements. Any page, symbol, color, etc is an instance of this class.

const symbolsPage = sketch.symbolsPage;

console.log(symbolsPage instanceof Node); //true 

//It include useful methods to search an inner node by class:
const button = symbolsPage.get('symbolMaster');

//by class and name
const button = symbolsPage.get('symbolMaster', 'button');

//by class and callback
const button = symbolsPage.get('symbolMaster', symbol => symbol.name === 'button');

//Just a callback
const button = symbolsPage.get(node => node._class === 'symbolMaster' && node.name === 'button');

//And the same than above but returning all inner nodes instead just the first:
const allSymbols = symbolsPage.getAll('symbolMaster');

There are other classes extending Node to provide special funcionalities in some nodes, like Style or SymbolInstance.

JSON Scheme

Technically, the sketch format consist in a zip with some json files. To manipulate a sketch file with this library, you need to know the scheme of json. You can use this code to read and extract a sketch file into a directory, in order to inspect the json scheme:

const ns = require('../');

ns.read('demo.sketch').then(sketch => sketch.saveDir('demo'));

Here you can see an example of extracted file

CLI

Starting from v0.14.0, the command node-sketch was included to use the library from CLI. You only need a file named node-sketch.js exporting the function to manipulate a sketch file. For example:

module.exports = sketch => {
    //Convert the text style names to uppercase
    sketch.textStyles.forEach(textStyle => {
        textStyle.name = textStyle.name.toUpperCase();
    })
}

To execute this script with the sketch file my-styles.sketch, run node-sketch my-styles.sketch. By default, the file is readed, but not saved. If you want to override the file with the modifications, run node-sketch my-styles.sketch --save.

And to execute a script file with a different name, use the --script argument: node-sketch my-styles.sketch --script=my-script.js --save.


See the API detailed

Or build it locally with npm run docs

node-sketch's People

Contributors

aleen42 avatar dependabot-preview[bot] avatar dependabot-support avatar oscarotero avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-sketch's Issues

Syncing shared styles

I'm writing a small script to update a shared style and apply it to all layers that inherit it. Currently I can update the shared style, but I'm not quite sure how to "sync" it to all layers.

I see there's an UpdateStyles plugin, but that takes styles from an external document and applies them to another. I want to update shared styles within a document and then update all layers that use it.

export image

Hi,are there any plans to export images or convert irregular shape to image?

can not read sketch.colors

inspired of demo I do some thing like this

const ns = require('node-sketch');
const fs = require('fs')

ns.read('./test.sketch').then(sketch => {
  fs.writeFile('test.js', JSON.stringify(sketch.colors, null, 2)) // => got an empty array  []
})

how can I get all colors in some sketch file?
sketch version 55.2

sketch.getAll is not a function

node -v 
v8.12.0

node-sketch
v0.14.1

(node:15887) UnhandledPromiseRejectionWarning: TypeError: sketch.getAll is not a function
at run (/Users/rihikobon/study/demo/index.js:11:10)
at
(node:15887) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:15887) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Updating Styles in Layers

Hi! Love this library, I have a problem where I'm making a change to the styles (adding color), and saving it, but the changes aren't being saved, or it'll corrupt the file :/

    ns.read(filePath)
      .then((sketch) => {     
         layers[i].getAll("style", style => {
            style.fills = [];
            style.fills[0] = {
              _class: 'color',
              alpha: endColor[3] === undefined ? undefined : endColor[3],
              blue: endColor[2],
              green: endColor[1],
              red: endColor[0],
            }
         return sketch.save(path.join(__dirname + `/output.sketch`))
          .then((success) => {
            console.log('SUCCESS')
          });
      })

It'll log the success, and the output.sketch file is there, but it'll give me this prompt when i attempt to open it

screen shot 2017-11-21 at 3 48 35 pm

When I fix it it'll show me the original file, before any changes were made.

If i select don't fix i get::

screen shot 2017-11-21 at 3 48 39 pm

Any tips?

Thank you

SVG exporting

Hello, I just came across this wonderful library and was really intrigued by it :) I was curious if there are any plans or any current way to export SVG's with this tool? I'm looking to build a sketch babel loader and was curious if I could use this to do it?

Text value for text nodes?

Hey – been messing around with this module a bit for the past couple of days (awesome job, btw!)

Haven't figured out how to get the actual text value of an element though. I only see things like this:

{ _archive: 'YnBsaXN0MDDUAQIDBAUGZGVYJHZlcnNpb25YJG9iamVjdHNZJGFyY2hpdmVyVCR0b3ASAAGGoK8QGwcIDxAcHR4fKywtLi8wNjpCQ0RFRklNV1pdYFUkbnVsbNMJCgsMDQ5YTlNTdHJpbmdWJGNsYXNzXE5TQXR0cmlidXRlc4ACgBqAA1tIZWxsbyAjdGV4dNMREgoTFxtXTlMua2V5c1pOUy5vYmplY3RzoxQVFoAEgAWABqMYGRqAB4AOgBaADV8QKk1TQXR0cmlidXRlZFN0cmluZ0NvbG9yRGljdGlvbmFyeUF0dHJpYnV0ZV8QH01TQXR0cmlidXRlZFN0cmluZ0ZvbnRBdHRyaWJ1dGVfEBBOU1BhcmFncmFwaFN0eWxl0xESCiAlG6QhIiMkgAiACYAKgAukJiYmJoAMgAyADIAMgA1TcmVkVWFscGhhVGJsdWVVZ3JlZW4jP/AAAAAAAADSMTIzNFokY2xhc3NuYW1lWCRjbGFzc2VzXE5TRGljdGlvbmFyeaIzNVhOU09iamVjdNIKNzg5XxAaTlNGb250RGVzY3JpcHRvckF0dHJpYnV0ZXOAFYAP0xESCjs+QaI8PYAQgBGiP0CAEoATgBRfEBNOU0ZvbnRTaXplQXR0cmlidXRlXxATTlNGb250TmFtZUF0dHJpYnV0ZSNASAAAAAAAAF8QEk1vbnRzZXJyYXQtUmVndWxhctIxMkdIXxATTlNNdXRhYmxlRGljdGlvbmFyeaNHMzXSMTJKS18QEE5TRm9udERlc2NyaXB0b3KiTDVfEBBOU0ZvbnREZXNjcmlwdG9y1U5PClBRUlNUVVVaTlNUYWJTdG9wc1tOU0FsaWdubWVudFxOU1RleHRCbG9ja3NbTlNUZXh0TGlzdHOAABAEgBmAF4AX0hIKWFmggBjSMTJbXFdOU0FycmF5ols10jEyXl9fEBBOU1BhcmFncmFwaFN0eWxlol410jEyYWJfEBJOU0F0dHJpYnV0ZWRTdHJpbmeiYzVfEBJOU0F0dHJpYnV0ZWRTdHJpbmdfEA9OU0tleWVkQXJjaGl2ZXLRZmdUcm9vdIABAAgAEQAaACMALQAyADcAVQBbAGIAawByAH8AgQCDAIUAkQCYAKAAqwCvALEAswC1ALkAuwC9AL8AwQDuARABIwEqAS8BMQEzATUBNwE8AT4BQAFCAUQBRgFKAVABVQFbAWQBaQF0AX0BigGNAZYBmwG4AboBvAHDAcYByAHKAc0BzwHRAdMB6QH/AggCHQIiAjgCPAJBAlQCVwJqAnUCgAKMApkCpQKnAqkCqwKtAq8CtAK1ArcCvALEAscCzALfAuIC5wL8Av8DFAMmAykDLgAAAAAAAAIBAAAAAAAAAGgAAAAAAAAAAAAAAAAAAAMw' }

Inside an attribute called attributedString on the text node.

Any thoughts on how to get the actual text value? That looks like a dump from an Objective C object into JSON and not sure what format it's in..

Overwrite Sketch styles from external css/less

I have a situation where I would like to overwrite existing styles (layer/text/colors in a sketch file by reading the new values from an external css/less, and output a new sketch file with those applied. Ideally batch apply multiple css/less files -> output sketch files

Right now I use puzzle tokens, which does a great job at applying a .less file, though its a plugin and needs to be run from within sketch. I'd like to run this from the Command line so it can be automized.

Any thoughts on how to approach this?

Preview is not updated after saving

I'm trying to update text layers of sketch files dynamically like below.

const sketch = await ns.read(mySketchFile);
const page = sketch.pages[0].layers[0];
let my_layer = _.find(page.layers, { name: 'my_layer' });
my_layer.attributedString.string = myDataLayer;
sketch.save(myNewSketchFilePath)

The preview of the new sketch file exported is never updated as if updates have not been taken.
I have to manually open the sketch file, save it and now the preview will be OK.
You can see the issue in the demo replace-styles in the repo

Any ideas ?

bin.js is missing in NPM package v0.14

To reproduce:

You'll see the error:

npm ERR! enoent ENOENT: no such file or directory, chmod '..../node_modules/node-sketch/bin.js'

A quick check of the package contents with npm pack [email protected], lists these files:

npm notice 
npm notice πŸ“¦  [email protected]
npm notice === Tarball Contents === 
npm notice 1.2kB  package.json         
npm notice 4.2kB  CHANGELOG.md         
npm notice 3.1kB  index.js             
npm notice 1.1kB  LICENSE              
npm notice 4.4kB  README.md            
npm notice 1.7kB  src/FileReference.js 
npm notice 11.0kB src/Node.js          
npm notice 6.4kB  src/Sketch.js        
npm notice 2.3kB  src/Style.js         
npm notice 1.4kB  src/SymbolInstance.js
npm notice === Tarball Details === 
npm notice name:          node-sketch                             
npm notice version:       0.14.0                                  
npm notice filename:      node-sketch-0.14.0.tgz                  
npm notice package size:  9.7 kB                                  
npm notice unpacked size: 36.8 kB                                 
npm notice shasum:        67f0c4fcc228d0488fa2b052faa9bd5cf3e54c5a
npm notice integrity:     sha512-lK55Z0W2tJyx/[...]zbtyVGgI/xEmg==
npm notice total files:   10                                      
npm notice 
node-sketch-0.14.0.tgz

Note that this problem happens with npm, yarn will silently fail to create the bin symlink but it doesn't give any error

Swapping styles from different libraries

This is probably loosely related to #4 .

I have two libraries (A, and B), and a Sketch file that currently uses some foreignStyles from A.

What's the most efficient way to swap every foreignStyle used in the Sketch file to point from library A, to B?

The IDs of the styles to match in the two different libraries are exactly the same, if that helps.

Thanks a lot, and keep up the great work! πŸ‘‹

set('foreignSymbols', arr) doesn't work properly

Hi,

I'm trying to do something like this:

sketch.document.set('foreignSymbols', arrayOfNewNodeSymbols);

the assignment works OK, but when I check the actual array I assigned to sketch.foreignSymbols, I'm seeing this:

screen shot 2019-02-19 at 3 01 55 pm

I'm guessing I'm doing something wrong or am doing something that is not allowed. I'm looking to strip out some symbols based on certain conditions and rewrite the file with that new set of symbols.

EDIT: I think I figured this out; sketch.foreignSymbols has different object types (symbolMaster) than sketch.document.foreignSymbols.

Perhaps in the future be able to set sketch.whatever attrs as well as getting them?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.