# Document
```javascript
var Document = require('sketch/dom').Document
```
A Sketch document.
| Properties | |
| --- | --- |
| idstring | The unique ID of the document. |
| pages[Page](#page)[] | The pages of the document. |
| selectedPage[Page](#page) | The selected page of the Document. |
| selectedLayers[Selection](#selection) | The Selection of the layers that the user has selected in the currently selected page. |
| pathstring | The path to the document (or the appcast URL in case of a Document from a remote Library). |
| sharedLayerStyles[SharedStyle](#shared-style)[] | The list of all shared layer styles defined in the document. |
| sharedTextStyles[SharedStyle](#shared-style)[] | The list of all shared text styles defined in the document. |
| colors[ColorAsset](#color-asset)[] | A list of color assets defined in the document. Mutating the returned array will update the document colors. |
| swatches[Swatch](#swatch)[] | A list of swatches defined in the document. Mutating the returned array will update the document swatches. |
| gradients[GradientAsset](#gradient-asset)[] | A list of gradient assets defined in the document. Mutating the returned array will update the document gradients. |
| colorSpace[ColorSpace](#documentcolorspace) | The color space of the document. |
## Access the selected Document
```javascript
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
```javascript
var documents = require('sketch/dom').getDocuments()
// also exposed on Document
var documents = Document.getDocuments()
```
### Returns
An array of Documents.
## Create a new Document
```javascript
var document = new Document()
```
## Open a Document
```javascript
// 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`). |
## Find a Layer by Id
```javascript
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](#layer) object or `undefined` if it's not found.
## Find Layers by name
```javascript
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](#layer).
## Find a Shared Layer Style
```javascript
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](#shared-style) object or `undefined` if it's not found.
## Find a Shared Text Style
```javascript
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](#shared-style) object or `undefined` if it's not found.
## Get all the Symbol Sources
```javascript
var symbols = document.getSymbols()
```
A method to get all Symbol Sources defined in the document.
### Returns
Return an array of the [SymbolMaster](#symbol-source) objects defined in the document.
## Find a Symbol Source
```javascript
var source = document.getSymbolMasterWithID(symbolInstance.symbolId)
```
A method to help find a Symbol Source in the document.
| Parameters | |
| --- | --- |
| symbolIdstring - required | The Symbol ID of the Symbol Source to find |
### Returns
Return a [SymbolMaster](#symbol-source) object or `undefined` if it's not found.
## Center on Layer
```javascript
document.centerOnLayer(layer)
```
A method to help center the view of the document window on a given layer.
| Parameters | |
| --- | --- |
| layer[Layer](#layer) - required | The layer to center the view onto |
## Zoom to Fit
```js
document.zoomToFitCanvas()
```
A method to adjust the zoom level and scroll position to fit all layers of the current page in the canvas viewport.
## Save the Document
```javascript
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.saveMode[SaveMode](#savemode) | 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
```javascript
document.close()
```
A method to close a document.
## Change the color space
```javascript
// By default the method assigns a new color space
document.changeColorSpace(ColorSpace.sRGB)
console.log(document.colorSpace === ColorSpace.sRGB) // true
// Pass true as an optional second argument
// to convert instead of assign
document.changeColorSpace(ColorSpace.P3, true)
console.log(document.colorSpace === ColorSpace.P3) // true
// Alternatively, use the property setter (the behaviour
// here is to always assign the color space)
document.colorSpace = ColorSpace.P3
console.log(document.colorSpace === ColorSpace.P3) // true
// Create a document with a pre-defined color space
const p3Doc = new Document({ colorSpace: ColorSpace.P3 })
```
A method to change a document's color space. For an in-depth discussion of this topic and the difference between assigning and converting the color space check the [color management](https://www.sketch.com/docs/other/color-management/) documentation.
## `Document.SaveMode`
```javascript
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. |
## `Document.ColorSpace`
```javascript
Document.ColorSpace.sRGB
Document.ColorSpace.P3
```
Enumeration of the available color space settings.
| Value | |
| ----------- | -------------------------------- |
| `sRGB` | sRGB color profile (the default) |
| `P3` | Display P3 color profile |
| `Unmanaged` | (Deprecated) |
# Library
```javascript
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. If the library is not valid, the methods will often not be available so always check this field before doing something with a library. |
| enabledboolean | If the user has enabled the Library. |
| libraryType[LibraryType](#librarylibrarytype) - readonly | The type of Library. |
| lastModifiedAtDate - readonly | The date at which the library was last updated |
## Access all the Libraries
```javascript
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
```javascript
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
```javascript
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
```javascript
library.remove()
```
A method to remove an existing library.
## Get the Library's Document
```javascript
var libDocument = library.getDocument()
```
A library references a Sketch [Document](#document) and you can access it with this method.
### Returns
The [Document](#document) that the Library references. It can throw an error if the Document cannot be accessed.
## Get the Symbols that can be imported
```javascript
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 Symbol Source directly. Instead, get the [Symbol References](#importable-object) 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](#importable-object) that represents the Symbols which you can import from the Library.
## Get the Shared Layer Styles that can be imported
```javascript
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](#importable-object) 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](#importable-object) that represents the Shared Layer Styles which you can import from the Library.
## Get the Shared Text Styles that can be imported
```javascript
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](#importable-object) 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](#importable-object) that represents the Shared Layer Styles which you can import from the Library.
## Get the Shared Swatches that can be imported
```javascript
var document = sketch.getSelectedDocument()
var stylesReferences = library.getImportableSwatchReferencesForDocument(
document
)
```
To import a Swatch from a Library, do **not** access its Document and look for the Swatch directly. Instead, get the [Shared Swatch References](#importable-object) 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 Swatch, it will reference the local version to keep all the instances in sync.
### Returns
An array of [Shareable Object](#importable-object) that represents the Shared Swatches which you can import from the Library.
## `Library.LibraryType`
```javascript
Library.LibraryType.LocalUser
```
Enumeration of the types of Library.
| Value |
| ------------------ |
| `Internal` |
| `LocalUser` |
| `RemoteUser` |
| `RemoteTeam` |
| `RemoteThirdParty` |
# Importable Object
```javascript
var symbolReferences = library.getImportableSymbolReferencesForDocument(
document
)
```
An Object that can be imported from a [Library](#library). All its properties are read-only.
| Properties | |
| --- | --- |
| idstring | The unique ID of the Object. |
| namestring | The name of the Object. |
| objectType[ImportableObjectType](#libraryimportableobjecttype) | The type of the Object. Will only be `Library.ImportableObjectType.Symbol` for now. |
| library[Library](#library) | The Library the Object is part of. |
## Import in the Document
```javascript
var symbol = symbolReference.import()
var style = 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 Source](#symbol-source) which will be linked to the Library (meaning that if the Library is updated, the [Symbol Instances](#symbol-instance) created from the Source will be updated as well).
## `Library.ImportableObjectType`
```javascript
Library.ImportableObjectType.Symbol
```
Enumeration of the types of Importable Objects.
| Value |
| ------------ |
| `Symbol` |
| `LayerStyle` |
| `TextStyle` |
| `Swatch` |
# Style
```javascript
const { Style } = require('sketch')
```
```javascript
var shape = new Shape({
style: {
borders: [{ color: '#c0ffee' }],
},
})
shape.style.fills = [
{
color: '#c0ffee',
fillType: Style.FillType.Color,
},
]
text.style.textUnderline = 'double dash-dot'
```
The style of a Layer.
| Properties | |
| --- | --- |
| opacitynumber | The opacity of a Layer, between 0 (transparent) and 1 (opaque). |
| blendingMode[BlendingMode](#styleblendingmode) | The blend mode used to determine the composite color. |
| blurs[Blur](#blur) | The blurs applied to the Layer. Contains either one or zero items. |
| fills[Fill](#fill)[] | The fills of a Layer. |
| borders[Border](#border)[] | The borders of a Layer. |
| borderOptions[BorderOptions](#borderoptions) | The options that the borders share. |
| shadows[Shadow](#shadow)[] | The shadows of a Layer. |
| innerShadows[Shadow](#shadow)[] | The inner shadows of a Layer. |
| corners[Corners](#corners) | The corners of a Layer and their radii if set. |
| progressiveAlpha[Gradient](#gradient) / undefined | The progressive alpha gradient of a Layer or `undefined` if there's none. |
| Group-specific properties | |
| --- | --- |
| `tint`[Fill](#fill) / undefined | The [Tint](https://www.sketch.com/docs/symbols-and-styles/styling/tints/) color fill of a Group. |
| Text-specific properties | |
| --- | --- |
| alignment[Alignment](#textalignment) | The horizontal alignment of the text of a Text Layer |
| verticalAlignment[VerticalAlignment](#textverticalalignment) | The vertical alignment of the text of a Text Layer |
| kerningnumber / `null` | The kerning between letters of a Text Layer. `null` means that the kerning will be the one defined by the font. |
| lineHeightnumber / `null` | The height of a line of text in a Text Layer. `null` means "automatic". |
| paragraphSpacingnumber | The space between 2 paragraphs of text in a Text Layer. |
| textColorstring | A rgba hex-string (`#000000ff` is opaque black) of the color of the text in a Text Layer. |
| textSwatch[Swatch](#swatch) / undefined | A Color Variable associated with a Text Layer's text color. |
| fontSizenumber | The size of the font in a Text Layer. |
| textTransform'none' / 'uppercase' / 'lowercase' | The transform applied to the text of a Text Layer. |
| fontFamilystring | The name of the font family of a Text Layer. `'system'` means the font family of the OS (`'.SF NS Text'` on macOS 10.14). |
| fontWeightnumber | The weight of the font of a Text Layer. Goes from 0 to 12, 0 being the thinest and 12 being the boldest. Not every weight are available for every fonts. When setting a font weight that does not exist for the current font family, the closest weight that exists will be set instead. |
| fontStyle'italic' / undefined | The style of the font of a Text Layer. |
| fontVariant'small-caps' / undefined | The variant of the font of a Text Layer. |
| fontStretch'compressed' / 'condensed' / 'narrow' / 'expanded' / 'poster' / undefined | The size variant of the font of a Text Layer. |
| textUnderlinestring: ` [] ['by-word']` / undefined where `` can be `single` / `thick` / `double` and `` can be `dot` / `dash` / `dash-dot` / `dash-dot-dot` | The underline decoration of a Text Layer. |
| textStrikethroughstring: ` [] ['by-word']` / undefined where `` can be `single` / `thick` / `double` and `` can be `dot` / `dash` / `dash-dot` / `dash-dot-dot` | The strikethrough decoration of a Text Layer. |
| fontAxes[FontAxes](#font-axes) | The axes of the Text Layer font (only available when the font is a variable font). |
## Get the default line height
```javascript
var defaultlineHeight = style.getDefaultLineHeight()
```
When no line height is specified, `style.lineHeight` will be `undefined`. You can get the default line height of the font using `style.getDefaultLineHeight()`.
### Returns
A number if the layer is a Text layer or `undefined`.
## Check if the Style is in sync with a Shared Style
```javascript
var isOutOfSync = style.isOutOfSyncWithSharedStyle(sharedStyle)
```
### Returns
Whether the Style has some differences with a [Shared Style](#shared-style).
## Sync the Style with a Shared Style
```javascript
style.syncWithSharedStyle(sharedStyle)
```
The style instance will be updated with the value of the Shared Style.
```javascript
var sharedStyle = styledLayer.sharedStyle
sharedStyle.style = style
```
The Shared Style value will be updated with the style.
## `Style.BlendingMode`
```javascript
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` |
| `PlusDarker` |
| `PlusLighter` |
## Blur
```javascript
shape.style.blurs = [
{
blurType: Style.BlurType.Motion,
motionAngle: 10,
enabled: true,
},
]
shape.style.blurs = [] // to delete a blur
```
An object that represents the blur of the layer.
| Common Properties | |
| --- | --- |
| blurType[BlurType](#styleblurtype) | The type of the blur. |
| radiusnumber | The radius of the blur. |
| enabledboolean | Whether the blur is active or not. |
| Glass Properties | |
| --- | --- |
| brightnessnumber in [0.0, 2.0] | The brightness of the custom Glass. |
| distortionnumber in [0.0, 1.0] | The distortion effect of the custom Glass. |
| depthnumber in [0.0, 1.0] | The depth effect of the custom Glass. |
| chromaticAberrationnumber in [0.0, 1.0] | The chromatic aberration effect multiplier of the custom Glass. |
| saturationnumber in [0.0, 2.0] | The saturation value of the custom Glass. |
| hasSpecularHighlightsboolean | Whether this custom Glass has specular highlights enabled. |
| isCustomGlassboolean | (Deprecated and always equals `true`: Auto Glass has been removed in Sketch 2025.3). |
| Progressive Blur Properties | |
| --- | --- |
| progressiveboolean | Whether the blur is progressive. |
| gradient[Gradient](#gradient) | The gradient of the progressive blur. |
| Motion Blur Properties | |
| --- | --- |
| motionAnglenumber | The angle of the `Motion` blur. |
| Zoom Blur Properties | |
| --- | --- |
| centerobject | The center of the `Zoom` blur. |
| center.xnumber | The horizontal coordinate of the center of the `Zoom` blur. |
| center.ynumber | The vertical coordinate of the center of the `Zoom` blur. |
| Background Blur Properties | |
| --- | --- |
| saturationnumber in [0.0, 2.0] | The saturation value of the `Background` blur. |
### `Style.BlurType`
```javascript
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. |
| `Glass` | This will add the visual appearance of frosted glass to the affected layer. |
### Glass
```js
const { Style } = require('sketch')
layer.style.blurs = [
{
blurType: Style.BlurType.Glass,
enabled: true,
},
]
if (blur.blurType === sketch.Style.BlurType.Glass) {
// The Glass parameters could be adjusted as follows
// to match user-visible values in the Inspector
console.log(`Blur: ${blur.radius}`)
console.log(`Distortion: ${blur.distortion * 100}`)
console.log(`Depth: ${blur.depth * 100}`)
console.log(`Chromatic Aberration: ${blur.chromaticAberration * 100}`)
console.log(`Brightness: ${(blur.brightness - 1) * 100}`)
console.log(`Saturation: ${(blur.saturation - 1) * 100}`)
console.log(`Specular Highlights: ${blur.hasSpecularHighlights}`)
}
```
Since Glass is just another type of `Blur`, you may access its properties like you would with a regular `Blur`:
```js
if (blur.progressive) {
console.log(`${blur.gradient.from} => ${blur.gradient.to}`)
if (blur.gradient.gradientType === Style.GradientType.Linear) {
// ..
}
blur.gradient.stops.forEach((stop) => {
const progression = stop.alpha
// ...
})
}
```
### Progressive Blur
Use the `Blur.progressive` and `Blur.gradient` properties to access a gradient of a particular Progressive Blur:
## Fill
```javascript
shape.style.fills = [
{
color: '#c0ffee',
fillType: Style.FillType.Color,
},
]
```
An object that represents a Fill. `color`, `gradient` and `pattern` will always be defined regardless of the type of the fill.
| Properties | |
| --- | --- |
| fillType[FillType](#stylefilltype) | The type of the fill. |
| colorstring | A rgba hex-string (`#000000ff` is opaque black). |
| swatch[Swatch](#swatch) / undefined | A Color Variable associated with the fill. |
| gradient[Gradient](#gradient) | The gradient of the fill. |
| patternobject | The pattern of the fill. |
| pattern.patternType[PatternFillType](#stylepatternfilltype) | How the pattern should fill the layer. |
| pattern.image[ImageData](#imagedata) / `null` | The image of tile of the pattern. |
| pattern.tileScalenumber | The scale applied to the tile of the pattern. |
| enabledboolean | Whether the fill is active or not. |
| blendingMode[BlendingMode](#styleblendingmode) | The blend mode used to determine the composite color. |
## `Style.FillType`
```javascript
Style.FillType.Color
```
Enumeration of the types of fill.
| Value |
| ---------- |
| `Color` |
| `Gradient` |
| `Pattern` |
## `Style.PatternFillType`
```javascript
Style.PatternFillType.Fit
```
Enumeration of the types of pattern fill.
| Value |
| --------- |
| `Tile` |
| `Fill` |
| `Stretch` |
| `Fit` |
## Border
```javascript
shape.style.borders = [
{
color: '#c0ffee',
fillType: Style.FillType.Color,
position: Style.BorderPosition.Inside,
},
]
```
An object that represents a Border.
| Properties | |
| --- | --- |
| fillType[FillType](#stylefilltype) | The type of the fill of the border. |
| colorstring | A rgba hex-string (`#000000ff` is opaque black). |
| swatch[Swatch](#swatch) / undefined | A Color Variable associated with the border. |
| gradient[Gradient](#gradient) | The gradient of the fill. |
| enabledboolean | Whether the border is active or not. |
| position[BorderPosition](#styleborderposition) | The position of the border. |
| thicknessnumber | The thickness of the border. |
| blendingMode[BlendingMode](#styleblendingmode) | The blend mode used to determine the composite color. |
| hasIndividualSidesboolean | Whether the border has per-side thickness. |
| sidesobject | An object that contains individual thickness values for `left`, `top`, `right`, and `bottom` border sides. |
## `Style.BorderPosition`
```javascript
Style.BorderPosition.Center
```
Enumeration of the positions of a border.
| Value |
| --------- |
| `Center` |
| `Inside` |
| `Outside` |
## Individual Borders
```js
if (style.border.hasIndividualSides) {
console.log(border.sides)
// Outputs:
// {
// left: 5,
// top: 10,
// right: 10,
// bottom: 10
// }
// Reset to a uniform thickness
style.border.sides = null
}
```
Rectangles, Frames, and Graphics support per-side border thickness:
## BorderOptions
```javascript
shape.style.borderOptions = {
dashPattern: [20, 5, 20, 5],
}
```
An object that represents the options that the Borders of the Layer share.
| Properties | |
| --- | --- |
| startArrowhead[Arrowhead](#stylearrowhead) | The type of the arrow head for the start of the path. |
| endArrowhead[Arrowhead](#stylearrowhead) | 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. |
| lineEnd[LineEnd](#stylelineend) | The type of the border ends (if visible). |
| lineJoin[LineJoin](#stylelinejoin) | The type of the border joins (if any). |
## `Style.Arrowhead`
```javascript
Style.Arrowhead.OpenArrow
```
Enumeration of the type of the Arrowhead for line layers.
| Value |
| -------------- |
| `None` |
| `OpenArrow` |
| `FilledArrow` |
| `Line` |
| `OpenCircle` |
| `FilledCircle` |
| `OpenSquare` |
| `FilledSquare` |
## `Style.LineEnd`
```javascript
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`
```javascript
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
```javascript
shape.style.shadows = [
{
color: '#c0ffee',
blur: 3,
},
]
```
```javascript
shape.style.innerShadows = [
{
color: '#c0ffee',
blur: 3,
},
]
```
An object that represents a Shadow.
| Properties | |
| --- | --- |
| colorstring | A rgba hex-string (`#000000ff` is opaque black). |
| swatch[Swatch](#swatch) / undefined | A Color Variable associated with the shadow. |
| 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 | Whether the fill is active or not. |
| isInnerShadowboolean | Whether this shadow is an inner shadow or a drop (regular) shadow. |
| blendingMode[BlendingMode](#styleblendingmode) | The blend mode used to determine the composite color. |
## Gradient
```javascript
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 represents a Gradient.
| Properties | |
| --- | --- |
| gradientType[GradientType](#stylegradienttype) | The type of the Gradient. |
| from[Point](#point) | The position of the start of the Gradient |
| to[Point](#point) | The position of the end of the Gradient. |
| aspectRationumber | When the gradient is `Radial`, the from and to points makes one axis of the ellipse of the gradient while the aspect ratio determine the length of the orthogonal axis (`aspectRatio === 1` means that it's a circle). |
| stops[GradientStop](#gradientstop)[] | The different stops of the Gradient |
## `Style.GradientType`
```javascript
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 represents 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. |
| swatch[Swatch](#swatch) / undefined | A Color Variable associated with the Stop. |
| alphanumber | The alpha value of the Stop's color. |
## Corners
An object that describes corner radii and style of a Layer.
```js
const { Style } = require('sketch')
layer.style.corners.style = Style.CornerStyle.Smooth
layer.style.corners.smoothing = 0.6
layer.style.corners.radii = 10
layer.style.corners.radii = [10]
layer.style.corners.radii = [10, 20, 30]
if (layer.style.corners.hasRadii) {
console.log('This layer has a non-zero corner radius')
}
```
| Properties | |
| --- | --- |
| style[CornerStyle](#stylecornerstyle) | The style of corners. |
| radiinumber \| number[] | A corner radius clockwise (starting at top-left) for rectangular layers or one for points on a shape path. Values are repeated until they fit the required points. |
| hasRadiiboolean | Whether there's any corner radius set that wouldn't result in the layer effectively having 0 radius. |
| concentricboolean | Whether the layer has [concentric](#concentric-corners) corners. |
| smoothingnumber in [0.0, 1.0] | The amount of smoothing to apply to corners when the style is `Style.CornerStyle.Smooth`. The default value is `0.6`. |
### `Style.CornerStyle`
| Value |
| -------------- |
| `Auto` |
| `Rounded` |
| `Smooth` |
| `Angled` |
| `InsideSquare` |
| `InsideArc` |
### `Corners.radiusAt(number)`
`Corners.radiusAt()` returns the radius of a layer's corner at the given index, iterating any previously set radii values as many times as necessary to find a matching value.
```js
layer.style.corners.radii = [10, 20]
```
For instance, let's say we have a shape with 8 corners. We can only set radii for the first two.
```js
const radius = layer.style.corners.radiusAt(7)
console.log(`Radius no.7 is ${radius} as well`)
// 👉 Radius no.7 is 20 as well
```
And let Sketch interpolate values for the other corners from the two set.
### Concentric Corners
A concentric corner follows the curvature of its ancestor Frame that also has corner radii. This may not be the immediate parent Frame but also one higher up. The curvature is followed by taking the parent corner radius into account, any padding it has and the layer's distance to that Frame.
```js
const frame = new Group({
groupBehavior: GroupBehavior.Frame,
frame: new Rectangle(0, 0, 100, 100),
style: {
corners: { radii: 20 },
},
verticalSizing: FlexSizing.Fixed,
horizontalSizing: FlexSizing.Fixed,
})
```
For instance, let's create a Frame and set its radii to `20`.
```js
const shape = new ShapePath({
style: {
fills: [{ color: '#ffaa00' }],
corners: { concentric: true },
},
frame: new Rectangle(10, 10, 80, 80),
verticalSizing: FlexSizing.Relative,
horizontalSizing: FlexSizing.Relative,
})
frame.layers.push(shape)
```
Now insert a shape with concentric corners into this Frame with a uniform padding of `10`.
```js
console.log(`Auto corner radius: ${layer.style.corners.radii}`)
// 👉 Auto corner radius: [10]
```
Inspecting the shape's corner radius we'll see that it's been automatically calculated to be `10`.
```js
parent.frame = new Rectangle(0, 0, 80, 80)
console.log(`New corner radius: ${layer.style.corners.radii}`)
// 👉 New corner radius: [12]
```
Now let's shrink the parent Frame and see the shape's corner radius being _increased_ accordingly.
#### Concentric Corners and Corner Styles
```js
layer.style.corners.concentric = true
const isAutoCorners = layer.style.corners.style === Style.CornerStyle.Auto
console.log(`Auto mode? ${isAutoCorners}`)
// 👉 Auto mode? true
```
Setting the `concentric` flag on layer's corners switches them to `Style.CornerStyle.Auto` mode.
```js
layer.style.corners.radii = 10
// 👉 `corners.style` is reset to `Style.CornerStyle.Rounded`
// 👉 `corners.concentric` is reset to `false`
```
Assigning values to any other property after that will switch the concentric flag back to `false`.
## Font Axes
```javascript
// Get the axes
const axes = textLayer.style.fontAxes
// If axes is non-null the Text Layer's font
// is a valid variable font recognised by Sketch
if (axes) {
// Mutate the axes object, taking care
// to work within the min and max range
// specified for each axis
axes.Weight.value = axes.Weight.max
axes.Monospace.value = 1
// Apply the new axes to update
// the text layer
textLayer.style.fontAxes = axes
}
```
The `fontAxes` property allows you to adjust the parameters, or "axes", exposed by [variable fonts](https://blog.sketchapp.com/variable-fonts-improved-opentype-support-and-a-new-data-plugin-whats-new-in-sketch-e16f81bf8b75).
It works by allowing you to get and set an object representing the axes for a Text Layer's current font. The object will only contain information about the axes supported by the Text Layer's current font, and these will vary from font to font.
The object is keyed by axis name, and has values with the following structure:
| Properties | |
| --- | --- |
| idstring | The axis id |
| minnumber | The minimum value allowable on the axis |
| maxnumber | The maximum value allowable on the axis |
| valuenumber | The current axis value |
# Shared Style
```javascript
var SharedStyle = require('sketch/dom').SharedStyle
```
```javascript
document.sharedTextStyles.push({
name: 'Header 1',
style: text.style,
})
```
A shared style (either a layer style or a text style).
| Properties | |
| --- | --- |
| idstring | The unique ID of the Shared Style. |
| styleType[SharedStyle.StyleType](#sharedstylestyletype) | The type of the Shared Style. |
| namestring | The name of the Shared Style. |
| style[Style](#style) | The Style value that is shared. |
> Note that the `id` of a Shared Style coming from a Library might look like this: `FBFF821E-20F3-48C5-AEDC-89F97A8C2344[D1A683E0-5333-4EBE-977C-48F64F934E99]`.
>
> If you have a Symbol Instance which has a Layer using a Shared Style from a Library and a Layer in the Document using the same Shared Style from the Library, the style will be imported twice; once for use in the layer and once for use by the foreign Symbol. The reason for this is to do with syncing. If you change the Shared Style in the Library it will cause both the Symbol Instance and the Shared Style to be out-of-date in the document. This will be shown in the component sync sheet, but you can choose only to sync the Shared Style (or the Symbol). Using these “private” Shared Styles means that syncing just the shared style doesn’t implicitly also sync the symbol.
>
> The format of these Symbol private shared style IDs is `SYMBOLID[STYLEID]` Where: `STYLEID` is the id of the original Shared Style in the original Library. And `SYMBOLID` is the new symbolId of the foreign Symbol in the destination document.
>
> Where we have such as Symbol private style, the same ID will be used both as the local ID and as the remote ID.
## Create a new Shared Style from a Style
```javascript
const newSharedStyle = SharedStyle.fromStyle({
name: 'Header 1',
style: layer.style,
document: document,
})
// you can also push to the shared styles arrays directly
document.sharedTextStyles.push({
name: 'Header 1',
style: text.style,
})
```
Create a new Shared Style with a specific name in a specific Document.
> ⚠️You can only insert local shared styles (eg. not linked to a Library). `document.sharedLayerStyles` returns the foreign shared styles (eg. linked to a Library) concatenated with the local shared styles. So if you try to insert a new Shared Style at the beginning (using `unshift` for example), it will end up at the beginning of the local Shared Styles but that might not be the beginning of all the shared styles if there are some foreign.
## Get all the Instances
```javascript
var styles = sharedStyle.getAllInstances()
```
Returns an array of all instances of the Shared Style in the document, on all pages.
### Returns
A [Style](#style) array.
## Get all the Instances' Layers
```javascript
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](#layer) array.
## Get Library defining the style
```javascript
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](#library) the Shared Style was defined in, or `null` if it is a local shared style.
## Sync the local reference with the library version
```javascript
const success = sharedStyle.syncWithLibrary()
```
If a [Library](#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
```javascript
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`
```javascript
SharedStyle.StyleType.Text
```
Enumeration of the type of Shared Style. `Unknown` indicates the object is broken and Sketch can't determine the style type.
| Value |
| --------- |
| `Text` |
| `Layer` |
| `Unknown` |
# Symbol Override
```javascript
var overrides = symbolInstance.overrides
```
A [Symbol](https://sketch.com/docs/symbols/) override. This component is not exposed, it is only returned when accessing the `overrides` of a [Symbol Instance](#symbol-instance) or [Symbol Source](#symbol-source). The overrides are not available until after the instance is injected into the document.
| 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. See below for what properties are available. |
| idstring | The unique ID of the override (`${path}_${property}`). |
| symbolOverrideboolean | If the override is a nested Symbol override. |
| colorOverrideboolean | If the override is a color override. |
| valuestring / [ImageData](#imagedata) | The value of the override which can be changed. |
| isDefaultboolean | If the override hasn't been changed and is the default value. |
| defaultValuestring / [ImageData](#imagedata) | The default value for the override. |
| affectedLayer[Layer](#layer) / [Text](#text) / [Image](#image) / [Symbol Instance](#symbolinstance) | The layer the override applies to. It will be an immutable version of the layer. |
| editableboolean | If the value of the override can be changed. |
| selectedboolean / undefined | If the override is selected (or `undefined` if it's the override of a Symbol Source). |
## Text Overrides
```js
if (override.property === 'stringValue') {
override.value = 'an overridden text'
}
if (override.property === 'textStyle') {
override.value = someTextStyle.id
}
if (override.property === 'textSize') {
override.value = String(32)
}
if (override.property === 'textColor') {
override.value = '#FF00FF'
}
if (override.property === 'textDecoration') {
// 'none', 'underline', or 'strikethrough'
override.value = 'underline'
}
if (override.property === 'textHAlign') {
const { Text } = require('sketch/dom')
override.value = Text.Alignment.right
}
```
| `Override.property` | `Override.value` |
| --- | --- |
| `stringValue` | Text contents string |
| `textStyle` | Text style identifier string |
| `textSize` | Font size string |
| `textColor` | Text color string |
| `textDecoration` | Text decoration string |
| `textHAlign` | Text horizontal alignment string / number |
## Symbol Overrides
```js
if (override.symbolOverride) { ... }
if (override.property === 'symbolID') {
override.value = someOtherSymbol.id
}
```
| `Override.property` | `Override.value` |
| --- | --- |
| `symbolID` | A symbol identifier for a nested instance string |
## Image Overrides
```js
if (override.property === 'image') {
// Value could be one of:
// - an `ImageData`
// - a `Buffer`
// - a native `NSImage`
// - a native `NSURL`
// - a native `MSImageData`
// - a string: path to an image file
// - an object with a `path` property: path to an image file
// - an object with a `base64` string: a base64 encoded image
override.value = ImageData.from(...)
override.value = {
base64: "..."
}
// etc
}
if (override.property === 'imageResizeBehavior') {
const ResizeBehavior = Object.freeze({
Stretch: 0,
Original: 1,
Fit: 2,
Fill: 3
})
const currentValue = Object.keys(ResizeBehavior).find((k) => {
return String(ResizeBehavior[k]) === override.value
})
if (currentValue === 'Original') {
override.value = ResizeBehavior.Stretch
}
}
```
| `Override.property` | `Override.value` |
| --- | --- |
| `image` | A nested image [ImageData](#imagedata) |
| `imageResizeBehavior` | A nested image sizing string / number |
## Color Overrides
```js
if (override.colorOverride) { ... }
if (override.property === 'color:fill-0') {
override.value = '#aa7080'
console.log(
`First fill color for "${override.affectedLayer.name}": ${override.value}`,
)
// 👉 First fill color for "Rectangle": #aa7080
}
```
| `Override.property` | `Override.value` |
| --- | --- |
| `textColor` | Text color string |
| `fillColor` | Group tint color string |
| `color:fill-N` | N-th fill color string |
| `color:border-N` | N-th border color string |
| `color:shadow-N` | N-th shadow color string |
| `color:innershadow-N` | N-th inner shadow color string |
| `swatchValue` | Color Variable value [Swatch](#swatch) / undefined |
| `defaultSwatchValue` | A default Color Variable value [Swatch](#swatch) / undefined |
| `blendMode:fill-N` | The blend mode for the N-th fill color |
| `opacity:fill-N` | The opacity value for the N-th fill color |
## Layer Overrides
```js
if (override.property === 'layerStyle') {
override.value = someLayerStyle.id
}
if (override.property === 'flowDestination') {
override.value = someHotspotLayer.id
}
if (override.property === 'isVisible') {
override.value = false
}
if (override.property === 'horizontalSizing') {
const { FlexSizing } = require('sketch/dom')
const currentValue = Object.keys(FlexSizing).find((k) => {
return String(FlexSizing[k]) === override.value
})
if (currentValue === 'Fixed') {
override.value = FlexSizing.Fill
}
}
```
| `Override.property` | `Override.value` |
| --- | --- |
| `layerStyle` | A shared layer style identifier string |
| `flowDestination` | A hotspot target identifier string |
| `isVisible` | A layer visibility flag boolean |
| `horizontalSizing` | Layer sizing options [FlexSizing](#flexsizing) |
| `verticalSizing` | Layer sizing options [FlexSizing](#flexsizing) |
## Get the frame of an Override
```javascript
var frame = override.getFrame()
```
The frame of an override can be different than the frame of its affected Layer in case where the Symbol Instance has been scaled for example.
### Returns
A [Rectangle](#rectangle) describing the frame of the affected layer in the Symbol Instance's coordinates.
# Flow
```javascript
var Flow = require('sketch/dom').Flow
```
The prototyping action associated with a layer.
| Properties | |
| --- | --- |
| target[Artboard](#artboard) / [Flow.BackTarget](#flowbacktarget) | The target artboard of the action or `Flow.BackTarget` if the action is a back action |
| targetIdstring / [Flow.BackTarget](#flowbacktarget) | The ID of target artboard of the action or `Flow.BackTarget` if the action is a back action |
| animationType[AnimationType](#flowanimationtype) | The type of the animation. |
## Create a new prototyping action
```javascript
layer.flow = {
target: artboard,
}
```
You can create an action without specifying an animation type, it will use the default one.
```javascript
layer.flow = {
targetId: artboard.id,
}
```
You can create an action by using the ID of an Artboard instead of the artboard.
```javascript
layer.flow = {
target: artboard,
animationType: Flow.AnimationType.slideFromLeft,
}
```
You can also specify the [animation type](#flowanimationtype).
```javascript
layer.flow = {
target: Flow.BackTarget,
}
```
You can also create a back action.
## Check if the action is a Back action
```javascript
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
```javascript
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`
```javascript
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`
```javascript
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 |
# Export Format
An export format associated with a layer.
| Properties | |
| --- | --- |
| fileFormatstring | The file format of the export. |
| prefixstring / `undefined` | The prefix added to the file name. |
| suffixstring / `undefined` | The suffix added to the file name. |
| sizestring | The size of the export. Valid values include `2x`, `100w`, `100width`, `100px`, `300h`, `300height`. |
## Valid export file formats
- `jpg`
- `png`
- `tiff`
- `eps`
- `pdf`
- `webp`
- `svg`
# Selection
```javascript
var selection = document.selectedLayers
```
A utility class to represent the layers selection. Contains some methods to make interacting with a selection easier.
| Properties | |
| --- | --- |
| layers[Layer](#layer)[] | The Layers in the selection. Setting this property will change the selection. |
| lengthnumber - read-only | The number of Layers in the selection. |
| isEmptyboolean - read-only | Does the selection contain any layers? |
## `map`, `forEach`, and `reduce`
```javascript
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 to its layers. Those are just convenience methods to avoid getting the layers every time.
## Clear the Selection
```javascript
selection.clear()
```
Clears the selection.
### Returns
Return the selection (useful if you want to chain the calls).
# FlexSizing
Represents sizing options available to layers within Frames. See [Layer Sizing](#layer-sizing).
```js
const { FlexSizing } = require('sketch/dom')
layer.verticalSizing = FlexSizing.Relative
```
| Value | |
| --- | --- |
| `Fixed` | The layer determines its own size along the horizontal axis (some other properties may still override it). |
| `Fit` | The layer hugs its children or contents along the horizontal axis (only available for [Stacks](#stacklayout) and [Texts](#text)). |
| `Fill` | The layer fills the available horizontal space in the parent container (only available to layers inside [Stacks](#stacklayout)). |
| `Relative` | The layer is sized proportionally relative to its parent along the horizontal axis. When its parent resizes, it does too. |
> Not all FlexSizing options are applicable for all layers at all times — see ["Sizing options for frame contents"](https://www.sketch.com/blog/frames/#working-within-frames) for details.
# Pin
Represents edge pinning options available to layers within Frames. See [Layer Pinning](#layer-pinning).
```js
const { Pin } = require('sketch/dom')
if (layer.verticalPins == Pin.Min) {
console.log('The top edge is pinned, the bottom edge is not.')
}
```
| Value | |
| --- | --- |
| `None` | Neither edge is pinned. |
| `Min` | Only the _top_ or the _left_ edge (for the vertical and horizontal axis respectively) is pinned. |
| `Max` | Only the _bottom_ or the _right_ edge (for the vertical and horizontal axis respectively) is pinned. |
| `Both` | Both edges are pinned: _top_ and _bottom_ for the vertical axis, _left_ and _right_ for the horizontal axis. |
# Point
A utility class to represent a point.
| Properties | |
| --- | --- |
| xnumber / Point | The x coordinate of the point. |
| ynumber | The y coordinate of the point. |
## Get a `CGPoint`
```javascript
var cgPoint = point.asCGPoint()
```
Return the Point as a [`CGPoint`](https://developer.apple.com/documentation/coregraphics/cgpoint?language=objc).
## Get an `NSPoint`
```javascript
var nsPoint = rect.asNSPoint()
```
Return the Point as a [`NSPoint`](https://developer.apple.com/documentation/foundation/nspoint?language=objc).
# CurvePoint
A utility class to represent a curve point (with handles to control the curve in a path).
| Properties | |
| --- | --- |
| point[Point](#point) | The position of the point. |
| curveFrom[Point](#point) | The position of the handle control point for the incoming path. |
| curveTo[Point](#point) | The position of the handle control point for the outgoing path. |
| cornerRadiusnumber | The corder radius of the point. |
| pointType[PointType](#curvepointpointtype) | The type of the point. |
## Check if the point is selected
```javascript
shape.points[0].isSelected()
```
In case the user is currently editing a path, you can check if a curve point is selected using the `curvePoint.isSelected()` method.
## `CurvePoint.PointType`
Enumeration of the animation types.
| Value |
| -------------- |
| `Undefined` |
| `Straight` |
| `Mirrored` |
| `Asymmetric` |
| `Disconnected` |
# Rectangle
```javascript
var Rectangle = require('sketch/dom').Rectangle
```
```javascript
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
```javascript
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
```javascript
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
```javascript
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.from[Layer](#layer) | The layer in which the rectangle's coordinates are expressed. |
| change.to[Layer](#layer) | 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`
```javascript
var cgRect = rect.asCGRect()
```
Return the Rectangle as a [`CGRect`](https://developer.apple.com/documentation/coregraphics/cgrect?language=objc).
## Get an `NSRect`
```javascript
var nsRect = rect.asNSRect()
```
Return the Rectangle as a [`NSRect`](https://developer.apple.com/documentation/foundation/nsrect?language=objc).
# fromNative
```javascript
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](#document) while a native text layer will be wrapped as a [Text](#text).
# Assets
Wrapper classes that are used to represent reusable assets retrieved from a document or globally.
## Color Asset
| Properties | |
| ----------------------------------------- | ------------------------------- |
| namestring | The name of the asset, or null. |
| colorstring | The hex string for the color. |
### Get the Global Colors
```javascript
const sketch = require('sketch/dom')
const colors = sketch.globalAssets.colors
```
#### Returns
An array of [ColorAsset](#color-asset) objects.
## Gradient Asset
| Properties | |
| --- | --- |
| namestring | The name of the asset, or null. |
| gradient[Gradient](#gradient) | The gradient object. |
### Get the Global Gradients
```javascript
const sketch = require('sketch/dom')
const gradients = sketch.globalAssets.gradients
```
#### Returns
An array of [GradientAsset](#gradient-asset) objects.
## Swatch
> A swatch is an API term for a Color Variable in Sketch.
| Properties | |
| --- | --- |
| namestring | The name of the swatch, or null. |
| colorstring | The hex string for the color. |
| referencingColor object | A special color object that's bound to the swatch. This color will automatically update itself when the swatch changes. |
```js
const sketch = require('sketch')
const document = sketch.getSelectedDocument()
document.swatches.append({
name: 'Safety Orange',
color: '#ff6600ff',
})
const swatch = document.swatches[0]
```
A Swatch must be added to a document before its first use:
```js
layer.style.fills = [
{
fillType: 'Color',
color: swatch.referencingColor,
},
]
```
Wherever you'd normally specify a plain color string, you may pass the `referencingColor` of a Swatch:
```js
layer.style.fills = [
{
fillType: 'Color',
swatch: swatch,
},
]
```
Or pass the swatch object directly where applicable:
```js
swatch.name = 'Something else'
swatch.color = '#ffffffff'
assert(layer.style.fills[0].color === '#ffffffff') // ✅
```
Swatches are mutable, you can update their name and color value. Once you update a swatch color, it will automatically propagate to all instances of this swatch throughout the document:
### Library Swatches
```js
if (mySwatch.getLibrary()) {
const libraryName = mySwatch.getLibrary()?.name
// ...
mySwatch.syncWithLibrary()
}
```
# StackLayout
```js
const { StackLayout } = require('sketch/dom')
```
Describes a particular [Stack Layout](https://www.sketch.com/docs/designing/stack-layout/).
| Properties | |
| --- | --- |
| direction[StackLayout.Direction](#stacklayoutdirection) | Defines how the stack is laid out |
| justifyContent[StackLayout.JustifyContent](#stacklayoutjustifycontent) | Defines the alignment of content along the main axis of a stack. `justify-content` in CSS |
| alignItems[StackLayout.AlignItems](#stacklayoutalignitems) | Defines the alignment of content on the stack's cross-axis. `align-items` in CSS |
| gapnumber | A gap between individual stack items |
| paddingobject / number | The stack's padding around its content. When set to a number, denotes uniform padding for all edges |
| padding.vertical, padding.horizontal | Sets padding per axis: `vertical` for top and bottom, `horizontal` for left and right |
| padding.top, padding.left, padding.bottom, padding.right | Sets padding per individual edge |
| Wrapping Properties | |
| --- | --- |
| wrapsboolean | Whether the contents of the stack should wrap when their combined _height_ (for vertical stacks) or _width_ (for horizontal stacks) exceeds the stack's fixed dimensions |
| alignContent[StackLayout.JustifyContent](#stacklayoutjustifycontent) | Defines how the wrapped content should be aligned on the cross axis of the stack |
| crossAxisGapnumber | A gap between wrapped lines of the stack |
## Inspecting Stacks
```js
if (group.stackLayout) {
// This is a Stack
}
```
Use the `stackLayout` property of a [`Group`](#Group) to find out whether a given container is a stack.
```js
const { direction, alignItems, ...other } = group.stackLayout
if (group.stackLayout.justifyContent === StackLayout.JustifyContent.End) {
// ...
}
```
Inspect this property further to learn more about that particular stack:
## Creating Stacks
```js
const stack = new Group({
stackLayout: {
direction: StackLayout.Direction.Column,
alignItems: StackLayout.AlignItems.Center,
gap: 120,
},
layers: [
/* ... */
],
})
```
To create a brand new container with a Stack Layout, pass a `stackLayout` object to a `Group` constructor:
## Converting containers to Stacks
```js
const group = new Group.Frame(/* ... */)
group.stackLayout = {
padding: { top: 50, bottom: 30 },
}
```
In order to turn an existing layer group to a stack, assign a layout object to its `stackLayout` property:
## Updating Stacks
```js
const stack = new Group({
stackLayout: { padding: 10 },
layers: [
/* ... */
],
})
stack.layers.push(new Text(/* ... */))
stack.stackLayout.apply()
```
After adding or removing layers from a stack, call `StackLayout.apply()` to update the layout:
```js
stack.layers[0].ignoresStackLayout = true
const stack = new Group({
stackLayout: { padding: 10 },
layers: [
new Text({
preservesSpaceInStackLayoutWhenHidden: true,
}),
],
})
```
Once added to a stack, layers gain additional layout properties:
| Property | Description |
| --- | --- |
| `ignoresStackLayout`boolean | Controls whether this layer ignores the enclosing Stack Layout properties when positioning itself |
| `preservesSpaceInStackLayoutWhenHidden`boolean | Controls whether a Stack should keep a layer's space even when it's hidden |
## Wrapping Stacks
```js
const { Group, StackLayout, FlexSizing } = require('sketch')
// for new Stacks
const stack = new Group.Frame({
stackLayout: {
direction: StackLayout.Direction.Row,
wraps: true,
},
horizontalSizing: FlexSizing.Fixed,
})
// or, for existing Stacks
container.stackLayout.wraps = true
```
Use `StackLayout.wrap` property to control whether the contents of a particular Stack Layout should wrap when their combined _height_ (for vertical stacks) or _width_ (for horizontal stacks) exceeds the Stack's fixed dimensions:
```js
container.stackLayout.alignContent = StackLayout.AlignContent.End
```
You can also choose how the wrapped content should be aligned on the cross axis:
```js
container.stackLayout.crossAxisGap = 30
```
And specify an optional gap between wrapped lines:
## Removing Stack Layout from containers
```js
container.stackLayout = null
```
Set the `stackLayout` value to `null` to remove the Stack Layout from the given stack and effectively convert it to a regular layer container.
## `StackLayout.Direction`
| Value | Description |
| -------- | ------------------------------ |
| `Row` | Lay out the stack horizontally |
| `Column` | Lay out the stack vertically |
## `StackLayout.JustifyContent`
| Value | Description |
| --- | --- |
| `Start` | Lay out from the start of the stack (e.g. left or top) |
| `Center` | Center items within the stack |
| `End` | Lay out from the end of the stack (e.g. right or bottom) |
| `Between` | Add spacing _between_ the items so the stack is filled. `space-between` in CSS. |
| `Around` | Add spacing either side of every item so the stack is filled. Visually the spacing at start and end of the stack is half of the other spaces, because there's only a single item to add spacing to `space-around` in CSS. |
| `Evenly` | Add spacing between every item _and_ at the start and end of the stack. `space-evenly` in CSS. |
## `StackLayout.AlignItems`
| Value | Description |
| --- | --- |
| `Start` | Align to the start of the cross-axis (e.g. left or top) |
| `Center` | Align to the center of the cross-axis |
| `End` | Align to the end of the cross-axis (e.g. right or bottom). |
| `Stretch` | Align items by stretching. |
| `None` | For an individual stack item, use the default alignment inherited from the stack |
# SmartLayout (Legacy)
> Since the launch of Sketch 2025.1 Athens, we’ve introduced a more flexible feature called [Stacks](https://www.sketch.com/docs/designing/stack-layout/). While Smart Layout remains available as a legacy feature, we encourage you to explore Stacks to take full advantage of the latest layout capabilities.
The [SmartLayout](#smartlayout-legacy) object contains the set of possible Smart Layouts that can be applied to [SymbolMaster](#symbol-source) and [Group](#group) layers.
| Properties | |
| ------------------ | --------------------------------------------------- |
| LeftToRight | Smart Layout flowing left to right |
| HorizontallyCenter | Smart Layout expanding horizontally from the center |
| RightToLeft | Smart Layout flowing right to left |
| TopToBottom | Smart Layout flowing from top to bottom |
| VerticallyCenter | Smart Layout expanding vertically from the center |
| BottomToTop | Smart Layout flowing from bottom to top |
## Set a Smart Layout
```javascript
const SmartLayout = require('sketch').SmartLayout
layer.smartLayout = SmartLayout.TopToBottom
```
Given a reference to a [SymbolMaster](#symbol-source) or [Group](#group) layer use the `smartLayout` setter to apply one of the Smart Layout values.
## Clear a Smart Layout
Set the `smartLayout` value to `null` to remove the Smart Layout. This is the equivalent of selecting "None" in the Sketch Inspector.
```javascript
symbol.smartLayout = null
```
## Trigger a smart layout
```javascript
const SmartLayout = require('sketch').SmartLayout
symbol.smartLayout = SmartLayout.TopToBottom
symbolInstance.resizeWithSmartLayout()
```
In order to trigger a Smart Layout resize in an instance, for example after changing an override value, call the `resizeWithSmartLayout()` method on the [SymbolInstance](#symbol-instance) layer.
# 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. |
| nameIsFixedboolean | Whether the Layer prevents implicit modifications of its name. |
| parent[Group](#group) | The group the layer is in. |
| lockedboolean | If the layer is locked. |
| hiddenboolean | If the layer is hidden. |
| frame[Rectangle](#rectangle) | The frame of the Layer. This is given in coordinates that are local to the parent of the layer. |
| horizontalSizing[FlexSizing](#flexsizing) | The horizontal axis sizing option of the layer. |
| verticalSizing[FlexSizing](#flexsizing) | The vertical axis sizing option of the layer. |
| horizontalPins[Pin](#pin) | The pinning options along the horizontal axis of the layer. |
| verticalPins[Pin](#pin) | The pinning options along the vertical axis of the layer. |
| selectedboolean | If the layer is selected. |
| flow[Flow](#flow) | The prototyping action associated with the layer. |
| exportFormats[ExportFormat](#export-format)[] | The export formats of the Layer. |
| transformobject | The transformation applied to the Layer. |
| transform.rotationnumber | The rotation of the Layer in degrees, clock-wise. |
| transform.flippedHorizontallyboolean | If the layer is horizontally flipped. |
| transform.flippedVerticallyboolean | If the layer is vertically flipped. |
| Stack Properties | |
| --- | --- |
| `ignoresStackLayout`boolean | If the layer ignores the parent [Stack Layout](#stacklayout) when positioning itself. |
| `preservesSpaceInStackLayoutWhenHidden`boolean | If the enclosing [Stack Layout](#stacklayout) should keep the layer's space even when it's hidden. |
| Masking Properties | |
| --- | --- |
| `closestMaskingLayer`[Layer](#layer) / null | The closest layer that is masking this layer, if any. |
| `breaksMaskChain`boolean | Opts the layer (and any following siblings) out of masking. |
## Layer Sizing
```js
const { FlexSizing } = require('sketch/dom')
layer.verticalSizing = FlexSizing.Relative
layer.horizontalSizing = FlexSizing.Fixed
```
`verticalSizing` and `horizontalSizing` properties [describe](#flexsizing) how a layer is laid out within its containing Frame along the respective axis.
## Layer Pinning
```js
const { Pin } = require('sketch/dom')
if (layer.verticalPins & Pin.Min) {
// The top edge is pinned
// (the bottom edge might be pinned too, but we don't care)
}
```
`horizontalPins` and `verticalPins` properties [describe](#pin) how a layer is positioned within its containing Frame along the respective axis.
These properties are [_bitmasks_](), which means that in order to query whether a _specific_ edge is pinned, you need to use the _bitwise_ AND operator — defined as **single** `&` in JavaScript (not to be confused with a **double** `&&` for the _logical_ AND).
```js
// Leave only the right edge pinned
// (this will pin the right edge *and* unpin the left one if pinned)
layer.horizontalPins = Pin.Max
```
In order to pin edges of a layer, you may either assign an entire new value for the desired axis...
```js
// Pin the left edge. Other already pinned edges remain intact:
layer.horizontalPins |= Pin.Min
// Unpin the left edge. Other pinned edges remain intact:
layer.horizontalPins &= ~Pin.Min
```
...or you may toggle individual edges via the bitwise OR and AND operators – to add or remove certain pins respectively.
## Masking
Masks are [Shapes](#shape) and [ShapePaths](#shapepath) that you can use to hide or show parts of other Layers.
### Inspecting masks
```js
const maskShape = layer.closestMaskingLayer
if (maskShape) {
// the layer is masked by `maskShape`
}
```
To check if a certain layer is masked, inspect its `closestMaskingLayer` property:
```js
layer.closestMaskingLayer?.closestMaskingLayer?.closestMaskingLayer // etc
```
In case of multiple masks, keep calling `closestMaskingLayer` on the returned value until there's a next mask available:
```js
if (layer.breaksMaskChain) {
// ...
}
```
To check whether a layer has the _"Ignores Underlying Mask"_ flag enabled, effectively breaking a mask chain, refer to the `Layer.breaksMaskChain` property. A layer with the `breaksMaskChain` flag set will automatically opt all layers _above it_ out of masking as well.
### Applying masks
```js
shape.masksSiblings = true
shape.maskMode = Layer.MaskMode.Outline
```
To use a certain Shape as a Mask on its siblings:
### `Layer.MaskMode`
```js
shape.maskMode = Layer.MaskMode.Outline
```
| Value |
| --------- |
| `Outline` |
| `Alpha` |
## Duplicate the Layer
```javascript
var duplicatedLayer = layer.duplicate()
```
A new identical layer will be inserted into the parent of this layer.
### Returns
A new [Layer](#layer).
## Remove the Layer
```javascript
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
```javascript
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
### Using the index
```javascript
layer.index = 2
```
You can set the index of the layer to move it in the hierarchy.
### Move to the front
```javascript
layer.moveToFront()
// which is the same as
layer.index = layer.parent.layers.length - 1
```
Move this layer to the front of its parent.
#### Returns
The current layer (useful if you want to chain the calls).
### Move forward
```javascript
layer.moveForward()
// which is the same as
layer.index = layer.index + 1
```
Move this layer forward in its parent.
#### Returns
The current layer (useful if you want to chain the calls).
### Move to the back
```javascript
layer.moveToBack()
// which is the same as
layer.index = 0
```
Move this layer to the back of its parent.
#### Returns
The current layer (useful if you want to chain the calls).
### Move backward
```javascript
layer.moveBackward()
// which is the same as
layer.index = layer.index - 1
```
Move this layer backward in its parent.
#### Returns
The current layer (useful if you want to chain the calls).
## Accessing the layer's hierarchy
```javascript
// access the page the layer is in
layer.getParentPage()
page.getParentPage() === undefined
// access the artboard the layer is in (if any)
layer.getParentArtboard()
artboard.getParentArtboard() === undefined
// access the Symbol Source the layer is in (if any)
layer.getParentSymbolMaster()
symbolMaster.getParentSymbolMaster() === undefined
// access the shape the layer is in (if any)
layer.getParentShape()
```
In addition to the direct `parent`, you can access a few other entities in the hierarchy of the layer.
# Group
```javascript
const { Group } = require('sketch/dom')
```
A group of layers. It is also an instance of [Layer](#layer) so all the methods defined there are available.
Different group types are sized differently:
1. A regular layer group fits around its children.
2. A Frame group has fixed size; its children can use different constraints to influence how they adjust when the Frame is resized.
3. A Graphic group is a specialized kind of Frame: its children don't support constraints, and they resize proportionally instead.
| Base Properties | |
| --- | --- |
| idstring | The unique ID of the Group. |
| namestring | The name of the Group |
| parent[Group](#group) | The group the Group is in. |
| lockedboolean | If the Group is locked. |
| hiddenboolean | If the Group is hidden. |
| frame[Rectangle](#rectangle) | The frame of the Group. This is given in coordinates that are local to the parent of the Layer. |
| selectedboolean | If the Group is selected. |
| flow[Flow](#flow) | The prototyping action associated with the Group. |
| flowStartPointboolean | A Start Point allows you to choose where to start your prototype from. |
| exportFormats[ExportFormat](#export-format)[] | The export formats of the Group. |
| transformobject | The transformation applied to the Group. |
| transform.rotationnumber | The rotation of the Group in degrees, clock-wise. |
| transform.flippedHorizontallyboolean | If the Group is horizontally flipped. |
| transform.flippedVerticallyboolean | If the Group is vertically flipped. |
| style[Style](#style) | The style of the Group. |
| sharedStyle[SharedStyle](#shared-style) / `null` | The associated shared style or `null`. |
| sharedStyleIdstring / `null` | The ID of the [SharedStyle](#shared-style) or `null`, identical to `sharedStyle.id`. |
| layers[Layer](#layer)[] | The Layers that this component groups together. |
| smartLayout[SmartLayout](#smartlayout-legacy) | The Group's Smart Layout. (Legacy) |
| stackLayout[StackLayout](#stacklayout) | The Group's Stack Layout. |
| Frame-specific Properties | |
| --- | --- |
| isFrameboolean | If the Group has Frame behavior. |
| isGraphicFrameboolean | If the Group has Graphic behavior. |
| clipsContentsboolean | Whether any child layers are clipped by this Frame, Graphic, or Symbol Master. |
| Frame[class](#working-with-frames-and-graphics) | A convenience constructor for a Frame group. |
| Graphic[class](#working-with-frames-and-graphics) | A convenience constructor for a Graphic group. |
| groupBehavior[GroupBehavior](#groupbehavior) | Defines how a Group should behave. Prefer `isFrame` and `isGraphicFrame` over reading this property directly. |
## Create a new Group
```javascript
new Group()
```
```javascript
var group = new Group({
name: 'my name',
layers: [
{
type: sketch.Types.Text,
text: 'Hello world',
},
],
})
```
## Working with Frames and Graphics
```js
const { Group } = require('sketch/dom')
let frame = new Group.Frame({ name: 'My Frame' })
let graphic = new Group.Graphic({
layers: [{ type: 'Text', text: 'Hello there' }],
})
```
To create a Frame or a Graphic container, use one of the `Group` convenience constructors: `Group.Frame()` and `Group.Graphic()`.
```js
if (group.isFrame) {
// ✅ This is a Frame OR a Graphic
}
if (group.isGraphicFrame) {
// ✅ This is a Graphic
}
```
To differentiate between regular layer groups, frames and graphic containers, use [`Group.isFrame`](#group) and [`Group.isGraphicFrame`](#group) properties.
> Note that since Graphics are a special kind of Frames, [`Group.isFrame`](#group) will report `true` for both of them.
### Styling Frames and Graphics
```js
const { Style } = require('sketch/dom')
graphic.style.fills = [
{
color: '#c0ffee',
fillType: Style.FillType.Color,
thickness: 5,
},
]
graphic.style.borderOptions = {
dashPattern: [20, 5, 20, 5],
}
```
Frames and Graphics support the full range of styling options available to most Sketch layers: borders, fills, shadows, and even blur. Styling these new containers is no different than styling any other [`StyledLayer`](#style).
> The legacy [`Group.background`](#group) property now acts as a mere proxy for the `style.fills` array: by adding or removing fills from the receiver container as necessary.
## Adjust to fit its children
```javascript
group.adjustToFit()
```
Adjust the group to fit its children.
### Returns
The current group (useful if you want to chain the calls).
## `GroupBehavior`
| Value | Description |
| --- | --- |
| `Default` | Normally, if no other properties influence the behavior, it will behave like a plain group that fits around its children. |
| `Frame` | Frames have fixed size, and their children can use different constraints to influence how they adjust when the Frame is resized. |
| `Graphic` | A Graphic is a specialized kind of Frame: their contents don't support constraints, and they resize proportionally instead. |
> The `Group.groupBehavior` isn't always a reliable indicator of whether the given Group acts as a Frame or Graphic. Use `Group.isFrame` or `Group.isGraphicFrame` to access this information instead.
# Page
```javascript
var Page = require('sketch/dom').Page
```
A Sketch page. It is an instance of both [Layer](#layer) and [Group](#group) so all the methods defined there are available.
| Properties | |
| --- | --- |
| idstring | The unique ID of the Page. |
| namestring | The name of the Page |
| parent[Document](#document) | The document the page is in. |
| layers[Layer](#layer)[] | An array of the layers and Artboards that this page has. It contains the first level children of the Page. If you need to access all layers and sublayers in the Page, use [`find`](#find). |
| frame[Rectangle](#rectangle) | The frame of the page. |
| selectedboolean | If the Page is selected. |
| canvasLevelFrames[Group](#group)[] | An array of top-level containers (Frames and Graphics) that this page has. |
## Create a new Page
```javascript
new Page()
```
```javascript
new Page({
name: 'my page',
})
```
## Get the selected Layers of the Page
```javascript
var selection = document.selectedLayers
```
A read-only property to get the layers that the user has selected in the page.
### Returns
Return a [Selection](#selection) object.
## Get the top-level Frames and Graphics (Artboards)
```js
page.canvasLevelFrames.forEach((container) => {
// ✅ Treat this layer container as an Artboard
})
```
## Symbols Page
The "Symbols" page is similar to other pages. The only way it is specific is when creating a Symbol, Sketch will ask the user if they want to move it to that page.
You can put Symbols in any page but if you want to respect the convention Sketch put in place, here are a few methods to help you do so.
### Get the Symbols Page
```javascript
var symbolsPage = Page.getSymbolsPage(document)
```
A method to get the Symbols Page of a Document.
| Parameters | |
| --- | --- |
| document[Document](#document) - required | The document from which you want the Symbols Page. |
#### Returns
Return a [Page](#page) or `undefined` if there is no Symbols Page yet.
### Create the Symbols Page
```javascript
var symbolsPage = Page.createSymbolsPage()
symbolsPage.parent = document
```
A method to create the Page with the name that Sketch will recognize as the Symbols Page.
#### Returns
Return a [Page](#page).
### Knows if a Page is the Symbols Page
```javascript
var isSymbolsPage = page.isSymbolsPage()
```
A method to tell if the page is the Symbols Page.
#### Returns
Return a `boolean`.
# Artboard (Legacy)
Starting with Sketch 2025.1 Artboards have been replaced by more powerful layer containers: [Frames and Graphics](#working-with-frames-and-graphics).
```js
const sketch = require('sketch/dom')
page.selectedLayers.forEach((layer) => {
if (layer.type == sketch.Types.Artboard) {
// ✅ this is a top-level Frame or Graphic
}
})
```
The `Artboard` class will remain in the API, but it will only be used as a mere marker for _top-level Frames_ returned from [`Document.selectedLayers`](#document), [`Page.selectedLayers`](#page), [`Group.layers`](#group), and [`find('Artboard')`](#find) calls.
```js
page.canvasLevelFrames.forEach((frame) => {
// ✅ Treat this `frame` as an Artboard
})
```
There's also [`Page.canvasLevelFrames`](#page) available if you need to iterate all top-level Frames (that would be considered Artboards in older versions of Sketch) on a given page.
```js
const { find } = require('sketch')
find('Artboard').forEach((frame) => {
// ✅ Treat this `frame` as an Artboard
})
find('Artboard', currentPage).forEach((frame) => {
// ✅ Treat this `frame` as an Artboard
})
```
You may also use the [`find('Artboard')`](#find) API to find top-level Frames within the whole document or a given page.
# Shape
```javascript
var Shape = require('sketch/dom').Shape
```
A shape layer. It is an instance of [Layer](#layer) so all the methods defined there are available. It is shaped by its layers which have boolean operations between them.
| Properties | |
| --- | --- |
| idstring | The unique ID of the Shape. |
| namestring | The name of the Shape |
| parent[Group](#group) | The group the shape is in. |
| lockedboolean | If the Shape is locked. |
| hiddenboolean | If the shape is hidden. |
| frame[Rectangle](#rectangle) | The frame of the Shape. This is given in coordinates that are local to the parent of the layer. |
| selectedboolean | If the Shape is selected. |
| flow[Flow](#flow) | The prototyping action associated with the Shape. |
| exportFormats[ExportFormat](#export-format)[] | The export formats of the Shape. |
| transformobject | The transformation applied to the Layer. |
| transform.rotationnumber | The rotation of the Layer in degrees, clock-wise. |
| transform.flippedHorizontallyboolean | If the layer is horizontally flipped. |
| transform.flippedVerticallyboolean | If the layer is vertically flipped. |
| style[Style](#style) | The style of the Shape. |
| sharedStyle[SharedStyle](#shared-style) / `null` | The associated shared style or `null`. |
| sharedStyleIdstring / `null` | The ID of the [SharedStyle](#shared-style) or `null`, identical to `sharedStyle.id`. |
| Masking Properties | |
| --- | --- |
| masksSiblingsboolean | If the layer acts like a mask for its siblings. |
| maskMode[MaskMode](#layermaskmode) | A mask mode for a [Shape](#shape) or [ShapePath](#shapepath) masking other layers. |
## Create a new Shape
```javascript
new Shape({
name: 'my shape',
})
```
# Image
```javascript
var Image = require('sketch/dom').Image
```
An image layer. It is an instance of [Layer](#layer) so all the methods defined there are available.
| Properties | |
| --- | --- |
| idstring | The unique ID of the Image. |
| namestring | The name of the Image |
| parent[Group](#group) | The group the Image is in. |
| lockedboolean | If the Image is locked. |
| hiddenboolean | If the Image is hidden. |
| frame[Rectangle](#rectangle) | The frame of the Image. This is given in coordinates that are local to the parent of the layer. |
| selectedboolean | If the Image is selected. |
| flow[Flow](#flow) | The prototyping action associated with the Image. |
| exportFormats[ExportFormat](#export-format)[] | The export formats of the Image. |
| transformobject | The transformation applied to the Image. |
| transform.rotationnumber | The rotation of the Image in degrees, clock-wise. |
| transform.flippedHorizontallyboolean | If the Image is horizontally flipped. |
| transform.flippedVerticallyboolean | If the Image is vertically flipped. |
| style[Style](#style) | The style of the Image. |
| sharedStyle[SharedStyle](#shared-style) / `null` | The associated shared style or `null`. |
| sharedStyleIdstring / `null` | The ID of the [SharedStyle](#shared-style) or `null`, identical to `sharedStyle.id`. |
| image[ImageData](#imagedata) | The actual image of the layer. |
## Create a new Image
```javascript
var imageLayer = new Image({
image: 'path/to/image.png',
})
```
The image property accepts a wide range of input:
- an [`ImageData`](#imagedata)
- a `Buffer`
- 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
```javascript
var imageLayer = new Image({
image: 'path/to/image.png',
frame: new Rectangle(0, 0, 300, 200),
})
```
By default, an `Image` layer will be created with a size of 100 × 100 pixels, unless you provide a `frame` property on its constructor.
## Original Size
```js
imageLayer.resizeToOriginalSize()
```
Adjust the Image to its original size. This is equivalent to pressing the 'Original Size' button in Sketch's Inspector.
### Returns
The current Image (useful if you want to chain the calls).
For performance reasons, Sketch initializes the `Image` object lazily. So if you want to set the dimensions of your Image layer to those of the original file, you'll first need to create the object, and then call the `resizeToOriginalSize` method.
## Remove Background
Remove backgrounds from the given image layers using Apple's on-device machine-learning frameworks and models.
The process is asynchronous: the given layer's image will be automatically updated upon completion, and your callback will be invoked.
```js
anImageLayer.removeBackground((error) => {
if (error) {
console.error(`Background removal failed: ${error}`)
}
})
anImageLayer.removeBackground({ people: true }, (error) => {
// ...
})
```
`removeBackground([options], callback)`
| Parameter | Description |
| --- | --- |
| `options.people`boolean | Whether Sketch should use an ML model optimized for images with people (defaults to `false`). |
| `callback`function(Error?) | The callback function that takes one argument: an optional `Error` object. |
```js
const { Image } = require('sketch')
Image.removeBackgroundFromLayers(imageLayers, (error) => {
if (error) {
console.error(
`Background removal failed for ${imageLayers.length} images: ${error}`,
)
}
})
Image.removeBackgroundFromLayers(imageLayers, { people: true }, (error) => {
// ...
})
```
`Image.removeBackgroundFromLayers(layers, [options], callback)`
| Parameter | Description |
| --- | --- |
| `layers`Layer[] | A list of image layers to remove a background from. |
| `options.people`boolean | Whether Sketch should use an ML model optimized for images with people (defaults to `false`). |
| `callback`function(Error?) | The callback function that takes one argument: an optional `Error` object. |
## `ImageData`
```javascript
var imageData = imageLayer.image
```
An `ImageData` is a wrapper around a native `NSImage`.
| Properties | |
| --- | --- |
| `size` | The dimensions of the image `{ width: number, height: number }` |
| `base64` | A base64-encoded representation of the imagestring |
| `nsdata` | A native NSData representation of the imageNSData |
| `nsimage` | A native NSImageNSImage |
You can access the native `NSImage` with `nsimage` or a native `NSData` representation of the image with `nsdata`.
```javascript
imageLayer.image.size // { width: 100, height: 100 }
```
As a convenience, you can access the original size of an `ImageData` object via its `size` property.
# ShapePath
```javascript
var ShapePath = require('sketch/dom').ShapePath
```
A shape path layer. It is an instance of [Layer](#layer) so all the methods defined there are available.
| Properties | |
| --- | --- |
| idstring | The unique ID of the ShapePath. |
| namestring | The name of the ShapePath |
| parent[Group](#group) | The group the ShapePath is in. |
| lockedboolean | If the ShapePath is locked. |
| hiddenboolean | If the ShapePath is hidden. |
| frame[Rectangle](#rectangle) | The frame of the ShapePath. This is given in coordinates that are local to the parent of the layer. |
| selectedboolean | If the ShapePath is selected. |
| flow[Flow](#flow) | The prototyping action associated with the ShapePath. |
| exportFormats[ExportFormat](#exportformat)[] | The export formats of the ShapePath. |
| style[Style](#style) | The style of the ShapePath. |
| sharedStyle[SharedStyle](#shared-style) / `null` | The associated shared style or `null`. |
| sharedStyleIdstring / `null` | The ID of the [SharedStyle](#shared-style) or `null`, identical to `sharedStyle.id`. |
| shapeType[ShapeType](#shapepathshapetype) | The type of the Shape Path. It can only be set when creating a new ShapePath. |
| points[CurvePoint](#curvepoint)[] | The points defining the Shape Path. |
| closedboolean | If the Path is closed. |
| editedboolean | If the Path has been edited. |
| Masking Properties | |
| --- | --- |
| masksSiblingsboolean | If the layer acts like a mask for its siblings. |
| maskMode[MaskMode](#layermaskmode) | A mask mode for a [Shape](#shapw) or [ShapePath](#shapepath) masking other layers. |
## Create a new ShapePath
```javascript
const shapePath = new ShapePath({
name: 'my shape path',
shapeType: ShapePath.ShapeType.Oval,
})
```
You can only set the `shapeType` when creating a new one. Once it is created, the `shapeType` is read-only. If it is not specified and you do not specify any `points`, it will default to `ShapePath.ShapeType.Rectangle` (if you do specify some `points`, it will default to `ShapePath.ShapeType.Custom`).
```javascript
const shapePath = ShapePath.fromSVGPath('M10 10 H 90 V 90 H 10 L 10 10')
```
You can also create a new ShapePath from an SVG path (the string that goes in the `d` attribute of a `path` tag in an SVG). See [the MDN documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths) for more information about SVG paths.
## Get the SVG path
```javascript
const svgPath = shapePath.getSVGPath()
```
Returns a string representing the SVG path of the ShapePath.
## `ShapePath.ShapeType`
```javascript
ShapePath.ShapeType.Oval
```
Enumeration of the type of Shared Style.
| Value |
| ----------- |
| `Rectangle` |
| `Oval` |
| `Triangle` |
| `Polygon` |
| `Star` |
| `Custom` |
## `ShapePath.PointType`
```javascript
ShapePath.PointType.Undefined
```
Enumeration of the point types.
| Value |
| -------------- |
| `Undefined` |
| `Straight` |
| `Mirrored` |
| `Asymmetric` |
| `Disconnected` |
# Text
```javascript
var Text = require('sketch/dom').Text
```
A text layer. It is an instance of [Layer](#layer) so all the methods defined there are available.
| Properties | |
| --- | --- |
| idstring | The unique ID of the Text. |
| namestring | The name of the Text |
| parent[Group](#group) | The group the Text is in. |
| lockedboolean | If the Text is locked. |
| hiddenboolean | If the Text is hidden. |
| frame[Rectangle](#rectangle) | The frame of the Text. This is given in coordinates that are local to the parent of the layer. |
| selectedboolean | If the Text is selected. |
| flow[Flow](#flow) | The prototyping action associated with the Text. |
| exportFormats[ExportFormat](#export-format)[] | The export formats of the Symbol Source. |
| transformobject | The transformation applied to the Text. |
| transform.rotationnumber | The rotation of the Text in degrees, clock-wise. |
| transform.flippedHorizontallyboolean | If the Text is horizontally flipped. |
| transform.flippedVerticallyboolean | If the Text is vertically flipped. |
| style[Style](#style) | The style of the Text. |
| sharedStyle[SharedStyle](#shared-style) / `null` | The associated shared style or `null`. |
| sharedStyleIdstring / `null` | The ID of the [SharedStyle](#shared-style) or `null`, identical to `sharedStyle.id`. |
| textstring | The string value of the text layer. |
| lineSpacing[LineSpacing](#textlinespacing) | The line spacing of the layer. |
| fixedWidthboolean | Whether the layer should have a fixed width or a flexible width. |
## Create a new Text
```javascript
var text = new Text({
text: 'my text',
alignment: Text.Alignment.center,
})
```
## Adjust to fit its value
```javascript
text.adjustToFit()
```
Adjust the Text to fit its value.
### Returns
The current Text (useful if you want to chain the calls).
## fragments
```javascript
var fragments = text.fragments
```
Returns a array of the text fragments for the text. Each one is a object containing a rectangle, a baseline offset, the range of the fragment, and the substring `{rect, baselineOffset, range, text}`.
## `Text.Alignment`
```javascript
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. |
## `Text.VerticalAlignment`
```javascript
Text.VerticalAlignment.center
```
Enumeration of the vertical alignments of the text.
| Value | |
| -------- | ---------------------------- |
| `top` | Visually top aligned |
| `center` | Visually vertically centered |
| `bottom` | Visually bottom aligned |
## `Text.LineSpacing`
```javascript
Text.LineSpacing.constantBaseline
```
Enumeration of the line spacing behavior for the text.
| Value | |
| ------------------ | ------------------------------------------------------- |
| `constantBaseline` | Uses min & max line height on paragraph style |
| `variable` | Uses MSConstantBaselineTypesetter for fixed line height |
# Symbol Source
```javascript
var SymbolMaster = require('sketch/dom').SymbolMaster
```
A [Symbol](https://sketch.com/docs/symbols/) Source. It is an instance of [Artboard](#artboard) (hence of [Layer](#layer) and [Group](#group)) so all the methods defined there are available.
| Properties | |
| --- | --- |
| idstring | The unique ID of the Symbol Source object (not to be confused with `symbolId`). |
| namestring | The name of the Symbol Source |
| parent[Group](#group) | The group the Symbol Source is in. |
| frame[Rectangle](#rectangle) | The frame of the Symbol Source. This is given in coordinates that are local to the parent of the layer. |
| selectedboolean | If the Symbol Source is selected. |
| exportFormats[ExportFormat](#export-format)[] | The export formats of the Symbol Source. |
| layers[Layer](#layer)[] | The layers composing the Symbol Source. |
| backgroundobject | The background of the Symbol Source |
| background.enabledboolean | If the background should be enabled, eg. shown or not |
| background.includedInExportboolean | If the background should be exported or if it should be transparent during the export |
| background.includedInInstanceboolean | If the background should appear in the instances of the Symbol Source |
| background.colorstring | The rgba representation of the color of the background |
| symbolIdstring | The unique ID of the Symbol that the Source and its instances share. |
| overrides[Override](#symbol-override)[] | The array of the overrides that the instances of the Symbol Source will be able to change. |
## Create a new Symbol Source
```javascript
var symbol = new SymbolMaster({
name: 'my symbol',
})
```
## Create a new Symbol Source from an Artboard
```javascript
var symbol = SymbolMaster.fromArtboard(artboard)
```
Replace the artboard with a Symbol Source.
| Parameters | |
| --- | --- |
| artboard[Artboard](#artboard) - required | The artboard to create the Symbol Source from. |
### Returns
A new SymbolMaster
## Change to an Artboard
```javascript
var artboard = symbol.toArtboard()
```
Replace the Symbol Source with an artboard and detach all its instances converting them into groups.
### Returns
A new [Artboard](#artboard)
## Create a new Instance
```javascript
var instance = symbol.createNewInstance()
```
Creates a new [SymbolInstance](#symbol-instance) linked to this Source, ready for inserting in the document.
### Returns
A new [SymbolInstance](#symbol-instance)
## Get all the Instances
```javascript
var instances = symbol.getAllInstances()
```
Returns an array of all instances of the Symbol in the document, on all pages.
## Get Library defining the Symbol Source
```javascript
var originLibrary = symbol.getLibrary()
```
If the Symbol Source was imported from a library, the method can be used to:
- know about it
- get the library back
### Returns
The [Library](#library) the Symbol was defined in, or `null` if it is a local symbol.
## Sync the local reference with the library version
```javascript
const success = symbol.syncWithLibrary()
```
If a [Library](#library) has some updates, you can synchronize the local Symbol Source 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
```javascript
const success = symbol.unlinkFromLibrary()
```
You can unlink a Symbol Source from the Library it comes from and make it a local Symbol Source instead. It will be added to the `Symbols` Page.
### Returns
`true` if it succeeded.
# Symbol Instance
```javascript
var SymbolInstance = require('sketch/dom').SymbolInstance
```
A [Symbol](https://sketch.com/docs/symbols/) instance. It is an instance of [Layer](#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 |
| parent[Group](#group) | The group the Symbol Instance is in. |
| lockedboolean | If the Symbol Instance is locked. |
| hiddenboolean | If the Symbol Instance is hidden. |
| frame[Rectangle](#rectangle) | The frame of the Symbol Instance. This is given in coordinates that are local to the parent of the layer. |
| flow[Flow](#flow) | The prototyping action associated with the Symbol. |
| selectedboolean | If the Symbol Instance is selected. |
| exportFormats[ExportFormat](#export-format)[] | The export formats of the Symbol Instance. |
| transformobject | The transformation applied to the Symbol Instance. |
| transform.rotationnumber | The rotation of the Symbol Instance in degrees, clock-wise. |
| transform.flippedHorizontallyboolean | If the Symbol Instance is horizontally flipped. |
| transform.flippedVerticallyboolean | If the Symbol Instance is vertically flipped. |
| style[Style](#style) | The style of the Symbol Instance. |
| symbolIdstring | The unique ID of the Symbol that the instance and its master share. |
| master[SymbolMaster](#symbol-source) | The Symbol Source that the instance is linked to. |
| overrides[Override](#symbol-override)[] | The array of the overrides to modify the instance. |
| expandedLayers [Layer](#layer)[] | A read-only list of overridable layers inside the instance. |
## Create a new Symbol Instance
```javascript
var instance = new SymbolInstance({
name: 'my symbol instance',
symbolId: symbolId,
})
```
## Create a new Symbol Instance from a Symbol Source
```javascript
var instance = symbol.createNewInstance()
```
Creates a new [SymbolInstance](#symbol-instance) linked to this Source, ready for inserting in the document.
### Returns
A new SymbolInstance
## Detach the instance
```javascript
var group = instance.detach()
var group = instance.detach({
recursively: true,
})
```
Replaces a group that contains a copy of the Symbol this instance refers to. Returns `null` if the Source contains no layers instead of inserting an empty group
| Parameters | |
| --- | --- |
| optionsobject | The options to apply when detaching the instance. |
| options.recursivelyboolean | If it should detach the nested symbols as well. Default to `false`. |
### Returns
A new [Group](#group) or `null`
## Set an Override value
```javascript
instance.setOverrideValue(instance.overrides[0], 'overridden')
```
Change the value of the override.
| Parameters | |
| --- | --- |
| override[Override](#symbol-override) - 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).
## Looking inside a Symbol Instance via `expandedLayers`
```js
symbolInstance.expandedLayers.forEach((layer) => {
const name = layer.name
const frame = layer.frame
const isHidden = layer.hidden
const isGroup = typeof layer.layers !== 'undefined'
if (layer.isNestedSymbol) {
const symbolSource = document.getSymbolMasterWithID(layer.symbolId)
// [...]
}
if (layer.type === sketch.Types.Text) {
console.log(layer.text === 'This text is overridden') // true
}
})
```
Nested symbols are represented as [`Groups`](#group) with a couple of unique properties: `isNestedSymbol` and `symbolId` – to help differentiate them from regular layer containers.
### `SymbolInstance.overridesForExpandedLayer()`
To access an instance's overrides while iterating its `expandedLayers` collection, use the new helper method `SymbolInstance.overridesForExpandedLayer()`.
This method returns all available [Overrides](#symbol-override) for a specific expanded layer.
```js
symbolInstance.expandedLayers.forEach((layer) => {
findAndUpdateText(layer, symbolInstance)
})
function findAndUpdateText(layer, parentInstance) {
if (layer.hidden) return
// 1) Get available overrides for this layer
const availableOverrides = parentInstance.overridesForExpandedLayer(layer)
// 2) Find the one you need
const textOverride = availableOverrides.find(o => o.property === 'stringValue')
textOverride?.value = 'New text'
// 3) (optional) Dive into grandchildren
layer.layers?.forEach((grandchild) =>
findAndUpdateText(grandchild, parentInstance),
)
}
```
## Resize with Smart Layout
```javascript
instance.resizeWithSmartLayout()
```
In order to trigger a Smart Layout resize in an instance, for example after changing an override value, call the `resizeWithSmartLayout()` method.
# HotSpot
```javascript
var HotSpot = require('sketch/dom').HotSpot
```
A Sketch hotspot. It is an instance of [Layer](#layer) so all the methods defined there are available.
| Properties | |
| --- | --- |
| idstring | The unique ID of the HotSpot. |
| namestring | The name of the HotSpot |
| parent[Group](#group) | The group the HotSpot is in.. |
| lockedboolean | If the HotSpot is locked. |
| hiddenboolean | If the HotSpot is hidden. |
| frame[Rectangle](#rectangle) | The frame of the HotSpot. This is given in coordinates that are local to the parent of the HotSpot. |
| selectedboolean | If the HotSpot is selected. |
| flow[Flow](#flow) | The prototyping action associated with the HotSpot. |
## Create a new Hotspot
```javascript
new HotSpot()
```
```javascript
new HotSpot({
name: 'my name',
flow: {
target: artboard,
},
})
```
## Create a new Hotspot from a Layer
```javascript
var hotspot = HotSpot.fromLayer(layer)
```
# Slice
```javascript
var Slice = require('sketch/dom').Slice
```
A Sketch slice. It is an instance of [Layer](#layer) so all the methods defined there are available.
| Properties | |
| --- | --- |
| idstring | The unique ID of the Slice. |
| namestring | The name of the Slice |
| parent[Group](#group) | The group the Slice is in. |
| lockedboolean | If the Slice is locked. |
| hiddenboolean | If the Slice is hidden. |
| frame[Rectangle](#rectangle) | The frame of the Slice. This is given in coordinates that are local to the parent of the layer. |
| selectedboolean | If the Slice is selected. |
| exportFormats[ExportFormat](#export-format)[] | The export formats of the Slice. |
# Settings
```js
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
```js
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
```js
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
```js
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
```js
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
```js
var setting = Settings.layerSettingForKey(layer, 'my-key')
```
Return the value of a setting for a given key on a specific [Layer](#layer) or [DataOverride](#dataoverride) or [Override](#override).
| Parameters | |
| --- | --- |
| layer[Layer](#layer) / [DataOverride](#dataoverride) / [Override](#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
```js
Settings.setLayerSettingForKey(layer, 'my-key', 0.1)
```
Store a value of a setting for a given key on a specific [Layer](#layer) or [DataOverride](#dataoverride) or [Override](#override).
| Parameters | |
| --- | --- |
| layer[Layer](#layer) / [DataOverride](#dataoverride) / [Override](#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
```js
var setting = Settings.documentSettingForKey(document, 'my-key')
```
Return the value of a setting for a given key on a specific document.
| Parameters | Description |
| --- | --- |
| document[Document](#document) - 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
```js
Settings.setDocumentSettingForKey(document, 'my-key', 0.1)
```
Store a value of a setting for a given key on a specific document.
| Parameters | |
| --- | --- |
| document[Document](#document) - required | The document on which the setting is set. |
| keystring - required | The setting to set. |
| valueany - required | The value to set it to. |
## Get a session variable
```js
var myVar = Settings.sessionVariable('myVar')
```
Return the value of a variable which is persisted when the plugin finishes to run but is _not_ persisted when Sketch closes. It is useful when you want to keep a value between plugin's runs.
| Parameters | |
| --- | --- |
| keystring - required | The variable to look up. |
### Returns
The setting that was stored for the given key. `undefined` if there was nothing.
## Set a session variable
```js
Settings.setSessionVariable('myVar', 0.1)
```
Store a value of a variable which is persisted when the plugin finishes to run but is _not_ persisted when Sketch closes. It is useful when you want to keep a value between plugin's runs.
| Parameters | |
| -------------------------------------------------- | ----------------------- |
| keystring - required | The variable to set. |
| valueany - required | The value to set it to. |
# UI
```js
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
```js
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
```js
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 an input from the user
```javascript
UI.getInputFromUser(
"What's your name?",
{
initialValue: 'Appleseed',
},
(err, value) => {
if (err) {
// most likely the user canceled the input
return
}
}
)
```
```javascript
UI.getInputFromUser(
"What's your favorite design tool?",
{
type: UI.INPUT_TYPE.selection,
possibleValues: ['Sketch', 'Paper'],
},
(err, value) => {
if (err) {
// most likely the user canceled the input
return
}
}
)
```
Shows a simple input sheet which displays a message, and asks for an input from the user.
| Parameters | |
| --- | --- |
| messagestring - required | The prompt message to show. |
| optionsobject | Options to customize the input sheet. Most of the options depends on the type of the input. |
| option.descriptionstring | A secondary text to describe with more details the input. |
| option.type[Input Type](#uiinput_type) | The type of the input. |
| option.initialValuestring / number | The initial value of the input. |
| option.possibleValuesstring[] - required with a selection | The possible choices that the user can make. Only used for a `selection` input. |
| option.numberOfLinesnumber | Controls the height of the input field. Only used for a `string` input. If a value is provided it converts the textfield into a scrollable textarea. |
| callbackfunction | A function called after the user entered the input. It is called with an `Error` if the user canceled the input and a `string` or `number` depending on the input type (or `undefined`). |
### `UI.INPUT_TYPE`
```js
UI.INPUT_TYPE.selection
```
The enumeration of the different input types.
| Values |
| ----------- |
| `string` |
| `selection` |
## Get the theme of Sketch
```js
var theme = UI.getTheme()
if (theme === 'dark') {
// shows UI in dark theme
} else {
// shows UI in light theme
}
```
Sketch has 2 themes: `light` and `dark`. If your plugin has some custom UI, it should support both as well.
# Data Supplier
```javascript
var DataSupplier = require('sketch/data-supplier')
```
When your plugin supplies some data, don’t forget to set the [`suppliesData`](/guides/plugin-bundles/#suppliesdata) field to `true` in your `manifest.json`!
## Register a Data Supplier
```javascript
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`, `public.image`, or `public.json` (available in Sketch 71+). |
| 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](#text), a native [Shape](#shape) or a native [DataOverride](#dataoverride) (a special object when the data is for an [Override](#override)) |
```javascript
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
```javascript
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(count).keys()].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
```javascript
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. In case of `public.json`, the value is a JSON object. |
| 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](#override).
| Properties | |
| --- | --- |
| idstring | The name of the override. |
| override[Override](#override) | The override whose value will replaced by the supplied data. |
| symbolInstance[SymbolInstance](#symbolinstance) | The Symbol instance that the override is on that will have the data replaced. |
## Deregister your Data Suppliers
```javascript
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
```javascript
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
```js
const sketch = require('sketch')
sketch.export(layer, options)
sketch.export([layer1, layer2, ..., layerN], options)
```
Export individual Layers and entire Pages as image files, image data (`Buffer`), or JSON.
| Parameters | |
| --- | --- |
| objectToExport[Layer](#layer) / [Layer](#layer)[] / [Page](#page) / [Page](#page)[] | The object(s) to export. |
| optionsobject | See below for available options. |
## Export images
| Image export options | |
| --- | --- |
| `formats`string[] | A list of formats to export to (`png`, `jpg`, `webp`, `tiff`, `svg`, `eps`, `pdf` or `json`). (defaults to `"png"`) |
| `scales`string[] | A list of scales which determine the sizes at which the layers are exported. (defaults to `"1"`) |
| `exportFormats`[ExportFormat[]](#exportformat) | A list of export formats to use. These formats **take precedence** over the `formats` and `scales` options. |
| `group-contents-only`boolean | Export only layers that are contained within the group. (default to `false`) |
| `trimmed`boolean | Trim any transparent space around the exported image (leaving it `undefined` will match Sketch's behavior: trim for layers that do not have a background color). |
| `save-for-web`boolean | If exporting a PNG, remove metadata such as the color profile from the exported file. (defaults to `false`) |
| `compact`boolean | If exporting a SVG, make the output more compact. (defaults to `false`) |
| `include-namespaces`boolean | If exporting a SVG, include extra attributes. (defaults to `false`) |
| `progressive`boolean | If exporting a JPG, export a progressive JPEG. (defaults to `false`) |
| `compression`number | 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`) |
### Image files
| File options | |
| --- | --- |
| `output`string | The path of the folder where all exported files are placed. (defaults to `"~/Documents/Sketch Exports"`) |
```js
sketch.export(layer, {
formats: 'png',
output: '/output/directory',
})
sketch.export(layer, {
output: '/output/directory',
exportFormats: [
{
size: '150w',
fileFormat: 'png',
},
],
})
```
To export a Layer to an image file, pass non-empty `output` and `format` options.
#### Configure the filename
```js
sketch.export(layer, {
formats: 'svg',
output: '/output/directory',
filename: 'MyLayer.svg',
})
sketch.export(layer, {
formats: 'svg',
output: '/output/directory',
'use-id-for-name': true,
overwriting: true,
})
```
The resulting image file name will be automatically chosen based on the layer's name and scale by default, but you may override the naming scheme using the following options:
| Filename options | |
| --- | --- |
| `filename`string | Specifies the exact filename for an exported image. When exporting multiple Layers and/or scales, make sure to pass the `suffixing: true` flag as well to let Sketch adapt the given filename to multiple outputs. |
| `use-id-for-name`boolean | Name exported images using their id rather than their name.(defaults to `false`) |
| `overwriting`boolean | Overwrite existing files (if any) with newly generated ones. (defaults to `false`) |
| `suffixing`boolean | Whether to append a numerical suffix to a filename automatically to make them unique within the `output` directory. (defaults to `false`) |
### Raw image data (`Buffer`)
```js
const buffer = sketch.export(layer, {
output: false,
formats: 'png',
})
```
Pass `false` for the `output` option to make `sketch.export()` return a `Buffer` (or an array of `Buffer`s in case of multiple inputs) containing raw image data.
## Export JSON
```js
const sketchJSON = sketch.export(layer, {
formats: 'json',
output: false,
})
sketch.export(layer, {
formats: 'json',
output: '/output/directory',
})
```
Use `"json"` as a `format` to make `sketch.export()` serialize the input layer to JSON and either save it to a file (when the `output` option is provided) or return it as `Object` (when the `output` option is `false`).
## Export pages
```js
sketch.export(page, {
formats: 'png',
output: '/some/folder',
filename: 'area.png',
bounds: '0,8,16,32', // x,y,width,height
})
```
When exporting Pages there's an additional `bounds` option that lets you specify a precise exportable area for the given page.
# import
```javascript
var sketch = require('sketch/dom')
const layer = sketch.createLayerFromData(buffer, 'svg')
```
```javascript
const svgString =
''
const group = sketch.createLayerFromData(svgString, 'svg')
```
Import a file as a Layer.
| Parameters | |
| --- | --- |
| dataBuffer / string | The data for the file. |
| typestring | The type of the file being imported. `"svg"`, `"pdf"`, `"eps"`, or `"bitmap"`. |
The method returns:
- a [Group](#group) if the type is `svg` or if the type is `pdf` and the pdf has only one page
- an [Image](#image) if the type is `bitmap`
- a [Page](#page) if the type is `pdf` and the pdf has multiple pages or `eps`
# find
A more efficient way to find layers fitting one or multiple criteria.
```js
const { find } = require('sketch')
find(`ShapePath, [name="Rectangle"]`)
```
| Parameters | |
| --- | --- |
| predicatestring - required | The search criteria. |
| scope[Group](#group) / [Document](#document) | The scope of the search. By default it is the current Document. |
## Find layers by type
| Type Predicates | Notes |
| --- | --- |
| `Image` | |
| `Page` | |
| `Shape` | |
| `ShapePath` | |
| `Slice` | |
| `SymbolInstance` | |
| `SymbolMaster` | |
| `Text` | |
| `Group`, `Frame`, `Graphic` | See [below](#groups-frames-and-graphics) |
| `Artboard` | Deprecated. See [below](#groups-frames-and-graphics) |
| `*` | Matches any layer type |
### Groups, Frames, and Graphics
```js
const containers = find(`Group`)
```
Use the `Group` type predicate to find all regular layer [Groups](#group) as well as _nested_ [Frames](#working-with-frames-and-graphics) and [Graphics](#working-with-frames-and-graphics).
```js
const frames = find(`Frame`)
```
Use the `Frame` type predicate to find all Frames – nested and top-level. Note that the results will include Graphics as well.
```js
const graphics = find(`Graphic`)
```
Use the `Graphic` type predicate to find all Graphics – nested or top-level.
### Wildcard
```js
const allChildren = find('*', container)
```
A wildcard predicate (`*`) will match layers of any type.
## Find layers by ID
```js
const layer = find(`#61628E95-05C6-4704-B7D0-963D8A7727F7`)
// Hint: use template literals for dynamic predicates
const match = find(`#${layerID}`)
```
Use the `#XXX-YYY-ZZZ` predicate to find a layer with the given identifier.
## Find layers by dimensions/position
```js
const tinyLayers = find(`[frame.width < 100], [frame.height < 100]`, group)
const layersBelowCutoff = find(`[frame.x < ${cutoffX}]`, page)
```
## Find layers by visibility status
```js
const visibleOvals = find(`ShapePath, [hidden=false], [name="Oval"]`)
const allHidden = find(`[hidden=true]`, page)
```
## Find selected layers
```js
const selectedShapes = find(`ShapePath, [selected=true]`)
```
## Find layers by name
```js
const matches = find(`[name="Exact Layer Name"]`)
```
For exact name match use the `[name=]` predicate.
```js
const matches = find(`[name~="case insensitive name"]`)
```
For case-insensitive search use the `[name~=]` predicate.
```js
const matches = find(`[name*="containing"]`)
```
To find partial name matches use the `[name*=]` predicate. There's also the `~*=` version for case-insensitive substring search.
```js
const beginWiths = find(`[name^="Prefix"]`)
const endWiths = find(`[name$="Suffix"]`)
```
To find layers with the given prefix and/or suffix use the `[name^=]` and `[name$=]` predicates respectively.