Skip to content

Instantly share code, notes, and snippets.

@LukeFinch
Last active June 5, 2020 10:17
Show Gist options
  • Save LukeFinch/bac3695c2c98459e4d417ef617eb58c0 to your computer and use it in GitHub Desktop.
Save LukeFinch/bac3695c2c98459e4d417ef617eb58c0 to your computer and use it in GitHub Desktop.
Extract TextStyles from Sketch document and output into a Figma friendly format
var sketch = require('sketch')
var Document = require('sketch/dom').Document
var document = Document.getSelectedDocument()
var texts = []
var paints = []
var output = {}
//Sketch's document.getTextStyles() doesn't return all the info.
function getSharedStyles(type) {
var myStyles = []
if (sketch.version.sketch < 52) {
var styles = (type == 0) ? MSDocument.currentDocument().documentData().layerStyles().objects() : MSDocument.currentDocument().documentData().layerTextStyles().objects();
} else {
var styles = (type == 0) ? MSDocument.currentDocument().documentData().allLayerStyles() : MSDocument.currentDocument().documentData().allTextStyles();
}
var sortByName = NSSortDescriptor.sortDescriptorWithKey_ascending("name",1);
styles = styles.sortedArrayUsingDescriptors([sortByName]);
styles.forEach(style => {myStyles.push(style)})
return myStyles;
}
var textStyles = getSharedStyles(1)
//Optional - Filter so we only get left aligned text, and the base colour.
var textStyles = textStyles.filter(style => style.name().includes('inkBase') && document.getSharedTextStyleWithID(style.objectID()).style.alignment == 'left')
textStyles.forEach(style => {
inp = document.getSharedTextStyleWithID(style.objectID()).style
let weight = inp.fontWeight
let weightName = style.style().textStyle().fontPostscriptName().split('-')[1].replace(/([a-z0-9])([A-Z])/g, '$1 $2')
o = {}
o.type = "TEXT"
//remove the ink Name from the token name
let n = style.name().split('/')
n.pop()
o.name = n.join('/')
o.fontSize = inp.fontSize
o.fontName = {family: inp.fontFamily, style: weightName}
o.lineHeight = {unit: "PIXELS",value: inp.lineHeight}
o.letterSpacing = inp.kerning
o.paragraphSpacing = inp.paragraphSpacing
texts.push(o)
}))
const regex = RegExp('(0[123457])','g')
inks = getSharedStyles(0).filter(style => regex.test(style.name()) && !style.name().includes('border') && !style.name().includes('transparent'))
inks.forEach(style => {
inp = style.style()
o = {}
o.type = "SOLID"
o.name = `${style.name()}`
try {
let color = inp.fills()[0].color()
o.color = {r:color.red(),g: color.green(),b: color.blue()}
o.opacity = color.alpha()
}
catch(e){console.error(style.name())}
paints.push(o)
})
output.paints = paints
output.texts = texts
str = JSON.stringify(output)
//console.log(str)
console.log(str)
//console.log(JSON.stringify(output))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment