Introduction
This is a prototype Javascript API for Sketch. It’s still a work in progress, but the intention is to make something which is:
- native Javascript
- an easily understandable subset of the full internals of Sketch
- fully supported by Bohemian between releases (ie we try not to change it, unlike our internal API which we can and do change whenever we need to)
- still allows you to drop down to our internal API when absolutely necessary.
The idea is to keep this API as lean-and-mean as possible. The main reason for that is that if we (Bohemian) are committing ourselves to making sure that we don’t break it, then it’s essential that doing so doesn’t become an unmanageable task.
Again, this is very much a work in progress, so comments and suggestions for this API are welcome - send them to developers@sketchapp.com, or open an issue to have a public discussion.
Installation
var sketch = require('sketch/dom')
var async = require('sketch/async')
var DataSupplier = require('sketch/data-supplier')
var UI = require('sketch/ui')
var Settings = require('sketch/settings')
// a more convenient require which exposes everything (might be a bit slower)
var sketch = require('sketch')
The API comes bundled inside Sketch, so no installation is required. You access it by calling the global require
function.
Sketch Components
The approach taken by the API is to wrap the native Sketch model objects inside javascript objects. These are thin wrappers, and contain no state - they just exist as a way to provide a cleaner and more stable coding interface to the underlying model.
Each Component follows the same API:
Component.fromNative(sketchObject)
returns a wrapped object from a native Sketch model objectComponent.toJSON()
return a JSON object that represent the componentnew Component(properties)
creates a new native Sketch model object and returns a wrapped objectcomponentInstance.sketchObject
returns the native Sketch model object.componentInstance.isImmutable()
returns if the component is wrapping an immutable version of a native Sketch model object. If that is the case, you won’t be able to mutable the object (setting any property will be a no-op).componentInstance.type
returns a string that represent the type of the component. If it’sundefined
, it means that we couldn’t match the native object and that we returned a really lightweight wrapper.
Document
var Document = require('sketch/dom').Document
A Sketch document.
Properties | |
---|---|
idstring | The unique ID of the document. |
pagesPage[] | The pages of the document. |
Access the selected Document
var document = require('sketch/dom').getSelectedDocument()
// also exposed on Document
var document = Document.getSelectedDocument()
Returns
The selected Document or undefined
if no document is open.
Access all the open Documents
var documents = require('sketch/dom').getDocuments()
// also exposed on Document
var documents = Document.getDocuments()
Returns
An array of Documents.
Create a new Document
var document = new Document()
Open a Document
// ask the user to select a document
Document.open((err, document) => {
if (err) {
// oh no, we failed to open the document
}
// if the user cancel the opening, `document` will be `undefined`
})
// open a sketch document at the specified path
Document.open('path/to/the/document.sketch', (err, document) => {
if (err) {
// oh no, we failed to open the document
}
})
A method to open an existing sketch document or ask the user to open one. The method is asynchronous so if you want to do something after the document is opening it, make sure that you pass a callback and continue your script there.
Parameters | |
---|---|
pathstring | The path to the document to open. If undefined , the user will be asked to select one. |
callbackfunction | A function called after the document is opened. It is called with an Error if opening the Document was unsuccessful and a Document (or undefined ). |
Get the selected Page
var page = document.selectedPage
A read-only property to get the current page that the user has selected.
Returns
Return a Page object.
Get the selected Layers
var selection = document.selectedLayers
A read-only property to get the layers that the user has selected in the currently selected page.
Returns
Returns a Selection object.
Find a Layer by Id
var layer = document.getLayerWithID(layerId)
if (layer) {
// do something
}
A method to help find the first layer in this document which has the given id.
Parameters | |
---|---|
layerIdstring - required | The ID of the layer to find |
Returns
Return a Layer object or undefined
if it’s not found.
Find Layers by name
var layers = document.getLayersNamed(name)
if (layers.length) {
// do something
}
A method to help find the layers in this document which have the given name.
Parameters | |
---|---|
namestring - required | The name of the layers to find |
Returns
Return an array of Layer.
Get all the Shared Layer Styles
var layerStyles = document.getSharedLayerStyles()
A method to get all shared layer styles defined in the document.
Returns
Return an array of the layer SharedStyle objects defined in the document.
Find a Shared Layer Style
var sharedStyle = document.getSharedLayerStyleWithID(sharedStyleId)
A method to help find a shared style in the document.
Parameters | |
---|---|
sharedStyleIdstring - required | The ID of the shared style to find |
Returns
Return a SharedStyle object or undefined
if it’s not found.
Get all the Shared Text Styles
var textStyles = document.getSharedTextStyles()
A method to get all shared text styles defined in the document.
Returns
Return an array of the text SharedStyle objects defined in the document.
Find a Shared Text Style
var sharedStyle = document.getSharedTextStyleWithID(sharedStyleId)
A method to help find a shared style in the document.
Parameters | |
---|---|
sharedStyleIdstring - required | The ID of the shared style to find |
Returns
Return a SharedStyle object or undefined
if it’s not found.
Get all the Symbol Masters
var symbols = document.getSymbols()
A method to get all symbol masters defined in the document.
Returns
Return an array of the SymbolMaster objects defined in the document.
Find a Symbol Master
var symbolMaster = document.getSymbolMasterWithID(symbolInstance.symbolId)
A method to help find a symbol master in the document.
Parameters | |
---|---|
symbolIdstring - required | The symbol ID of the symbol master to find |
Returns
Return a SymbolMaster object or undefined
if it’s not found.
Center on Layer
document.centerOnLayer(layer)
A method to help center the view of the document window on a given layer.
Parameters | |
---|---|
layerLayer - required | The layer to center the view onto |
Save the Document
document.save()
document.save('path/to/the/document.sketch')
document.save('path/to/the/document.sketch', err => {
if (err) {
// saving the document failed :(
}
})
A method to save a document to a specific path or ask the user to choose where to save it. The method is asynchronous so if you want to do something after the document is saved, make sure that you pass a callback and continue your script there.
Parameters | |
---|---|
pathstring | The path where the document will be saved. If undefined , the user will be asked to select one. |
optionsobject | The options for the save operation (only used when specifying a path). |
options.saveModeSaveMode | The way to save the document. |
callbackfunction | A function called after the document is saved. It is called with an Error if saving the Document was unsuccessful. |
Close the Document
document.close()
A method to close a document.
Document.SaveMode
Document.SaveMode.SaveAs
document.save('path/to/the/document.sketch', {
saveMode: Document.SaveMode.SaveAs,
})
Enumeration of the save mode.
Value | |
---|---|
Save |
Overwrites a document’s file with the document’s contents |
SaveAs |
Writes a document’s contents to a new file and then changes the document’s current location to point to the just-written file |
SaveTo |
Writes a document’s contents to a new file without changing the document’s current location to point to the new file. |
Library
var Library = require('sketch/dom').Library
A Sketch Library.
Properties | |
---|---|
idstring - readonly | The unique ID of the Library. |
namestring - readonly | The name of the Library. |
validboolean - readonly | If Sketch has been able to load the Library. |
enabledboolean | If the user has enabled the Library. |
libraryTypeLibraryType - readonly | The type of Library. |
lastModifiedAtDate - readonly | The date at which the library was last updated |
Access all the Libraries
var libraries = require('sketch/dom').getLibraries()
// also exposed on Library
var libraries = Library.getLibraries()
Returns
An array of Libraries.
Get a Library from a path
var library = Library.getLibraryForDocumentAtPath(
'path/to/existing/document.sketch'
)
Get the library for a local Sketch document. If the Document was already added as a Library, it will simply return it. If it is not already a Library, it will be added.
Parameters | |
---|---|
pathstring - required | The path of the Library. |
Returns
The existing Library at the path or a new Library from the document at the path.
Get a remote Library from an RSS feed URL
Library.getRemoteLibraryWithRSS(
'https://url/to/feed/rss.xml',
(err, library) => {
if (err) {
// oh no, failed to load the library
}
}
)
Get the remote library for an RSS feed. If the RSS feed was already added as a Library, it will simply return it. If it is not already a Library, it will be added.
Parameters | |
---|---|
urlstring - required | The URL to the rss feed describing the versions of the library. |
callbackfunction | A function called after the library is added. It is called with an Error if adding the Library was unsuccessful and a Library (or undefined ). |
Remove a Library
library.remove()
A method to remove an existing library.
Get the Library’s Document
var libDocument = library.getDocument()
A library references a Sketch Document and you can access it with this method.
Returns
The Document that the Library references. It can throw an error if the Document cannot be accessed.
Get the Symbols that can be imported
var document = sketch.getSelectedDocument()
var symbolReferences = library.getImportableSymbolReferencesForDocument(
document
)
To import a symbol from a Library, do not access its Document and look for the SymbolMaster directly. Instead, get the Symbol References of the Library and use those to import them.
Those references depends on the document you want to import them into. For example if a document has already imported a symbol, it will reference the local version to keep all the instances in sync.
Returns
An array of Shareable Object that represents the Symbols which you can import from the Library.
Get the Shared Layer Styles that can be imported
var document = sketch.getSelectedDocument()
var stylesReferences = library.getImportableLayerStyleReferencesForDocument(
document
)
To import a shared style from a Library, do not access its Document and look for the SharedStyle directly. Instead, get the Shared Layer Style References of the Library and use those to import them.
Those references depends on the document you want to import them into. For example if a document has already imported a shared style, it will reference the local version to keep all the instances in sync.
Returns
An array of Shareable Object that represents the Shared Layer Styles which you can import from the Library.
Get the Shared Text Styles that can be imported
var document = sketch.getSelectedDocument()
var stylesReferences = library.getImportableTextStyleReferencesForDocument(
document
)
To import a shared style from a Library, do not access its Document and look for the SharedStyle directly. Instead, get the Shared Text Style References of the Library and use those to import them.
Those references depends on the document you want to import them into. For example if a document has already imported a shared style, it will reference the local version to keep all the instances in sync.
Returns
An array of Shareable Object that represents the Shared Layer Styles which you can import from the Library.
Library.LibraryType
Library.LibraryType.User
Enumeration of the types of Library.
Value |
---|
Internal |
User |
Remote |
Importable Object
var symbolReferences = library.getImportableSymbolReferencesForDocument(
document
)
An Object that can imported from a Library. All its properties are read-only.
Properties | |
---|---|
idstring | The unique ID of the Object. |
namestring | The name of the Object. |
objectTypeImportableObjectType | The type of the Object. Will only be Library.ImportableObjectType.Symbol for now. |
libraryLibrary | The Library the Object is part of. |
Import in the Document
var symbolMaster = symbolReference.import()
var sharedStyle = sharedStyleReference.import()
An Importable Object is linked to a Document so importing it will import it in the said Document.
Returns
If the objectType
of the Object is Symbol
, it will return a Symbol Master which will be linked to the Library (meaning that if the Library is updated, the Symbol Instances created from the Master will be updated as well).
Library.ImportableObjectType
Library.ImportableObjectType.Symbol
Enumeration of the types of Importable Objects.
Value |
---|
Symbol |
LayerStyle |
TextStyle |
Style
var Style = require('sketch/dom').Style
var shape = new Shape({
style: {
borders: [{ color: '#c0ffee' }],
},
})
shape.style.fills = [
{
color: '#c0ffee',
fillType: Style.FillType.Color,
},
]
The style of a Layer.
Properties | |
---|---|
opacitynumber | The opacity of a Layer, between 0 (transparent) and 1 (opaque). |
blendingModeBlendingMode | The opacity of a Layer, between 0 (transparent) and 1 (opaque). |
blurBlur | The blur applied to the Layer. |
fillsFill[] | The fills of a Layer. |
bordersBorder[] | The borders of a Layer. |
borderOptionsBorderOptions | The options that the borders share. |
shadowsShadow[] | The shadows of a Layer. |
innerShadowsShadow[] | The inner shadows of a Layer. |
Check if the Style is in sync with a Shared Style
var isOutOfSync = style.isOutOfSyncWithSharedStyle(sharedStyle)
Returns
Wether the Style has some differences with a Shared Style.
Sync the Style with a Shared Style
style.syncWithSharedStyle(sharedStyle)
The style instance will be updated with the value of the Shared Style.
var sharedStyle = styledLayer.sharedStyle
sharedStyle.style = style
The Shared Style value will be updated with the style.
Style.BlendingMode
Style.BlendingMode.Darken
Enumeration of the blending mode.
Value |
---|
Normal |
Darken |
Multiply |
ColorBurn |
Lighten |
Screen |
ColorDodge |
Overlay |
SoftLight |
HardLight |
Difference |
Exclusion |
Hue |
Saturation |
Color |
Luminosity |
Blur
shape.style.blur = {
center: {
x: 10,
y: 20,
},
type: Style.BlurType.Motion,
motionAngle: 10,
}
An object that represent the blur of the layer.
Properties | |
---|---|
blurTypeBlurType | The type of the blur. |
radiusnumber | The radius of the blur. |
motionAnglenumber | The angle of the blur (only used when the blur type is Motion ). |
centerobject | The center of the blur (only used when the blur type is Zoom . |
center.xnumber | The horizontal coordinate of the center of the blur. |
center.ynumber | The vertical coordinate of the center of the blur. |
enabledboolean | Wether the fill is active or not. |
Style.BlurType
Style.BlurType.Background
Enumeration of the type of a blur.
Value | |
---|---|
Gaussian |
A common blur type that will accurately blur in all directions. |
Motion |
Blur only in one direction, giving the illusion of motion. |
Zoom |
Will blur from one particular point out. |
Background |
This will blur any content that appears behind the layer. |
Fill
shape.style.fills = [
{
color: '#c0ffee',
fill: Style.FillType.Color,
},
]
An object that represent a Fill.
Properties | |
---|---|
fillFillType | The type of the fill. |
colorstring | A rgba hex-string (#000000ff is opaque black). |
gradientGradient | The gradient of the fill. |
enabledboolean | Wether the fill is active or not. |
Style.FillType
Style.FillType.Color
Enumeration of the types of fill.
Value |
---|
Color |
Gradient |
Pattern |
Noise |
Border
shape.style.borders = [
{
color: '#c0ffee',
fillType: Style.FillType.Color,
position: Style.BorderPosition.Inside,
},
]
An object that represent a Border.
Properties | |
---|---|
fillTypeFillType | The type of the fill of the border. |
colorstring | A rgba hex-string (#000000ff is opaque black). |
gradientGradient | The gradient of the fill. |
enabledboolean | Wether the border is active or not. |
positionBorderPosition | The position of the border. |
thicknessnumber | The thickness of the border. |
Style.BorderPosition
Style.BorderPosition.Center
Enumeration of the positions of a border.
Value |
---|
Center |
Inside |
Outside |
BorderOptions
shape.style.borderOptions = {
dashPattern: [20, 5, 20, 5],
}
An object that represent the options that the Borders of the Layer share.
Properties | |
---|---|
startArrowheadArrowhead | The type of the arrow head for the start of the path. |
endArrowheadArrowhead | The type of the arrow head for the start of the path. |
dashPatternnumber[] | The dash pattern of the borders. For example, a dash pattern of 4-2 will draw the stroke for four pixels, put a two pixel gap, draw four more pixels and then so on. A dashed pattern of 5-4-3-2 will draw a stroke of 5 px, a gap of 4 px, then a stroke of 3 px, a gap of 2 px, and then repeat. |
lineEndLineEnd | The type of the border ends (if visible). |
lineJoinLineJoin | The type of the border joins (if any). |
Style.Arrowheads
Style.Arrowheads.OpenArrow
Enumeration of the type of the Arrowheads for line layers.
Value |
---|
None |
OpenArrow |
FilledArrow |
Line |
OpenCircle |
FilledCircle |
OpenSquare |
FilledSquare |
Style.LineEnd
Style.LineEnd.Round
Enumeration of the positions of a border.
Value | |
---|---|
Butt |
This is the default option that’ll draw the border right to the vector point. |
Round |
Creates a rounded, semi-circular end to a path that extends past the vector point. |
Projecting |
Similar to the rounded cap, but with a straight edges. |
Style.LineJoin
Style.LineJoin.Miter
Enumeration of the positions of a border.
Value | |
---|---|
Miter |
This will simply create an angled, or pointy join. The default setting. |
Round |
Creates a rounded corner for the border. The radius is relative to the border thickness. |
Bevel |
This will create a chamfered edge on the border corner. |
Shadow
shape.style.shadows = [
{
color: '#c0ffee',
blur: 3,
},
]
shape.style.innerShadows = [
{
color: '#c0ffee',
blur: 3,
},
]
An object that represent a Shadow.
Properties | |
---|---|
colorstring | A rgba hex-string (#000000ff is opaque black). |
blurnumber | The blur radius of the shadow. |
xnumber | The horizontal offset of the shadow. |
ynumber | The vertical offset of the shadow. |
spreadnumber | The spread of the shadow. |
enabledboolean | Wether the fill is active or not. |
Gradient
shape.style.fills = [
{
fillType: Style.FillType.Gradient,
gradient: {
gradientType: Style.GradientType.Linear,
from: {
x: 0,
y: 0,
},
to: {
x: 50,
y: 50,
},
stops: [
{
position: 0,
color: '#c0ffee',
},
{
position: 0.5,
color: '#0ff1ce',
},
{
position: 1,
color: '#bada55',
},
],
},
},
]
An object that represent a Gradient.
Properties | |
---|---|
gradientTypeGradientType | The type of the Gradient. |
fromPoint | The position of the start of the Gradient |
toPoint | The position of the end of the Gradient. |
stopsGradientStop[] | The different stops of the Gradient |
Style.GradientType
Style.GradientType.Radial
Enumeration of the type of a Gradient.
Value | |
---|---|
Linear |
Linear gradients tend to be the most common, where two colors will appear at opposite points of an object and will blend, or transition into each other. |
Radial |
A radial gradient will create an effect where the transition between color stops will be in a circular pattern. |
Angular |
This effect allows you to create gradients that sweep around the circumference (measured by the maximum width or height of a layer) in a clockwise direction. |
Gradient Stops
An object that represent a Gradient Stop. Each of colors of a Gradient are represented by a Stop. A Gradient can have as many Stops as you’d like.
Properties | |
---|---|
positionnumber | The position of the Stop. 0 represents the start of the gradient while 1 represent the end. |
colorstring | The color of the Stop |
Shared Style
var SharedStyle = require('sketch/dom').SharedStyle
var sharedStyle = SharedStyle.fromStyle({
name: 'Header 1',
style: text.style,
document: document,
})
A shared style (either a layer style or a text style).
Properties | |
---|---|
idstring | The unique ID of the Shared Style. |
cSharedStyleType | The type of the Shared Style (Layer or Text ). |
namestring | The name of the Shared Style. |
styleStyle | The Style value that is shared. |
Create a new Shared Style from a Style
var sharedStyle = SharedStyle.fromStyle({
name: 'Header 1',
style: text.style,
document: document,
})
Create a new Shared Style with a specific name in a specific Document.
Parameters | |
---|---|
options.namestring - required | The name of the Shared Style. |
options.styleStyle - required | The Style instance to use for the value of the Shared Style. |
options.documentDocument - required | The Document in which the Shared Style will be created. |
Returns
A new SharedStyle
Get all the Instances
var styles = sharedStyle.getAllInstances()
Returns an array of all instances of the Shared Style in the document, on all pages.
Returns
A Style array.
Get all the Instances’ Layers
var layers = sharedStyle.getAllInstancesLayers()
Returns an array of all layers with a Style which is an instance of the Shared Style in the document, on all pages.
Returns
A Layer array.
Get the Library it was defined in
var originLibrary = sharedStyle.getLibrary()
If the SharedStyle was imported from a library, the method can be used to:
- know about it
- get the library back
Returns
The Library the Shared Style was defined in, or null
if it is a local shared style.
Sync the local reference with the library version
const success = sharedStyle.syncWithLibrary()
If a Library has some updates, you can synchronize the local Shared Style with the Library’s version and bypass the panel where the user chooses the updates to bring.
Returns
true
if it succeeded.
Unlink the local reference from the library
const success = sharedStyle.unlinkFromLibrary()
You can unlink a Shared Style from the Library it comes from and make it a local Shared Style instead.
Returns
true
if it succeeded.
SharedStyle.StyleType
SharedStyle.StyleType.Text
Enumeration of the type of Shared Style.
Value |
---|
Text |
Layer |
Symbol Override
var overrides = symbolInstance.overrides
A Symbol override. This component is not exposed, it is only returned when accessing the overrides
of a Symbol Instance.
Properties | |
---|---|
pathstring | The path to the override. It’s formed by the symbolId of the nested symbols separated by a / . |
propertystring | The property that this override controls. It can be "stringValue" for a text override, "symbolID" for a nested symbol, or "image" for an image override. |
idstring | The unique ID of the override (${path}_${property} ). |
symbolOverrideboolean | If the override is a nested symbol override. |
valueString / ImageData | The value of the override which can be change. |
isDefaultboolean | If the override hasn’t been changed and is the default value. |
affectedLayerText / Image / Symbol Instance | The layer the override applies to. It will be an immutable version of the layer |
Flow
var Flow = require('sketch/dom').Flow
The prototyping action associated with a layer.
Properties | |
---|---|
targetArtboard / Flow.BackTarget | The target artboard of the action or Flow.BackTarget if the action is a back action |
targetIdstring / Flow.BackTarget | The ID of target artboard of the action or Flow.BackTarget if the action is a back action |
animationTypeAnimationType | The type of the animation. |
Create a new prototyping action
layer.flow = {
target: artboard,
}
You can create a action without specifying an animation type, it will use the default one.
layer.flow = {
targetId: artboard.id,
}
You can create a action by using the ID of an Artboard instead of the artboard.
layer.flow = {
target: artboard,
animationType: Flow.AnimationType.slideFromLeft,
}
You can also specify the animation type.
layer.flow = {
target: Flow.BackTarget,
}
You can also create a back action.
Check if the action is a Back action
layer.flow.isBackAction()
Returns whether the prototyping action is a back action or not, eg. whether layer.flow.target === Flow.BackTarget
.
Check if the target is valid
layer.flow.isValidConnection()
In some cases, the target of the action can be invalid, for example when the target has been removed from the document. The methods returns whether the target is valid or not.
Flow.BackTarget
layer.flow = {
target: Flow.BackTarget,
}
Flow.BackTarget
is a constant that you can set the target to in order to always take you back to the last Artboard you were looking at. When a Target has been set to Flow.BackTarget
, the transition leading into it will be reversed on return.
Flow.AnimationType
Flow.AnimationType.slideFromLeft
Enumeration of the animation types.
Value | |
---|---|
none |
No animation |
slideFromLeft |
Slide from the left |
slideFromRight |
Slide from the right |
slideFromBottom |
Slide from the bottom |
slideFromTop |
Slide from the top |
Selection
var selection = document.selectedLayers
A utility class to represent the layers selection. Contains some methods to make interacting with a selection easier. All the properties are read-only.
Properties | |
---|---|
layersLayer[] | The Layers in the selection. |
lengthnumber | The number of Layers in the selection. |
isEmptyboolean | Does the selection contain any layers? |
map
, forEach
, and reduce
selection.forEach(layer => log(layer.id))
selection.map(layer => layer.id)
selection.reduce((initial, layer) => {
initial += layer.name
return initial
}, '')
Even though a selection isn’t an array, it defines map
, forEach
and reduce
by just forwarding the arguments its layers. Those are just convenience methods to avoid getting the layers every time.
Clear the Selection
selection.clear()
Clear the selection.
Returns
Return the selection (useful if you want to chain the calls).
Point
A utility class to represent a point.
Properties | |
---|---|
xnumber / Point | The x coordinate of the point. Or an object with {x, y} |
ynumber | The y coordinate of the point. |
Rectangle
var Rectangle = require('sketch/dom').Rectangle
var rect = new Rectangle(0, 0, 100, 100)
var rectFromAnotherRect = new Rectangle(rect)
A utility class to represent a rectangle. Contains some methods to make interacting with a rectangle easier.
Properties | |
---|---|
xnumber / Rectangle | The x coordinate of the top-left corner of the rectangle. Or an object with {x, y, width, height} |
ynumber | The y coordinate of the top-left corner of the rectangle. |
widthnumber | The width of the rectangle. |
heightnumber | The height of the rectangle. |
Offset the Rectangle
var newRect = rect.offset(x, y)
Adjust the rectangle by offsetting it.
Returns
Return this rectangle (useful if you want to chain the calls).
Scale the Rectangle
var newRect = rect.scale(scaleWidth, scaleHeight)
Adjust the rectangle by scaling it. The scaleHeight
argument can be omitted to apply the same factor on both the width and the height.
Returns
Return this rectangle (useful if you want to chain the calls).
Change the coordinates basis
var newRect = rect.changeBasis({
from: layerA,
to: layerB,
})
var parentRect = rect.changeBasis({
from: layerA,
to: layerA.parent,
})
var pageRect = rect.changeBasis({
from: layerA,
// leaving out `to` means changing the
// basis to the Page's basis
})
Each layer defines its own system of coordinates (with its origin at the top left of the layer). You can change that basis from one layer to the other with changeBasis
.
Parameters | |
---|---|
changeobject - required | |
change.fromLayer | The layer in which the rectangle’s coordinates are expressed. |
change.toLayer | The layer in which the rectangle’s coordinates will be expressed. |
Both from
and to
can be omitted (but not at the same time) to change the basis from/to the Page coordinates.
Get a CGRect
var cgRect = rect.asCGRect()
Return the Rectangle as a CGRect
.
fromNative
var sketch = require('sketch/dom')
var document = sketch.fromNative(context.document)
A utility function to get a wrapped object from a native Sketch model object.
Parameters | |
---|---|
objectNative Sketch Object | The native Sketch model object to wrap. |
Returns
The wrapped object of the right type (you can check is type with wrappedObject.type
), eg. a native document will be wrapped as a Document while a native text layer will be wrapped as a Text.
Layer
A Sketch layer. This is the base class for most of the Sketch components and defines methods to manipulate them..
Properties | |
---|---|
idstring | The unique ID of the Layer. |
namestring | The name of the Layer |
parentGroup | The group the layer is in. |
lockedboolean | If the layer is locked. |
hiddenboolean | If the layer is hidden. |
frameRectangle | The frame of the Layer. This is given in coordinates that are local to the parent of the layer. |
selectedboolean | If the layer is selected. |
flowFlow | The prototyping action associated with the layer. |
Duplicate the Layer
var duplicatedLayer = layer.duplicate()
A new identical layer will be inserted into the parent of this layer.
Returns
A new Layer.
Remove the Layer
layer.remove()
Remove this layer from its parent.
Returns
The current layer (useful if you want to chain the calls).
Get the position in the hierarchy
var index = layer.index
The index of this layer in its parent. The layer at the back of the parent (visually) will be layer 0
. The layer at the front will be layer n - 1
(if there are n
layers).
Move the Layer in the hierarchy
Move to the front
layer.moveToFront()
Move this layer to the front of its parent.
Returns
The current layer (useful if you want to chain the calls).
Move forward
layer.moveForward()
Move this layer forward in its parent.
Returns
The current layer (useful if you want to chain the calls).
Move to the back
layer.moveToBack()
Move this layer to the back of its parent.
Returns
The current layer (useful if you want to chain the calls).
Move backward
layer.moveBackward()
Move this layer backward in its parent.
Returns
The current layer (useful if you want to chain the calls).
Group
var Group = require('sketch/dom').Group
A group of layers. It is also an instance of Layer so all the methods defined there are available.
Properties | |
---|---|
idstring | The unique ID of the Group. |
namestring | The name of the Group |
parentGroup | The group the Group is in. |
frameRectangle | The frame of the Group. This is given in coordinates that are local to the parent of the layer. |
flowFlow | The prototyping action associated with the Group. |
styleStyle | The style of the Group. |
sharedStyleIdstring / null | The ID of the SharedStyle this Group is linked to if any. |
layersLayer[] | The layers that this component groups together. |
Create a new Group
new Group()
var group = new Group({
name: 'my name',
layers: [
{
type: sketch.Types.Text,
text: 'Hello world',
},
],
})
Adjust to fit its children
group.adjustToFit()
Adjust the group to fit its children.
Returns
The current group (useful if you want to chain the calls).
Page
var Page = require('sketch/dom').Page
A Sketch page. It is an instance of both Layer and Group so all the methods defined there are available.
Properties | |
---|---|
idstring | The unique ID of the Page. |
namestring | The name of the Page |
parentDocument | The document the page is in. |
layersLayer | The layers that this page has. |
frameRectangle | The frame of the page. |
Create a new Page
new Page()
new Page({
name: 'my page',
})
Get the selected Layers of the Page
var selection = document.selectedLayers
A read-only property to get the layers that the user has selected in the page.
Returns
Return a Selection object.
Artboard
var Artboard = require('sketch/dom').Artboard
A Sketch artboard. It is an instance of both Layer and Group so all the methods defined there are available.
Properties | |
---|---|
idstring | The unique ID of the Artboard. |
namestring | The name of the Artboard |
parentPage | The page the Artboard is in. |
layersLayer[] | The layers that this component groups together. |
frameRectangle | The frame of the Artboard. This is given in coordinates that are local to the parent of the layer. |
flowStartPointboolean | A Start Point allows you to choose where to start your prototype from. |
Create a new Artboard
new Artboard()
new Artboard({
name: 'my name',
flowStartPoint: true,
})
Shape
var Shape = require('sketch/dom').Shape
An image layer. It is an instance of Layer so all the methods defined there are available.
Properties | |
---|---|
idstring | The unique ID of the Shape. |
namestring | The name of the Shape |
parentGroup | The group the shape is in. |
frameRectangle | The frame of the Shape. This is given in coordinates that are local to the parent of the layer. |
flowFlow | The prototyping action associated with the Shape. |
styleStyle | The style of the Shape. |
sharedStyleIdstring / null | The ID of the SharedStyle this Shape is linked to if any. |
Create a new Shape
new Shape({
name: 'my shape',
})
Image
var Image = require('sketch/dom').Image
An image layer. It is an instance of Layer so all the methods defined there are available.
Properties | |
---|---|
idstring | The unique ID of the Image. |
namestring | The name of the Image |
parentGroup | The group the Image is in. |
frameRectangle | The frame of the Image. This is given in coordinates that are local to the parent of the layer. |
flowFlow | The prototyping action associated with the Image. |
styleStyle | The style of the Image. |
sharedStyleIdstring / null | The ID of the SharedStyle this Image is linked to if any. |
imageImageData | The actual image of the layer. |
Create a new Image
var imageLayer = new Image({
image: 'path/to/image.png',
})
The image property accept a wide range of input:
- an
ImageData
- a native
NSImage
- a native
NSURL
- a native
MSImageData
- a string: path to the file to load the image from
- an object with a
path
property: path to the file to load the image from - an object with a
base64
string: a base64 encoded image
ImageData
var imageData = imageLayer.image
imageData.nsimage // return a native NSImage
image.nsdata // return a native NSData representation of the image
An ImageData
is a wrapper around a native NSImage
.
You can access the native NSImage
with nsimage
or a native NSData
representation of the image with nsdata
.
Text
var Text = require('sketch/dom').Text
A text layer. It is an instance of Layer so all the methods defined there are available.
Properties | |
---|---|
idstring | The unique ID of the Text. |
namestring | The name of the Text |
parentGroup | The group the Text is in. |
frameRectangle | The frame of the Text. This is given in coordinates that are local to the parent of the layer. |
flowFlow | The prototyping action associated with the Text. |
styleStyle | The style of the Text. |
sharedStyleIdstring / null | The ID of the SharedStyle this Text is linked to if any. |
textstring | The string value of the text layer. |
alignmentAlignment | The alignment of the layer. |
lineSpacingLineSpacing | The line spacing of the layer. |
fixedWidthboolean | Wether the layer should have a fixed width or a flexible width. |
Create a new Text
var text = new Text({
text: 'my text',
alignment: Text.Alignment.center,
})
Adjust to fit its value
text.adjustToFit()
Adjust the Text to fit its value.
Returns
The current Text (useful if you want to chain the calls).
font
text.font = myNSFont
Set the font of the text layer.
Parameters | |
---|---|
fontNSFont - required | The font to set on the Text layer. |
systemFontSize
text.systemFontSize = 16
Set the font of the text layer as the system font of the given size.
Parameters | |
---|---|
pointSizenumber - required | The size of the font to set. |
fragments
var fragments = text.fragments
Returns a array of the text fragments for the text. Each one is a object containing a rectangle, and a baseline offset and the range of the fragment {rect, baselineOffset, range}
.
Text.Alignment
Text.Alignment.center
Enumeration of the alignments of the text.
Value | |
---|---|
left |
Visually left aligned |
right |
Visually right aligned |
center |
Visually centered |
justify |
Fully-justified. The last line in a paragraph is natural-aligned. |
natural |
Indicates the default alignment for script |
Text.LineSpacing
Text.LineSpacing.constantBaseline
Enumeration of the line spacing behaviour for the text.
Value | |
---|---|
constantBaseline |
Uses min & max line height on paragraph style |
variable |
Uses MSConstantBaselineTypesetter for fixed line height |
Symbol Master
var SymbolMaster = require('sketch/dom').SymbolMaster
A Symbol master. It is an instance of Artboard (hence of Layer and Group) so all the methods defined there are available.
Properties | |
---|---|
idstring | The unique ID of the Symbol Master object (not to be confused with symbolId ). |
namestring | The name of the Symbol Master |
parentGroup | The group the Symbol Master is in. |
frameRectangle | The frame of the Symbol Master. This is given in coordinates that are local to the parent of the layer. |
flowFlow | The prototyping action associated with the Symbol. |
symbolIdstring | The unique ID of the Symbol that the master and its instances share. |
Create a new Symbol Master
var master = new SymbolMaster({
name: 'my symbol master',
})
Create a new Symbol Master from an Artboard
var master = SymbolMaster.fromArtboard(artboard)
Replace the artboard with a symbol master.
Parameters | |
---|---|
artboardArtboard - required | The artboard to create the master from. |
Returns
A new SymbolMaster
Change to an Artboard
var artboard = master.toArtboard()
Replace the symbol master with an artboard and detach all its instances converting them into groups.
Returns
A new Artboard
Create a new Instance
var instance = master.createNewInstance()
Creates a new SymbolInstance linked to this master, ready for inserting in the document.
Returns
A new SymbolInstance
Get all the Instances
var instances = master.getAllInstances()
Returns an array of all instances of the symbol in the document, on all pages.
Get the Library it was defined in
var originLibrary = master.getLibrary()
If the Symbol Master was imported from a library, the method can be used to:
- know about it
- get the library back
Returns
The Library the symbol was defined in, or null
if it is a local symbol.
Sync the local reference with the library version
const success = master.syncWithLibrary()
If a Library has some updates, you can synchronize the local Symbol Master with the Library’s version and bypass the panel where the user chooses the updates to bring.
Returns
true
if it succeeded.
Unlink the local reference from the library
const success = master.unlinkFromLibrary()
You can unlink a Symbol Master from the Library it comes from and make it a local Symbol Master instead. It will be added to the Symbols
Page.
Returns
true
if it succeeded.
Symbol Instance
var SymbolInstance = require('sketch/dom').SymbolInstance
A Symbol instance. It is an instance of Layer so all the methods defined there are available.
Properties | |
---|---|
idstring | The unique ID of the Symbol Instance object (not to be confused with symbolId ). |
namestring | The name of the Symbol Instance |
parentGroup | The group the Symbol Instance is in. |
frameRectangle | The frame of the Symbol Instance. This is given in coordinates that are local to the parent of the layer. |
flowFlow | The prototyping action associated with the Symbol. |
styleStyle | The style of the Symbol Instance. |
symbolIdstring | The unique ID of the Symbol that the instance and its master share. |
masterSymbolMaster | The Symbol master that the instance is linked to. |
overridesOverride[] | The array of the overrides to modify the instance. |
Create a new Symbol Instance
var instance = new SymbolInstance({
name: 'my symbol instance',
symbolId: symbolId,
})
Create a new Symbol Instance from a Symbol Master
var instance = master.createNewInstance()
Creates a new SymbolInstance linked to this master, ready for inserting in the document.
Returns
A new SymbolInstance
Detach the instance
var group = instance.detach()
Replaces a group that contains a copy of the Symbol this instance refers to. Returns null
if the master contains no layers instead of inserting an empty group
Returns
A new Group or null
Set an Override value
instance.setOverrideValue(instance.overrides[0], 'overridden')
Change the value of the override.
Parameters | |
---|---|
overrideOverride - required | The override to change. |
valuestring / NSImage - required | The value of override to set. Can be a string or an NSImage or a symbolId depending on the type of the override. |
Returns
The current Symbol instance (useful if you want to chain the calls).
HotSpot
var HotSpot = require('sketch/dom').HotSpot
A Sketch hotspot. It is an instance of both Layer so all the methods defined there are available.
Properties | |
---|---|
idstring | The unique ID of the Artboard. |
namestring | The name of the Artboard |
parentPage | The page the Artboard is in. |
frameRectangle | The frame of the Artboard. This is given in coordinates that are local to the parent of the layer. |
flowFlow | The prototyping action associated with the layer. |
Create a new Hotspot
new HotSpot()
new HotSpot({
name: 'my name',
flow: {
target: artboard,
},
})
Create a new Hotspot from a Layer
var hotspot = HotSpot.fromLayer(layer)
Settings
var Settings = require('sketch/settings')
A set of functions to handle user settings. The settings are persisted when the user closes Sketch.
Get a plugin setting
var setting = Settings.settingForKey('my-key')
Return the value of a setting scoped to your plugin for a given key.
Parameters | |
---|---|
keystring - required | The setting to look up. |
Returns
The setting that was stored for the given key. undefined
if there was nothing.
Set a plugin setting
Settings.setSettingForKey('my-key', 0.1)
Store a value of a setting scoped to your plugin for a given key.
Parameters | |
---|---|
keystring - required | The setting to set. |
valueany - required | The value to set it to. |
Get a Sketch setting
var setting = Settings.globalSettingForKey('my-key')
Return the value of a Sketch setting for a given key.
Parameters | |
---|---|
keystring - required | The setting to look up. |
Returns
The setting that was stored for the given key. undefined
if there was nothing.
Set a Sketch setting
Settings.setGlobalSettingForKey('my-key', 0.1)
Store a value of a Sketch setting for a given key.
Parameters | |
---|---|
keystring - required | The setting to set. |
valueany - required | The value to set it to. |
Get a Layer setting
var setting = Settings.layerSettingForKey(layer, 'my-key')
Return the value of a setting for a given key on a specific Layer or DataOverride or Override.
Parameters | |
---|---|
layerLayer / DataOverride / Override - required | The layer on which a setting is stored. |
keystring - required | The setting to look up. |
Returns
The setting that was stored for the given key. undefined
if there was nothing.
Set a Layer setting
Settings.setLayerSettingForKey(layer, 'my-key', 0.1)
Store a value of a setting for a given key on a specific Layer or DataOverride or Override.
Parameters | |
---|---|
layerLayer / DataOverride / Override - required | The layer on which the setting is set. |
keystring - required | The setting to set. |
valueany - required | The value to set it to. |
Get a Document setting
var setting = Settings.documentSettingForKey(document, 'my-key')
Return the value of a setting for a given key on a specific document.
Parameters | Description |
---|---|
documentDocument - required | The document on which a setting is stored. |
keystring - required | The setting to look up. |
Returns
The setting that was stored for the given key. undefined
if there was nothing.
Set a Document setting
Settings.setDocumentSettingForKey(document, 'my-key', 0.1)
Store a value of a setting for a given key on a specific document.
Parameters | |
---|---|
documentDocument - required | The document on which the setting is set. |
keystring - required | The setting to set. |
valueany - required | The value to set it to. |
UI
var UI = require('sketch/ui')
A set of functions to show some user interfaces. The set is small on purpose. Any more complex UI should be provided by third party libraries and doesn’t need to be in the core.
Show a message
UI.message('Hello world!')
Show a small, temporary, message to the user. The message appears at the bottom of the selected document, and is visible for a short period of time. It should consist of a single line of text.
Parameters | |
---|---|
textstring - required | The message to show. |
documentDocument | The document to show the message into. |
Show an alert
UI.alert('my title', 'Hello World!')
Show an alert with a custom title and message. The alert is modal, so it will stay around until the user dismisses it by pressing the OK button.
Parameters | |
---|---|
titlestring - required | The title of the alert. |
textstring - required | The text of the message. |
Get a string input from the user
var string = UI.getStringFromUser("What's your name?", 'Appleseed')
Shows a simple input sheet which displays a message, and asks for a single string input.
Parameters | |
---|---|
messagestring - required | The prompt message to show. |
initialValuestring | The initial value of the input string. |
Returns
The string that the user input, or “null” (String) if the user clicked ‘Cancel’.
Make the user select an option
var options = ['Sketch']
var selection = UI.getSelectionFromUser(
"What's your favorite design tool?",
options
)
var ok = selection[2]
var value = options[selection[1]]
if (ok) {
// do something
}
Shows an input sheet which displays a popup with a series of options, from which the user is asked to choose.
Parameters | |
---|---|
messagestring - required | The prompt message to show. |
itemsstring[] - required | An array of option items. |
selectedIndexnumber | The index of the item to select initially. |
Returns
An array with a response code, the selected index and ok
. The code will be one of NSAlertFirstButtonReturn
or NSAlertSecondButtonReturn
. The selection will be the integer index of the selected item. ok
is the boolean code === NSAlertFirstButtonReturn
.
Data Supplier
var DataSupplier = require('sketch/data-supplier')
When your plugin supplies some data, don’t forget to set the suppliesData
field to true
in your manifest.json
!
Register a Data Supplier
var DataSupplier = require('sketch/data-supplier')
// onStartup would be the handler for the `Startup` action defined in the manifest.json
export function onStartup() {
DataSupplier.registerDataSupplier(
'public.text',
'My Custom Data',
'SupplyKey'
)
}
Register some data with a name and a key.
Parameters | |
---|---|
dataTypestring - required | The data type. Allowed values are public.text or public.image . |
dataNamestring - required | The data name, used as the menu item title for the data. |
actionstring - required | The name of the Action that will be dispatched when the user requests some data. See supplyData . |
Context of the action
When a user runs a Data plugin, Sketch will forward the request to your plugin, passing a context.data
object with all the information you need to fulfil the request:
Key | |
---|---|
context.data.key |
A unique key to identify the supply request. You need to pass it to the supply method untouched. |
context.data.items |
The array of native model objects for which we want some data. It can be either a native Text, a native Shape or a native DataOverride (a special object when the data is for an Override) |
var util = require('util')
var sketch = require('sketch/dom')
var DataSupplier = require('sketch/data-supplier')
// onSupplyKeyNeeded would be the handler for
// the `SupplyKey` action defined in the manifest.json
export function onSupplyKeyNeeded(context) {
var count = context.data.items.count()
var key = context.data.key
var items = context.data.items
// you will often want to get wrapped objects instead
// of the native ones supplied in the context
var wrappedItems = util.toArray(items).map(sketch.fromNative)
}
Supply the Data
You have two different methods to supply data from your plugin: supplyData
(to provide all the data at once), and supplyDataAtIndex
(to provide data one by one).
Supply all the data in one go
var DataSupplier = require('sketch/data-supplier')
// onSupplyKeyNeeded would be the handler for
// the `SupplyKey` action defined in the manifest.json
export function onSupplyKeyNeeded(context) {
var count = context.data.items.count()
var key = context.data.key
var data = Array.from(Array(count)).map(i => 'foo')
DataSupplier.supplyData(key, data)
}
When the plugin providing the dynamic data has finished generating the data (could be an asynchronous operation), it will call this function with the data key and the data.
Parameters | |
---|---|
keystring - required | Should be equal to context.data.key |
datastring[] - required | The list of values to provide. In case of public.image , the string is the path to the image. |
Supply the data one by one
var util = require('util')
var sketch = require('sketch/dom')
var DataSupplier = require('sketch/data-supplier')
// onSupplyKeyNeeded would be the handler for
// the `SupplyKey` action defined in the manifest.json
export function onSupplyKeyNeeded(context) {
var key = context.data.key
var items = util.toArray(context.data.items).map(sketch.fromNative)
items.forEach((item, i) => {
// item is either a Layer or a DataOverride
DataSupplier.supplyDataAtIndex(key, 'foo', i)
})
}
When the plugin providing the dynamic data has finished generating the datum (could be an asynchronous operation), it will call this function with the data key and the datum.
Parameters | |
---|---|
keystring - required | Should be equal to context.data.key |
datumstring - required | The value to provide. In case of public.image , the string is the path to the image. |
indexnumber - required | The index of the item you are providing a value for. |
DataOverride
A special object passed in the context of the action to supply data when the item is an Override.
Properties | |
---|---|
idstring | The name of the override. |
overrideOverride | The override whose value will replaced by the supplied data. |
symbolInstanceSymbolInstance | The symbol instance that the override is on that will have the data replaced. |
Deregister your Data Suppliers
var DataSupplier = require('sketch/data-supplier')
// onShutdown would be the handler for the `Shutdown` action defined in the manifest.json
export function onShutdown() {
DataSupplier.deregisterDataSuppliers()
}
When registering something, it’s good practice to clean up after it. This is specially useful when your plugin is updated: the Shutdown
Action will be called before the Startup
will. It gives you the opportunity to update your handler cleanly.
async
var fiber = require('sketch/async').createFiber()
longRunningTask(function(err, result) {
fiber.cleanup()
// you can continue working synchronously here
})
By default, Sketch cleans up your script as soon as its call-stack is empty. So if you schedule an asynchronous task, chances are that when the task returns, your script will be cleaned up and it will crash Sketch.
A fiber is a way to keep track of a asynchronous task. The script will stay alive as long as at least one fiber is running.
To end a fiber, call fiber.cleanup()
. This will tell Sketch that it can garbage collect the script if no other fiber is running.
You can run a function when the fiber is about to be cleaned up by setting a callback: fiber.onCleanup(function () {...})
. Always do your clean up in this function instead of doing before calling fiber.cleanup
: there might be some cases where the fiber will be cleaned up by Sketch so you need to account for that.
export
var sketch = require('sketch/dom')
sketch.export(layer, {
formats: 'svg',
})
sketch.export([layer, layer2])
const options = { scales: '1, 2, 3', formats: 'png, jpg' }
sketch.export(page, options)
sketch.export(document.pages)
Export an object, using the options supplied.
Parameters | |
---|---|
objectToExportLayer / Layer[] / Page / Page[] | The object to export. |
optionsobject | Options indicating which sizes and formats to use, etc.. |
options.outputstring | this is the path of the folder where all exported files are placed (defaults to "~/Documents/Sketch Exports" ). |
options.formatsstring | Comma separated list of formats to export to (png , jpg , svg or pdf ) (default to "png" ). |
options.scalesstring | Comma separated list of scales which determine the sizes at which the layers are exported (defaults to "1" ). |
options[‘use-id-for-name’]boolean | Name exported images using their id rather than their name (defaults to false ). |
options[‘group-contents-only’]boolean | Export only layers that are contained within the group (default to false ). |
options.overwritingboolean | Overwrite existing files (if any) with newly generated ones (defaults to false ). |
options.trimmedboolean | Trim any transparent space around the exported image (defaults to false ). |
options[‘save-for-web’]boolean | If exporting a PNG, remove metadata such as the colour profile from the exported file (defaults to false ). |
options.compactboolean | If exporting a SVG, make the output more compact (defaults to false ). |
options[‘include-namespaces’]boolean | If exporting a SVG, include extra attributes (defaults to false ). |
options.progressiveboolean | If exporting a JPG, export a progressive JPEG (only used when exporting to jpeg ) (defaults to false ). |
options.compressionnumber | If exporting a JPG, the compression level to use fo jpeg (with 0 being the completely compressed, 1.0 no compression) (defaults to 1.0 ). |