New in Sketch 69

Released 29 September, 2020 – read release notes

Changes

Color Variables API

Sketch 69 introduces a new Color Variables feature.

Color Variables replace the previously existing colors object in Document with a new one: swatches. It is an array of Color Variables, internally referred to as Swatches, which you can modify directly.

This example generates 100 random swatches and adds them to the current document:

const sketch = require('sketch')
const Swatch = sketch.Swatch
const doc = sketch.getSelectedDocument()

for (var i = 0; i < 100; i++) {
  const randomColor = generateHex()
  const swatch = Swatch.from({
    name: `Rainbow ${i + 1}`,
    color: randomColor,
  })
  doc.swatches.push(swatch)
}

function generateHex() {
  var randomColor = Math.floor(Math.random() * 16777215).toString(16)
  var hexColor = '#' + randomColor
  return hexColor
}

To use a Color Variable on a Layer, Style or any API expecting a Color, use the Swatch’s referencingColor attribute:

const mySwatch = Swatch.from({
  name: 'Safety Orange',
  color: '#ff6600',
})
doc.swatches.push(mySwatch) // Add Swatch to document before using
textLayer.style.textColor = mySwatch.referencingColor

In addition to local Color Variables, Sketch also supports Color Variables from shared Libraries. They work in a similar way to Symbols, so the API will look familiar if you’ve previously used the Symbols API.

This example will import all the Color Variables from a shared Library:

const sketch = require('sketch')
const Library = sketch.Library

const doc = sketch.getSelectedDocument()

const lib = Library.getLibraryForDocumentAtPath(
  'shared-color-variables.sketch'
)
const importableSwatches = lib.getImportableSwatchReferencesForDocument(doc)
const importedSwatch = importableSwatches[0].import()

textLayer.style.textColor = importedSwatch.referencingColor

For more details about the API, check the documentation for Swatch, Document, and Library.