### Initialize HotSpot Source: https://developer.sketch.com/plugins/reference Provides examples for creating a new Hotspot, both with default properties and with custom name and flow settings. ```javascript var HotSpot = require('sketch/dom').HotSpot new HotSpot() new HotSpot({ name: 'my name', flow: { target: artboard, }, }) ``` -------------------------------- ### Example Sketch Shared Library URL Source: https://developer.sketch.com/app An example URL for adding the Apple iOS Sketch Library, which is hosted on Apple's servers and shared via an appcast RSS file. This illustrates the format for the `url` parameter. ```URL sketch://add-library?url=https%3A%2F%2Fdeveloper.apple.com%2Fdesign%2Fdownloads%2Fsketch.rss ``` -------------------------------- ### Install Sketch Reference Files via npm Source: https://developer.sketch.com/pages/file-format-reference-files This command installs the @sketch-hq/sketch-reference-files npm module, which provides access to reference file metadata and JSON contents for various Sketch document versions. ```Shell npm install @sketch-hq/sketch-reference-files ``` -------------------------------- ### Install Sketch File Format npm Module Source: https://developer.sketch.com/pages/file-format-json-schema Installs the official Sketch file format npm module using either npm or yarn. This module provides access to the JSON schemas for Sketch files. ```bash npm install @sketch-hq/sketch-file-format ``` ```bash yarn install @sketch-hq/sketch-file-format ``` -------------------------------- ### Install Sketch API Source: https://developer.sketch.com/plugins/reference This snippet shows how to require the necessary modules from the Sketch JavaScript API. It demonstrates both individual module imports and a convenient way to import all modules at once. ```javascript var sketch = require('sketch/dom') var async = require('sketch/async') var DataSupplier = require('sketch/data-supplier') var UI = require('sketch/ui') var Settings = require('sketch/settings') // a more convenient require which exposes everything (might be a bit slower) var sketch = require('sketch') ``` -------------------------------- ### Install Sketch File Format TS Source: https://developer.sketch.com/pages/file-format-typescript Installs the npm module for the Sketch File Format TypeScript types using either npm or yarn. ```bash npm install @sketch-hq/sketch-file-format-ts ``` ```bash yarn add @sketch-hq/sketch-file-format-ts ``` -------------------------------- ### Creating and Opening Documents Source: https://developer.sketch.com/plugins/reference Provides examples for creating a new Sketch document and opening an existing one. These operations are essential for plugins that manage document lifecycles or integrate with external files. ```javascript const newDocument = Document.create(); const existingDocument = Document.open("/path/to/your/sketchfile.sketch"); ``` -------------------------------- ### Build Sketch File Format Schemas from Source Source: https://developer.sketch.com/pages/file-format-json-schema Instructions for building the Sketch file format schemas from the source code. This involves checking out the repository, installing dependencies with Yarn, and running the build script. ```bash # 1. Check you have modern versions of Yarn and Node installed # 2. Check out the repo # 3. Run `yarn` to setup the dependencies # 4. Run `yarn build` to generate the schemas into the `dist` folder ``` -------------------------------- ### Updating Schemas Workflow Source: https://developer.sketch.com/pages/file-format-json-schema A step-by-step guide for updating schema YAML source files, validating them, and preparing for a release using the 'changesets' tool. ```Shell yarn validate-schemas yarn validate-file yarn validate-reference-files yarn changeset ``` -------------------------------- ### Sketch Plugin Command Handler Source: https://developer.sketch.com/app Example JavaScript code for a Sketch plugin command that handles URL requests. It demonstrates how to access query parameters passed through the URL scheme. ```javascript const sketch = require('sketch') // If you're using skpm: export function handleURL(context) function handleURL(context) { let query = context.actionContext.query sketch.UI.message(query.msg || '👋') } ``` -------------------------------- ### Creating Shape and Image Layers Source: https://developer.sketch.com/plugins/reference Provides examples for creating new shape layers, image layers, and accessing image data. This is for programmatically adding graphical elements to a document. ```javascript const shape = Shape.create(); const image = Image.create(); const imageData = image.imageData; ``` -------------------------------- ### Define Linear Gradient Fill Source: https://developer.sketch.com/plugins/reference Provides an example of setting a linear gradient fill for a shape's style. It specifies the gradient type, start and end points, and color stops. ```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', }, ], }, }, ] ``` -------------------------------- ### Handle Color Overrides Source: https://developer.sketch.com/plugins/reference Provides examples for setting color overrides, including fill colors and specific indexed colors for fills, borders, and shadows. ```javascript 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 } ``` -------------------------------- ### Get User Input with Initial Value Source: https://developer.sketch.com/plugins/reference Prompts the user for input with a specified message and an initial value. Handles potential user cancellation. ```javascript UI.getInputFromUser( "What's your name?", { initialValue: 'Appleseed', }, (err, value) => { if (err) { // most likely the user canceled the input return } } ) ``` -------------------------------- ### Page and Artboard Operations Source: https://developer.sketch.com/plugins/reference Shows how to create new pages, get selected layers on a page, and retrieve top-level frames (artboards). Also covers legacy Artboard operations. ```javascript const page = Page.create(); const artboards = page.getTopLevelFrames(); ``` -------------------------------- ### Example TypeScript Configuration Source: https://developer.sketch.com/pages/file-format-reference-files This is a standard TypeScript configuration file (tsconfig.json) used for compiling TypeScript code. It includes settings for module resolution, target JavaScript version, and output directory. ```JSON { "compilerOptions": { "target": "es2019", "module": "esnext", "lib": [ "dom", "dom.iterable", "esnext" ], "jsx": "react", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true }, "include": [ "src" ] } ``` -------------------------------- ### Working with Libraries Source: https://developer.sketch.com/plugins/reference Provides methods for accessing, getting, and removing libraries, as well as retrieving importable objects like symbols and styles from them. This facilitates the use of external design assets. ```javascript const libraries = Library.getAll(); const library = Library.getFromPath("/path/to/library.sketch"); Library.remove(library); ``` -------------------------------- ### Plugin and Sketch Settings Management Source: https://developer.sketch.com/plugins/reference Demonstrates how to get and set various settings, including plugin settings, Sketch application settings, layer settings, and document settings. This allows plugins to store and retrieve configuration data. ```javascript const pluginSetting = Settings.getPluginSetting("mySetting"); Settings.setPluginSetting("mySetting", "myValue"); Settings.setLayerSetting(layer, "layerSetting", 123); ``` -------------------------------- ### Get Plugin Setting Source: https://developer.sketch.com/plugins/reference Explains how to retrieve a user-defined setting for a plugin using a specific key. Settings are persisted across Sketch sessions. ```javascript var Settings = require('sketch/settings') var setting = Settings.settingForKey('my-key') ``` -------------------------------- ### Find Layers by Name Prefix Source: https://developer.sketch.com/plugins/reference Locate layers that start with a specific prefix. This predicate helps in finding layers that follow a naming convention. ```JavaScript const beginWiths = find(`[name^="Prefix"]`) ``` -------------------------------- ### Get User Selection Input Source: https://developer.sketch.com/plugins/reference Prompts the user to select from a list of possible values. Handles potential user cancellation. ```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 } } ) ``` -------------------------------- ### Get Plugin Setting Source: https://developer.sketch.com/plugins/reference Retrieves the value of a setting for a given key that is scoped to your plugin. Returns undefined if the key does not exist. ```javascript var setting = Settings.globalSettingForKey('my-key') ``` -------------------------------- ### UI Interaction and Messaging Source: https://developer.sketch.com/plugins/reference Provides methods for interacting with the Sketch user interface, such as showing messages, displaying alerts, and getting user input. This enables plugins to communicate with the user. ```javascript UI.message("Operation complete!"); UI.alert("Warning", "Are you sure?"); const userInput = UI.getInput("Enter value:"); ``` -------------------------------- ### Get Importable Swatch References Source: https://developer.sketch.com/plugins/reference Fetches references for shared swatches available for import into a Sketch document. Similar to text styles, using these references is the recommended approach for importing swatches to maintain consistency. ```javascript var document = sketch.getSelectedDocument() var stylesReferences = library.getImportableSwatchReferencesForDocument( document ) ``` -------------------------------- ### Working with Shape Paths Source: https://developer.sketch.com/plugins/reference Demonstrates how to create new shape paths, get their SVG path data, and access their point types. This is for advanced vector manipulation. ```javascript const shapePath = ShapePath.create(); const svgPath = shapePath.getSVGPath(); const pointType = shapePath.PointType.Bezier; ``` -------------------------------- ### Get All Symbol Instances Source: https://developer.sketch.com/plugins/reference Retrieves an array containing all instances of a specific SymbolMaster across all pages in the document. This is helpful for managing symbol usage. ```javascript var instances = symbol.getAllInstances() ``` -------------------------------- ### Create New Sketch Document Source: https://developer.sketch.com/plugins/reference This code shows the straightforward way to create a brand new Sketch document using the JavaScript API. This is the starting point for generating new design files programmatically. ```javascript var document = new Document() ``` -------------------------------- ### Get All Instances Layers of Shared Style Source: https://developer.sketch.com/plugins/reference Returns an array of all layers within the document that utilize a specific Shared Style as an instance, regardless of the page they are on. ```javascript var layers = sharedStyle.getAllInstancesLayers() ``` -------------------------------- ### Import Schemas in JavaScript/TypeScript Source: https://developer.sketch.com/pages/file-format-json-schema Demonstrates how to import the Sketch file format schemas into a JavaScript or TypeScript project after installation. The imported 'schemas' object contains various schema definitions. ```javascript import schemas from '@sketch-hq/sketch-file-format' ``` -------------------------------- ### Style Blending Mode Enumeration Source: https://developer.sketch.com/plugins/reference Provides an example of using the Style.BlendingMode enumeration to set the blending mode for a layer. The enumeration lists various available blending modes. ```javascript Style.BlendingMode.Darken ``` -------------------------------- ### Manipulate Font Axes for Variable Fonts (JavaScript) Source: https://developer.sketch.com/plugins/reference Provides an example of how to access and modify the properties of variable fonts using the `fontAxes` object. It demonstrates getting the available axes, updating specific axis values (like Weight and Monospace), and applying these changes back to the text layer. ```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 } ``` -------------------------------- ### Build Project Module Source: https://developer.sketch.com/pages/file-format-reference-files Builds the project module and outputs the result into the `dist/` folder. This is a standard build command for compiling the project's code. ```Shell yarn build ``` -------------------------------- ### Point and Rectangle Operations Source: https://developer.sketch.com/plugins/reference Provides methods for getting CGPoint and NSPoint, as well as performing operations like offsetting, scaling, and changing the coordinate basis of rectangles. This is useful for geometric calculations. ```javascript const point = Point.getCGPoint(10, 20); const rect = Rectangle.getCGRect(0, 0, 100, 50); rect.offset(10, 10); ``` -------------------------------- ### Initialize SymbolInstance Source: https://developer.sketch.com/plugins/reference Demonstrates how to create a new SymbolInstance with a specified name and symbol ID. ```javascript var SymbolInstance = require('sketch/dom').SymbolInstance var instance = new SymbolInstance({ name: 'my symbol instance', symbolId: symbolId, }) ``` -------------------------------- ### Handling Symbol Overrides Source: https://developer.sketch.com/plugins/reference Explains how to get the frame of a symbol override and how to set various types of overrides, including text, image, and color. This is crucial for customizing symbol instances. ```javascript const overrideFrame = override.getFrame(); override.setValue("New Text", "text"); override.setValue(new Color(1, 0, 0, 1), "color"); ``` -------------------------------- ### Symbol Source Creation and Linking Source: https://developer.sketch.com/plugins/reference Demonstrates creating new symbol sources, converting artboards to symbol sources, and managing the link between local symbol instances and their library versions. ```javascript const symbolSource = SymbolSource.create(); const library = symbolSource.getLibrary(); symbolSource.unlinkFromLibrary(); ``` -------------------------------- ### Get Sketch Theme Source: https://developer.sketch.com/plugins/reference Retrieves the current theme of Sketch ('dark' or 'light') to adapt plugin UI accordingly. ```javascript var theme = UI.getTheme() if (theme === 'dark') { // shows UI in dark theme } else { // shows UI in light theme } ``` -------------------------------- ### Layer Sizing and Pinning Source: https://developer.sketch.com/plugins/reference Explains how to manage layer sizing properties and pinning behavior, which are crucial for responsive design and how layers adapt to changes in their parent containers. ```javascript layer.sizing = Layer.Sizing.Stretch; layer.pin = Layer.Pin.Left; layer.pin = Layer.Pin.TopRight; ``` -------------------------------- ### Access All Open Sketch Documents Source: https://developer.sketch.com/plugins/reference This snippet illustrates how to get a list of all currently open Sketch documents. This is useful for managing multiple design files simultaneously or performing batch operations. ```javascript var documents = require('sketch/dom').getDocuments() // also exposed on Document var documents = Document.getDocuments() ``` -------------------------------- ### Manage Changesets Source: https://developer.sketch.com/pages/file-format-reference-files Opens an interactive command-line interface (CLI) to add a changeset. Changesets are used to manage versioning and changelogs for releases. ```Shell yarn changeset ``` -------------------------------- ### Get Document Setting Source: https://developer.sketch.com/plugins/reference Retrieves a setting value associated with a specific document. It requires the document object and the setting key. ```javascript var setting = Settings.documentSettingForKey(document, 'my-key') ``` -------------------------------- ### Symbol Source and Instance Management Source: https://developer.sketch.com/plugins/reference Demonstrates how to retrieve symbol sources and create symbol instances. This is fundamental for working with reusable components in Sketch, enabling efficient design system management. ```javascript const symbolSources = Document.getSymbolSources(); const symbolSource = Document.findSymbolSource("Symbol ID"); const symbolInstance = layer.createSymbolInstance(); ``` -------------------------------- ### Get Selected Layers of a Page Source: https://developer.sketch.com/plugins/reference Retrieves the layers that are currently selected by the user on the active page. This returns a Selection object. ```javascript var selection = document.selectedLayers ``` -------------------------------- ### Add Reference Files for New Sketch Version Source: https://developer.sketch.com/pages/file-format-reference-files Steps to add reference files for a new Sketch version. This involves updating configuration, downloading binaries, generating files, and submitting a pull request. ```Shell yarn download-apps yarn generate-files ``` -------------------------------- ### Get Override Frame Source: https://developer.sketch.com/plugins/reference Retrieves the frame of an override, which may differ from the layer's frame if the Symbol Instance has been scaled. ```javascript var frame = override.getFrame() ``` -------------------------------- ### Get Importable Symbols from Library Source: https://developer.sketch.com/plugins/reference Fetches references to symbols that can be imported from a Sketch library into a specific document. It's recommended to use these references rather than accessing the library's document directly to ensure instances stay in sync. ```javascript var document = sketch.getSelectedDocument() var symbolReferences = library.getImportableSymbolReferencesForDocument( document ) ``` -------------------------------- ### Download Sketch App Binaries Source: https://developer.sketch.com/pages/file-format-reference-files Downloads and caches all necessary Sketch app binaries for generating files. This script ensures that the correct versions of Sketch are available locally for the file generation process. ```Shell yarn download-apps ``` -------------------------------- ### Get Session Variable Source: https://developer.sketch.com/plugins/reference Retrieves the value of a session variable by its key. Session variables are persisted between plugin runs but not when Sketch closes. ```javascript var myVar = Settings.sessionVariable('myVar') ``` -------------------------------- ### Get Importable Layer Styles from Library Source: https://developer.sketch.com/plugins/reference Retrieves references for shared layer styles available for import from a Sketch library into a given document. Using these references helps maintain synchronization for imported styles, similar to how symbol instances are managed. ```javascript var document = sketch.getSelectedDocument() var stylesReferences = library.getImportableLayerStyleReferencesForDocument( document ) ``` -------------------------------- ### Get the Symbols Page Source: https://developer.sketch.com/plugins/reference Retrieves the dedicated Symbols Page for a given document. Returns the Page object if it exists, otherwise undefined. ```javascript var symbolsPage = Page.getSymbolsPage(document) ``` -------------------------------- ### Create New Group Source: https://developer.sketch.com/plugins/reference Demonstrates creating a new Group instance. It shows a basic instantiation and a more complex one with properties like name and initial layers. ```javascript new Group() var group = new Group({ name: 'my name', layers: [ { type: sketch.Types.Text, text: 'Hello world', }, ], }) ``` -------------------------------- ### Get Library for Document Path Source: https://developer.sketch.com/plugins/reference Retrieves a Sketch library associated with a specific document path. If the document is already registered as a library, it returns the existing library; otherwise, it adds the document as a new library and returns it. ```javascript var library = Library.getLibraryForDocumentAtPath( 'path/to/existing/document.sketch' ) ``` -------------------------------- ### Get All Symbol Sources Source: https://developer.sketch.com/plugins/reference Retrieves all Symbol Sources defined within the document. This method returns an array containing all SymbolMaster objects. ```javascript var symbols = document.getSymbols() ``` -------------------------------- ### Initialize UI Module Source: https://developer.sketch.com/plugins/reference Loads the UI module from the 'sketch/ui' library, providing access to user interface functions. ```javascript var UI = require('sketch/ui') ``` -------------------------------- ### Create SymbolInstance from Symbol Source Source: https://developer.sketch.com/plugins/reference Shows how to create a new SymbolInstance linked to a Symbol Source. This instance is ready to be inserted into the document. ```javascript var SymbolInstance = require('sketch/dom').SymbolInstance var instance = symbol.createNewInstance() ``` -------------------------------- ### Build Project Source: https://developer.sketch.com/pages/file-format-typescript Builds the project and outputs the compiled files to the `dist` folder. ```bash yarn build ``` -------------------------------- ### Get Layer Setting Source: https://developer.sketch.com/plugins/reference Retrieves a setting value associated with a specific layer, DataOverride, or Override. It takes the layer object and the key as parameters. ```javascript var setting = Settings.layerSettingForKey(layer, 'my-key') ``` -------------------------------- ### Get Symbol Master Library Source: https://developer.sketch.com/plugins/reference Returns the library from which a SymbolMaster was imported. If the symbol is local, it returns null. This helps in managing symbol sources. ```javascript var originLibrary = symbol.getLibrary() ``` -------------------------------- ### Get Selection Layers Source: https://developer.sketch.com/plugins/reference Retrieves the currently selected layers. This is a utility class to represent the layers selection, providing methods for easier interaction. ```javascript var selection = document.selectedLayers ``` -------------------------------- ### Get All Instances of Shared Style Source: https://developer.sketch.com/plugins/reference Retrieves an array containing all instances of a given Shared Style present throughout the document, across all pages. ```javascript var styles = sharedStyle.getAllInstances() ``` -------------------------------- ### Create Back Action Source: https://developer.sketch.com/plugins/reference Creates a back action for prototyping by setting the target to Flow.BackTarget. ```javascript layer.flow = { target: Flow.BackTarget, } ``` -------------------------------- ### Get Library Defining Shared Style Source: https://developer.sketch.com/plugins/reference Identifies and returns the Library from which a Shared Style was imported. Returns null if the style is local and not linked to any library. ```javascript var originLibrary = sharedStyle.getLibrary() ``` -------------------------------- ### Create the Symbols Page Source: https://developer.sketch.com/plugins/reference Creates a new page that Sketch will recognize as the Symbols Page. This page is then assigned to the document. ```javascript var symbolsPage = Page.createSymbolsPage() symbolsPage.parent = document ``` -------------------------------- ### Supply All Data at Once Source: https://developer.sketch.com/plugins/reference Provides all requested data for a given key in a single call, typically after data generation is complete. ```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.from(Array(count)).map(i => 'foo') DataSupplier.supplyData(key, data) } ``` -------------------------------- ### Get Library's Document Source: https://developer.sketch.com/plugins/reference Retrieves the Sketch `Document` object that a `Library` object references. This method might throw an error if the document cannot be accessed. ```javascript var libDocument = library.getDocument() ``` -------------------------------- ### Initialize Slice Source: https://developer.sketch.com/plugins/reference Demonstrates the initialization of a Slice object, which is used for exporting specific areas of a Sketch document. ```javascript var Slice = require('sketch/dom').Slice ``` -------------------------------- ### Get Text Fragments Source: https://developer.sketch.com/plugins/reference Retrieves an array of text fragments from a Text layer. Each fragment object contains its rectangle, baseline offset, range, and the text substring. ```javascript var fragments = text.fragments ``` -------------------------------- ### Export Pages from Sketch File using sketchtool Source: https://developer.sketch.com/index This command-line snippet exports all pages from a specified Sketch file using the `sketchtool` utility. It first finds the Sketch application path and then executes the export command, generating PNG images for each page in the current directory. ```Shell SKETCH=$(mdfind kMDItemCFBundleIdentifier == 'com.bohemiancoding.sketch3' | head -n 1) && \ "$SKETCH/Contents/Resources/sketchtool/bin/sketchtool" export pages ~/Desktop/App.sketch ``` -------------------------------- ### Get SVG Path of a ShapePath Source: https://developer.sketch.com/plugins/reference Retrieves the SVG path string representation of a given ShapePath object. This is useful for exporting or further processing the shape's geometry. ```javascript const svgPath = shapePath.getSVGPath() ``` -------------------------------- ### Generate Reference Files Source: https://developer.sketch.com/pages/file-format-reference-files Generates reference files into the `files/` folder. Existing files are skipped, so the `files/` folder should be deleted to regenerate all files. This command is run manually and is not part of the standard build process. ```Shell yarn generate-files ``` -------------------------------- ### Get Layer Index (JavaScript) Source: https://developer.sketch.com/plugins/reference Explains how to retrieve the position (index) of a Sketch layer within its parent group. The index determines the visual order of layers. ```javascript var index = layer.index ``` -------------------------------- ### Add New Reference File Feature Type Source: https://developer.sketch.com/pages/file-format-reference-files Steps to add a new feature type for reference files. This includes adding plugin code, updating configuration, downloading binaries, generating files, and submitting a pull request. ```Shell yarn download-apps yarn generate-files ``` -------------------------------- ### Prototyping Actions and Flows Source: https://developer.sketch.com/plugins/reference Shows how to create new prototyping actions, check target validity, and define back targets and animation types. This is used for building interactive prototypes within Sketch. ```javascript const flow = Flow.create(); flow.setTarget(targetLayer); flow.setAnimationType(Flow.AnimationType.SlideLeft); ``` -------------------------------- ### Style Frames and Graphics Source: https://developer.sketch.com/plugins/reference Demonstrates how to apply styling options, such as fills and border options, to Frames and Graphics. These containers support the same styling properties as other `StyledLayer` objects. ```javascript const { Style } = require('sketch/dom') graphic.style.fills = [ { color: '#c0ffee', fillType: Style.FillType.Color, thickness: 5, }, ] graphic.style.borderOptions = { dashPattern: [20, 5, 20, 5], } ``` -------------------------------- ### Supply Data One by One Source: https://developer.sketch.com/plugins/reference This function handles the 'SupplyKey' action, iterating through provided items and supplying data for each using the DataSupplier.supplyDataAtIndex method. It expects context data containing a key and items to process. ```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) }) } ``` -------------------------------- ### Get Selected Layer ID in Sketch Source: https://developer.sketch.com/app A JavaScript snippet to retrieve the ID of the currently selected layer in a Sketch document. This ID is needed for the `centerOnLayer` parameter in the URL scheme. ```javascript const document = require('sketch/dom').getSelectedDocument() document.selectedLayers.forEach((layer) => console.log(layer.id)) ``` -------------------------------- ### Execute Sketch Plugin with Message Parameter Source: https://developer.sketch.com/app Demonstrates how to call a Sketch plugin command via the URL scheme, passing a custom message using the `msg` query parameter. The plugin's `handleURL` function will display this message. ```URL sketch://plugin/com.example.sketch.messenger/message.show?msg=Hello%20World ``` -------------------------------- ### Modify Text Overrides Source: https://developer.sketch.com/plugins/reference Provides examples of how to modify various text-related properties of a Symbol override, such as string value, text style, size, color, decoration, and horizontal alignment. ```javascript 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 } ``` -------------------------------- ### Stack Layout Management Source: https://developer.sketch.com/plugins/reference Details how to inspect, create, and manipulate stack layouts, including converting containers to stacks and removing stack layouts. This is for managing responsive layouts within Sketch. ```javascript const stack = StackLayout.create(); stack.direction = StackLayout.Direction.Vertical; container.addStackLayout(stack); ``` -------------------------------- ### Working with Shared Styles Source: https://developer.sketch.com/plugins/reference Shows how to find shared layer and text styles, and how to check and sync local styles with their shared counterparts. This is key for maintaining design consistency across a project. ```javascript const sharedLayerStyle = Document.findSharedLayerStyle("Style ID"); const sharedTextStyle = Document.findSharedTextStyle("Text Style ID"); const isSynced = style.isSyncedWithSharedStyle(); style.syncWithSharedStyle(); ``` -------------------------------- ### Get Global Gradient Assets Source: https://developer.sketch.com/plugins/reference Retrieves an array of all globally defined GradientAsset objects within the Sketch document. These represent reusable gradients stored in the document's assets. ```javascript var sketch = require('sketch/dom') var gradients = sketch.globalAssets.gradients ``` -------------------------------- ### Get Global Color Assets Source: https://developer.sketch.com/plugins/reference Retrieves an array of all globally defined ColorAsset objects within the Sketch document. These represent reusable colors stored in the document's assets. ```javascript var sketch = require('sketch/dom') var colors = sketch.globalAssets.colors ``` -------------------------------- ### Register a Data Supplier Source: https://developer.sketch.com/plugins/reference Registers a data supplier with a specified data type, name, and action key. This is typically done on plugin startup. ```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' ) } ``` -------------------------------- ### Create Prototyping Action (Target Artboard) Source: https://developer.sketch.com/plugins/reference Creates a new prototyping action by setting the target artboard for a layer. ```javascript layer.flow = { target: artboard, } ``` -------------------------------- ### Resize SymbolInstance with Smart Layout Source: https://developer.sketch.com/plugins/reference Demonstrates how to trigger a Smart Layout resize for a SymbolInstance, typically after modifying an override value. ```javascript var SymbolInstance = require('sketch/dom').SymbolInstance instance.resizeWithSmartLayout() ``` -------------------------------- ### Initialize StackLayout Source: https://developer.sketch.com/plugins/reference Initializes a new Group with a StackLayout configuration. This allows you to define the layout properties such as direction, alignment, gap, and padding for the group's children. ```javascript const { StackLayout } = require('sketch/dom') const stack = new Group({ stackLayout: { direction: StackLayout.Direction.Column, alignItems: StackLayout.AlignItems.Center, gap: 120, }, layers: [ // ... ], }) ``` -------------------------------- ### Check Vertical Pinning Source: https://developer.sketch.com/plugins/reference Checks if the top edge of a layer is pinned using the Pin enum. This example checks if the vertical pins are set to 'Min', indicating the top edge is pinned. ```javascript const { Pin } = require('sketch/dom') if (layer.verticalPins == Pin.Min) { console.log('The top edge is pinned, the bottom edge is not.') } ``` -------------------------------- ### Create a New Page Source: https://developer.sketch.com/plugins/reference Demonstrates how to create a new page in a Sketch document. You can create a default page or specify a name during creation. ```javascript new Page() ``` ```javascript new Page({ name: 'my page', }) ``` -------------------------------- ### Sketch Plugin Manifest Source: https://developer.sketch.com/app A JSON file defining a Sketch plugin's properties, including its identifier, commands, and handlers. Crucially, it specifies the `HandleURL` action for commands that respond to the URL scheme. ```json { "identifier": "com.example.sketch.messenger", "commands": [ { "name": "Message", "identifier": "message.show", "script": "command.js", "handlers": { "actions": { "HandleURL": "handleURL" } } } ] } ``` -------------------------------- ### Apply Color Fill Source: https://developer.sketch.com/plugins/reference Illustrates how to set a solid color fill for a shape's style using a hex color string. ```javascript shape.style.fills = [ { color: '#c0ffee', fillType: Style.FillType.Color, }, ] ``` -------------------------------- ### Create Conventional Commit Source: https://developer.sketch.com/pages/file-format-reference-files Opens an interactive CLI to create a Git commit message following the conventional commits format. This helps maintain a standardized commit history. ```Shell yarn commit ``` -------------------------------- ### Creating and Manipulating Groups Source: https://developer.sketch.com/plugins/reference Demonstrates how to create new groups, work with frames and graphics within groups, and adjust groups to fit their children. This is fundamental for organizing layers. ```javascript const group = Group.create(); group.adjustToFitItsChildren(); ``` -------------------------------- ### Commitlint Configuration for CI Source: https://developer.sketch.com/pages/file-format-reference-files This commitlint.config.js file configures Commitlint, a tool for linting commit messages. It ensures that commit messages adhere to a specific format, which is useful for maintaining a consistent commit history and automating changelog generation. ```JavaScript module.exports = { extends: ['@commitlint/config-conventional'], }; ``` -------------------------------- ### Create Prototyping Action (Target and Animation) Source: https://developer.sketch.com/plugins/reference Creates a prototyping action with a specified target artboard and animation type. ```javascript layer.flow = { target: artboard, animationType: Flow.AnimationType.slideFromLeft, } ``` -------------------------------- ### Build and Validate Schemas with Yarn Source: https://developer.sketch.com/pages/file-format-json-schema Scripts for building, validating, and formatting schemas using Yarn. These commands are essential for maintaining the integrity and quality of the schema files. ```Shell yarn build yarn validate-schemas yarn validate-reference-files 121,122,123 yarn validate-file /absolute/path/to/file.sketch yarn format-check ``` -------------------------------- ### Create HotSpot from Layer Source: https://developer.sketch.com/plugins/reference Shows how to create a Hotspot directly from an existing Layer object. ```javascript var HotSpot = require('sketch/dom').HotSpot var hotspot = HotSpot.fromLayer(layer) ``` -------------------------------- ### Get Default Line Height Source: https://developer.sketch.com/plugins/reference Retrieves the default line height for a Text layer. If no line height is explicitly set, this method returns the font's default value. Returns a number for Text layers or undefined. ```javascript var defaultlineHeight = style.getDefaultLineHeight() ``` -------------------------------- ### Webpack Configuration for Sketch Reference Files Source: https://developer.sketch.com/pages/file-format-reference-files This webpack.config.js file configures Webpack for building the Sketch reference files project. It includes settings for handling TypeScript, JSON, and other assets, as well as output configuration. ```JavaScript const path = require('path'); module.exports = { entry: './src/index.ts', mode: 'production', module: { rules: [ { test: /\.ts$/, use: 'ts-loader', exclude: /node_modules/, }, { test: /\.json$/, loader: 'json-loader', type: 'javascript/auto', }, ], }, resolve: { extensions: ['.ts', '.js'], }, output: { filename: 'index.js', path: path.resolve(__dirname, 'dist'), libraryTarget: 'umd', library: '@sketch-hq/sketch-reference-files', umdNamedDefine: true, }, }; ``` -------------------------------- ### Get Importable Symbol References Source: https://developer.sketch.com/plugins/reference Obtains references for shared symbols that can be imported into the current Sketch document. These references provide read-only access to symbol properties like ID, name, object type, and the library it belongs to. ```javascript var symbolReferences = library.getImportableSymbolReferencesForDocument( document ) ``` -------------------------------- ### Run Build Script Unit Tests Source: https://developer.sketch.com/pages/file-format-typescript Executes unit tests for the build scripts to ensure their functionality. ```bash yarn test ``` -------------------------------- ### Get Importable Text Style References Source: https://developer.sketch.com/plugins/reference Retrieves references for shared text styles that can be imported into a Sketch document. It's important to use these references rather than accessing shared styles directly from a library's document to ensure proper synchronization. ```javascript var document = sketch.getSelectedDocument() var stylesReferences = library.getImportableTextStyleReferencesForDocument( document ) ``` -------------------------------- ### Create a new Image layer Source: https://developer.sketch.com/plugins/reference Shows how to create a new Image layer, optionally specifying the image source and frame dimensions. The image property accepts various formats including file paths and base64 strings. ```javascript var Image = require('sketch/dom').Image var imageLayer = new Image({ image: 'path/to/image.png', }) var imageLayer = new Image({ image: 'path/to/image.png', frame: new Rectangle(0, 0, 300, 200), }) ``` -------------------------------- ### Get Remote Library from RSS Feed Source: https://developer.sketch.com/plugins/reference Fetches a remote Sketch library using its RSS feed URL. If the library has already been added, it returns the existing one. Otherwise, it adds the library from the feed and provides a callback to handle success or failure. ```javascript Library.getRemoteLibraryWithRSS( 'https://url/to/feed/rss.xml', (err, library) => { if (err) { // oh no, failed to load the library } } ) ``` -------------------------------- ### Handle Visibility Overrides Source: https://developer.sketch.com/plugins/reference Illustrates setting visibility overrides for layers using a boolean flag. ```javascript if (override.property === 'isVisible') { override.value = false } ``` -------------------------------- ### Open Sketch Document Source: https://developer.sketch.com/plugins/reference Opens an existing sketch document or prompts the user to select one. This is an asynchronous operation, requiring a callback for post-execution actions. It accepts an optional path to the 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 } }) ``` -------------------------------- ### Set Smart Layout Source: https://developer.sketch.com/plugins/reference Illustrates how to apply a Smart Layout to a SymbolMaster or Group layer using the `smartLayout` setter with predefined values like `SmartLayout.TopToBottom`. ```javascript const SmartLayout = require('sketch').SmartLayout layer.smartLayout = SmartLayout.TopToBottom ``` -------------------------------- ### Find Artboards (Legacy Frames/Graphics) using find API Source: https://developer.sketch.com/plugins/reference Shows how to use the `find` API to locate top-level Frames (legacy Artboards) within the entire document or a specific page. ```javascript const { find } = require('sketch') find('Artboard').forEach((frame) => { // ✅ Treat this `frame` as an Artboard }) ``` ```javascript find('Artboard', currentPage).forEach((frame) => { // ✅ Treat this `frame` as an Artboard }) ``` -------------------------------- ### Symbol Instance Creation and Detachment Source: https://developer.sketch.com/plugins/reference Provides methods for creating new symbol instances, detaching them from their source, and setting override values. This is key for customizing and managing symbol usage. ```javascript const instance = SymbolInstance.create(symbolSource); instance.detach(); instance.setOverrideValue("override-name", "new-value"); ``` -------------------------------- ### Add and Remove Stack Items Source: https://developer.sketch.com/plugins/reference Demonstrates how to add items to a Stack's layers collection and remove items using `push` and `splice`. It also shows how to set individual layer properties like `ignoresStackLayout`. ```javascript let stack = new Group({ stackLayout: { padding: 10 }, layers: [ // ... ], }) let layer = new Text() stack.layers.push(layer) stack.layers.splice(0, 2) stack.layers[0].ignoresStackLayout = true const stack = new Group({ stackLayout: { padding: 10 }, layers: [ new Text({ preservesSpaceInStackLayoutWhenHidden: true, }), ], }) ``` -------------------------------- ### Hotspot Creation Source: https://developer.sketch.com/plugins/reference Shows how to create new hotspot layers, either independently or from existing layers. Hotspots are used for defining interactive areas in prototypes. ```javascript const hotspot = HotSpot.create(); const hotspotFromLayer = HotSpot.createFromLayer(layer); ``` -------------------------------- ### Run Sketch Plugin Command Source: https://developer.sketch.com/app Executes a specific command within a Sketch plugin. This allows for programmatic control of plugin functionalities and passing custom parameters via the URL. ```URL sketch://plugin/my.plugin.identifier/my.command.identifier ``` -------------------------------- ### Check Formatting Source: https://developer.sketch.com/pages/file-format-typescript Checks the codebase for formatting consistency using Prettier. ```bash yarn format-check ``` -------------------------------- ### Access Raw Reference File JSON via HTTP Source: https://developer.sketch.com/pages/file-format-reference-files This URL provides access to the raw reference file JSON data hosted on unpkg.com. It allows you to retrieve the Sketch file JSON content directly via HTTP requests for specific versions and files. ```HTTP https://unpkg.com/browse/@sketch-hq/sketch-reference-files@latest/files/ ``` -------------------------------- ### Handle Image Resize Behavior Overrides Source: https://developer.sketch.com/plugins/reference Shows how to manage image resize behavior overrides by mapping string representations to the ResizeBehavior enum and updating the value. ```javascript 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 } } ``` -------------------------------- ### Data Supplier Registration Source: https://developer.sketch.com/plugins/reference Shows how to register a data supplier, which allows plugins to provide dynamic data to Sketch's data features. This is useful for populating designs with realistic content. ```javascript DataSupplier.register("My Data Supplier", "image", (context, options) => { // Return data here }); ``` -------------------------------- ### Create Swatch and Reference Color Source: https://developer.sketch.com/plugins/reference Creates a Swatch object from provided name and color hex string, and then retrieves its referencing Color object. This is useful for creating new swatches or working with existing ones. ```javascript var sketch = require('sketch') var mySwatch = sketch.Swatch.from({ name: 'Safety Orange', color: '#ff6600' }) var myColor = mySwatch.referencingColor ``` -------------------------------- ### Handle Layer Style Overrides Source: https://developer.sketch.com/plugins/reference Demonstrates setting layer style overrides using a shared layer style identifier. ```javascript if (override.property === 'layerStyle') { override.value = someLayerStyle.id } ``` -------------------------------- ### Export Layers and Pages Source: https://developer.sketch.com/plugins/reference Provides functionality to export layers and pages as various image formats (PNG, JPG, etc.), image data (Buffer), or JSON. It supports exporting single or multiple objects and offers extensive options for format, scale, and specific export settings. ```javascript const sketch = require('sketch') sketch.export(layer, options) sketch.export([layer1, layer2, ..., layerN], options) ``` -------------------------------- ### Trigger Smart Layout Resize Source: https://developer.sketch.com/plugins/reference Explains how to trigger a Smart Layout resize on a SymbolInstance after changing an override value by calling the `resizeWithSmartLayout()` method. ```javascript const SmartLayout = require('sketch').SmartLayout symbol.smartLayout = SmartLayout.TopToBottom symbolInstance.resizeWithSmartLayout() ```