diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..d42c614 --- /dev/null +++ b/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,13 @@ +### Contents of this Pull Request +This PR makes changes to +- [ ] The typings in the `types` folder +- [ ] Configuration files (`tsconfig.json`, `jsconfig.json`, `.gitignore` etc.) +- [ ] The sample files (e.g., `sample.js`) +- [ ] The `README.md` or other files containing documentation +- [ ] Other + +### Purpose of this Pull Request +\[Description of what this pull request achieves / why it should get merged\] + +### Issues resolved by this Pull Request +- fixes \[issue id\] diff --git a/README.md b/README.md index 080423f..9192bc2 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # typings Typings for Adobe XD API Surfaces -Instructions for using these type defintions to get autocompletion features in editors and IDEs can be found in the [repository's wiki](https://github.com/AdobeXD/typings/wiki/Autocompletion-in-editors-and-IDEs). +Instructions for using these type definitions to get autocompletion features in editors and IDEs can be found in the [repository's wiki](https://github.com/AdobeXD/typings/wiki/Autocompletion-in-editors-and-IDEs). ## Download -The best option to download the typings is to download the latest release from https://github.com/AdobeXD/typings/releases. +The best option to download the typings is to download the latest release from . diff --git a/package.json b/package.json index 1ca9379..a5d7891 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@adobexd/typings", - "version": "19.0.0", + "version": "20.1.0", "typings": "./types/index.d.ts", "description": "Typings for Adobe XD CC", "repository": { @@ -27,6 +27,11 @@ "email": "xdplugins@pabloklaschka.de", "url": "https://github.com/pklaschka" }, + { + "name": "Eric Robinson", + "email": "eric@sonicbloom.io", + "url": "https://github.com/ericdrobinson" + }, { "name": "Kerri Shotts", "email": "kerrishotts@gmail.com", diff --git a/sample.js b/sample.js index cc9c5db..e14122c 100644 --- a/sample.js +++ b/sample.js @@ -2,19 +2,20 @@ const {Text, Ellipse, Color, RootNode} = require("scenegraph"); const clipboard = require("clipboard"); const shell = require("uxp").shell; const fs = require("uxp").storage.localFileSystem; +const assets = require('assets'); /** * @param {Selection} selection * @param {RootNode} documentRoot */ async function test(selection, documentRoot) { - selection.items.forEach(node => { + selection.items.forEach(async node => { console.log("Hello world: ", node); if (node instanceof Text) { clipboard.copyText(node.text); } else if (node instanceof Ellipse) { node.fill = new Color("#ffaaee"); - shell.openExternal('https://adobe-xd.gitbook.io/plugin-api-reference/uxp-api-reference/network-apis/shell'); + await shell.openExternal('https://adobe-xd.gitbook.io/plugin-api-reference/uxp-api-reference/network-apis/shell'); } }); const tempFolder = await fs.getTemporaryFolder(); @@ -28,6 +29,9 @@ async function test(selection, documentRoot) { } else if (anotherFile.isFolder) { console.log("That's a folder. It shouldn't be a folder. What have you done?") } + + const colors = assets.colors.get(); + console.log(colors); } module.exports = { diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..15b8f68 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "strict": true, + "target": "es2015", + "baseUrl": "./", + "lib": [ + "es2015", + "dom" + ], + "paths": { + "*": [ + "types/*" + ] + } + } +} diff --git a/types/application.d.ts b/types/application.d.ts index c5ceb24..ccc050f 100644 --- a/types/application.d.ts +++ b/types/application.d.ts @@ -1,4 +1,4 @@ -import {Color, SceneNode} from "./scenegraph"; +import {Color, SceneNode} from "scenegraph"; /** * All rendition settings fields are required (for a given rendition type) unless otherwise specified. @@ -49,34 +49,26 @@ type RenditionResult = { } /** - * The application module exposes useful information about XD's state, along with APIs for exporting content. + * Generate renditions of nodes in the document in a batch. Overwrites any existing files without warning. + * + * A single createRenditions() call can generate any number of renditions, including multiple renditions of the same node (with different output settings) or renditions of multiple different nodes. Only one createRenditions() call can be executing at any given time, so wait for the Promise it returns before calling it again. + * + * @param renditions List of renditions to generate + * @return Promise, string> - Promise which is fulfilled with an array of RenditionResults (pointing to the same outputFiles that were originally passed in, or rejected with an error string if one or more renditions failed for any reason. */ -declare class application { +export function createRenditions(renditions: RenditionSettings[]): Promise; - /** - * Generate renditions of nodes in the document in a batch. Overwrites any existing files without warning. - * - * A single createRenditions() call can generate any number of renditions, including multiple renditions of the same node (with different output settings) or renditions of multiple different nodes. Only one createRenditions() call can be executing at any given time, so wait for the Promise it returns before calling it again. - * - * @param renditions List of renditions to generate - * @return Promise, string> - Promise which is fulfilled with an array of RenditionResults (pointing to the same outputFiles that were originally passed in, or rejected with an error string if one or more renditions failed for any reason. - */ - static createRenditions(renditions: RenditionSettings[]): Promise; - - /** - * Adobe XD version number in the form "major.minor.patch.build" - */ - static readonly version: string; - - /** - * Current language the application UI is using. This may not equal the user's OS locale setting: it is the closest locale supported by XD - use this when you want your plugin's UI to be consistent with XD's UI. Specifies language only, with no region info (e.g. "fr", not "fr_FR"). - */ - static readonly appLanguage: string; +/** + * Adobe XD version number in the form "major.minor.patch.build" + */ +export const version: string; - /** - * User's OS-wide locale setting. May not match the XD UI, since XD does not support all world languages. Includes both language and region (e.g. "fr_CA" or "en_US"). - */ - static readonly systemLocale: string; -} +/** + * Current language the application UI is using. This may not equal the user's OS locale setting: it is the closest locale supported by XD - use this when you want your plugin's UI to be consistent with XD's UI. Specifies language only, with no region info (e.g. "fr", not "fr_FR"). + */ +export const appLanguage: string; -export = application; +/** + * User's OS-wide locale setting. May not match the XD UI, since XD does not support all world languages. Includes both language and region (e.g. "fr_CA" or "en_US"). + */ +export const systemLocale: string; diff --git a/types/assets.d.ts b/types/assets.d.ts index f24574b..f426006 100644 --- a/types/assets.d.ts +++ b/types/assets.d.ts @@ -1,192 +1,193 @@ import {Color, LinearGradientFill, RadialGradientFill} from "./scenegraph"; /** - * Represents the document styles listed in the Assets panel. Styles can be added and removed manually by the user, so there's no guarantee that these styles are currently used anywhere in the document's content. - * **Since: ** XD 15 + * Type of gradient color element: linear gradient or radial gradient */ -declare module assets { +export enum GradientType { + LINEAR, + RADIAL +} + +/** + * Assets library entry representing a solid color. + */ +type ColorAsset = { /** - * Type of gradient color element: linear gradient or radial gradient + * Name of the Assets entry, if it is explicitly named. (The UI shows an auto-generated label for any unnamed assets). */ - export enum GradientType { - LINEAR, - RADIAL - } + name?: string; /** - * Assets library entry representing a solid color. + * Color of the asset */ - type ColorAsset = { - /** - * Name of the Assets entry, if it is explicitly named. (The UI shows an auto-generated label for any unnamed assets). - */ - name?: string; + color: Color; +} - /** - * Color of the asset - */ - color: Color; - } +/** + * Assets library entry representing a linear or radial gradient. + */ +type GradientAsset = { + /** + * Name of the Assets entry, if it is explicitly named. (The UI shows an auto-generated label for any unnamed assets). + */ + name?: string; + /** + * Either `GradientType.LINEAR` or `GradientType.RADIAL` + */ + gradientType: GradientType; + /** + * Array of color stops used in the gradient, where stop >= 0 and <= 1, and the values are strictly increasing. Same format as the colorStops property of a LinearGradientFill object. + */ + colorStops: Array<{ stop: number, color: Color }> +} +/** + * Assets library entry representing a set of text character styles. + */ +type CharacterStyleAsset = { + /** + * Name of the Assets entry, if it is explicitly named. (The UI shows an auto-generated label for any unnamed assets). + */ + name?: string; /** - * Assets library entry representing a linear or radial gradient. - */ - type GradientAsset = { - /** - * Name of the Assets entry, if it is explicitly named. (The UI shows an auto-generated label for any unnamed assets). - */ - name?: string; - /** - * Either `GradientType.LINEAR` or `GradientType.RADIAL` - */ - gradientType: GradientType; - /** - * Array of color stops used in the gradient, where stop >= 0 and <= 1, and the values are strictly increasing. Same format as the colorStops property of a LinearGradientFill object. - */ - colorStops: Array<{ stop: number, color: Color }> - } + * Object containing the style properties + */ + style: CharacterStyle; +} +/** + * Character style properties. See documentation for the Text node type for more details. + * + * When creating a new character style, all properties are mandatory except those with default values specified here. When deleting + an existing character style, always pass the exact object returned by [`characterStyles.get()`](#module_assets-characterStyles-get) (with all properties fully + specified) to avoid any ambiguity. + */ +type CharacterStyle = { + /** + * the font family + */ + fontFamily: string; + /** + * the style of the font + */ + fontStyle: string; + /** + * the size of the font + */ + fontSize: number; /** - * Assets library entry representing a set of text character styles. - */ - type CharacterStyleAsset = { - /** - * Name of the Assets entry, if it is explicitly named. (The UI shows an auto-generated label for any unnamed assets). - */ - name?: string; - /** - * Object containing the style properties - */ - style: CharacterStyle; - } + * the Color of the font fill + */ + fill: Color; + /** + * the character spacing + */ + charSpacing: number; + /** + * the line spacing + */ + lineSpacing: number; + /** + * whether underline is turned on + */ + underline: boolean; + /** + * (**Since**: XD 19) + * Default `false`; whether strikethrough is turned on + */ + strikethrough?: boolean; + /** + * (**Since**: XD 19) + * Default "none"; one of "none", "uppercase", "lowercase", or "titlecase" + */ + textTransform?: 'none' | 'uppercase' | 'lowercase' | 'titlecase'; + /** + * (**Since**: XD 20) + * Default "none"; one of "none", "superscript", or "subscript" + */ + textScript?: 'none' | 'superscript' | 'subscript'; +} +/** + * The collection of colors and gradients saved in this document's Asset library + */ +interface colors { /** - * Character style properties. See documentation for the Text node type for more details. + * Get a list of all color/gradient assets, in the order they appear in the Assets panel. + * + * The list may contain a mix of solid Color assets and/or gradient assets. If there are no color/gradient assets, an empty array is returned. + * + * @example + * var assets = require("assets"), + * allColors = assets.colors.get(); * - * When creating a new character style, all properties are mandatory except those with default values specified here. When deleting - an existing character style, always pass the exact object returned by [`characterStyles.get()`](#module_assets-characterStyles-get) (with all properties fully - specified) to avoid any ambiguity. - */ - type CharacterStyle = { - /** - * the font family - */ - fontFamily: string; - /** - * the style of the font - */ - fontStyle: string; - /** - * the size of the font - */ - fontSize: number; - /** - * the Color of the font fill - */ - fill: Color; - /** - * the character spacing - */ - charSpacing: number; - /** - * the line spacing - */ - lineSpacing: number; - /** - * whether underline is turned on - */ - underline: boolean; - /** - * (**Since**: XD 19) - * Default `false`; whether strikethrough is turned on - */ - strikethrough?: boolean; - /** - * (**Since**: XD 19) - * Default "none"; one of "none", "uppercase", "lowercase", or "titlecase" - */ - textTransform?: 'none' | 'uppercase' | 'lowercase' | 'titlecase'; - /** - * (**Since**: XD 20) - * Default "none"; one of "none", "superscript", or "subscript" - */ - textScript?: 'none' | 'superscript' | 'subscript'; - } + */ + get(): Array; /** - * The collection of colors and gradients saved in this document's Asset library - */ - declare static class colors { - /** - * Get a list of all color/gradient assets, in the order they appear in the Assets panel. - * - * The list may contain a mix of solid Color assets and/or gradient assets. If there are no color/gradient assets, an empty array is returned. - * - * @example - * var assets = require("assets"), - * allColors = assets.colors.get(); - * - */ - static get(): Array; - - /** - * Add color/gradient assets to the collection. - * - * The list may contain a mix of solid Color assets and/or gradient assets. Items are not added if a duplicate color/gradient already exists in the collection, *regardless of its name*. - * @param colorAssets The color assets - * @returns {number} number of assets added (may be less than requested if duplicates already exist) - */ - static add(colorAssets: Color | ColorAsset | LinearGradientFill | RadialGradientFill | GradientAsset | Array): number; + * Add color/gradient assets to the collection. + * + * The list may contain a mix of solid Color assets and/or gradient assets. Items are not added if a duplicate color/gradient already exists in the collection, *regardless of its name*. + * @param colorAssets The color assets + * @returns {number} number of assets added (may be less than requested if duplicates already exist) + */ + add(colorAssets: Color | ColorAsset | LinearGradientFill | RadialGradientFill | GradientAsset | Array): number; - /** - * Delete color/gradient assets from the collection. - * - * The list may contain a mix of solid Color assets and/or gradient assets. Assets with the same color/gradient are removed even if their names differ. Assets that already don't exist in the collection are silently ignored. Typically you will pass asset objects returned from `get()` directly to this function. - * - * @param colorAssets The color assets - * @returns {number} number of assets deleted (may be less than requested if some didn't exist) - */ - static delete(colorAssets: Color | ColorAsset | LinearGradientFill | RadialGradientFill | GradientAsset | Array): number; - } + /** + * Delete color/gradient assets from the collection. + * + * The list may contain a mix of solid Color assets and/or gradient assets. Assets with the same color/gradient are removed even if their names differ. Assets that already don't exist in the collection are silently ignored. Typically you will pass asset objects returned from `get()` directly to this function. + * + * @param colorAssets The color assets + * @returns {number} number of assets deleted (may be less than requested if some didn't exist) + */ + delete(colorAssets: Color | ColorAsset | LinearGradientFill | RadialGradientFill | GradientAsset | Array): number; +} +/** + * The collection of character styles saved in this document's Assets library. + */ +interface characterStyles { /** - * The collection of character styles saved in this document's Assets library. - */ - declare static class characterStyles { - /** - * Get a list of all character style assets, in the order they appear in the Assets panel. - * - * If there are no character style assets, an empty array is returned. - * - * @example - * var assets = require("assets"), - * allCharacterStyles = assets.characterStyles.get(); - * - */ - static get(): Array; + * Get a list of all character style assets, in the order they appear in the Assets panel. + * + * If there are no character style assets, an empty array is returned. + * + * @example + * var assets = require("assets"), + * allCharacterStyles = assets.characterStyles.get(); + * + */ + get(): Array; - /** - * Add one or more character style assets to the collection. - * - * Items are not added if a duplicate character style already exists in the collection, regardless of its name. All character style properties must be fully specified (no properties are optional). - * - * @param charStyleAssets The character style assets - * @returns {number} number of assets added (may be less than requested if duplicates already exist) - */ - static add(charStyleAssets: CharacterStyleAsset | Array): number; + /** + * Add one or more character style assets to the collection. + * + * Items are not added if a duplicate character style already exists in the collection, regardless of its name. All character style properties must be fully specified (no properties are optional). + * + * @param charStyleAssets The character style assets + * @returns {number} number of assets added (may be less than requested if duplicates already exist) + */ + add(charStyleAssets: CharacterStyleAsset | Array): number; - /** - * Delete one or more character style assets from the collection. - * - * Assets with the same character style are removed *even if their names differ*. Assets that already don't exist in the - * collection are silently ignored. All character style properties must be fully specified (no properties are optional). - * To avoid ambiguity, pass the exact asset objects returned from [`get()`](#module_assets-characterStyles-get) directlyto this function. - * - * @returns {number} number of assets deleted (may be less than requested if some didn't exist) - * @param charStyleAssets The character styles - */ - static delete(charStyleAssets: CharacterStyleAsset | Array): number; - } + /** + * Delete one or more character style assets from the collection. + * + * Assets with the same character style are removed *even if their names differ*. Assets that already don't exist in the + * collection are silently ignored. All character style properties must be fully specified (no properties are optional). + * To avoid ambiguity, pass the exact asset objects returned from [`get()`](#module_assets-characterStyles-get) directlyto this function. + * + * @returns {number} number of assets deleted (may be less than requested if some didn't exist) + * @param charStyleAssets The character styles + */ + delete(charStyleAssets: CharacterStyleAsset | Array): number; } -export = assets; +/** + * The collection of colors and gradients saved in this document's Asset library + */ +export const colors: colors; +/** + * The collection of character styles saved in this document's Assets library. + */ +export const characterStyles: characterStyles; diff --git a/types/clipboard.d.ts b/types/clipboard.d.ts index 01a9fcf..d9425e6 100644 --- a/types/clipboard.d.ts +++ b/types/clipboard.d.ts @@ -1,12 +1,5 @@ /** - * This module lets you copy text to the clipboard. It is not yet possible to copy other content types, or to handle paste events. + * Write plain text to the clipboard. + * @param text Will be automatically converted to string if a different type is passed */ -declare class clipboard { - /** - * Write plain text to the clipboard. - * @param text Will be automatically converted to string if a different type is passed - */ - static copyText(text: string | any): void; -} - -export = clipboard; +export function copyText(text: string | any): void; diff --git a/types/cloud.d.ts b/types/cloud.d.ts index bf88adf..bc942a7 100644 --- a/types/cloud.d.ts +++ b/types/cloud.d.ts @@ -1,107 +1,87 @@ -declare namespace cloud { +interface BaseSharedArtifact { + type: ArtifactType; /** - * Interactive prototype view generated via "Share for Review." + * URL to view in browser */ - type PrototypeArtifact = { - /** - * Set to ArtifactType.PROTOTYPE - */ - type: ArtifactType.PROTOTYPE, - /** - * URL to view in browser - */ - url: string, - /** - * Name of shared artifact (often, but not always, matches the document name) - */ - name: string, - /** - * Level of access protection - */ - accessLevel: AccessLevel, - /** - * True if stakeholders can post comments on this artifact - */ - allowComments: boolean, - /** - * URL for embedding a view of the prototype inside an iframe (compact view with minimal surrounding UI) - */ - embedURL: string, - /** - * iframe width needed to display embedURL. May include room for navigation UI in addition to the prototype's content itself. - */ - embedWidth: number, - /** - * iframe height needed to display embedURL. May include room for navigation UI in addition to the prototype's content itself. - */ - embedHeight: number, - /** - * True if prototype defaults to a view that fills the entire page, with no surrounding UI visible for navigation, commenting, etc. - */ - fullscreenInPage: boolean, - /** - * True if clicking in non-interactive parts of the prototype flashes visual hints indicating the interactive spots - */ - hotspotHints: boolean - } - + url: string; /** - * Developer-oriented specs view generated via "Share for Development." + * Name of shared artifact (often, but not always, matches the document name) */ - type SpecsArtifact = { - type: ArtifactType.SPECS, - /** - * URL to view in browser - */ - url: string, - /** - * Name of shared artifact (often, but not always, matches the document name) - */ - name: string, - /** - * Level of access protection - */ - accessLevel: AccessLevel, - /** - * True if stakeholders can post comments on this artifact - */ - allowComments: boolean, - /** - * Target platform. Determines which information and measurement units are shown by default. - */ - targetPlatform: TargetPlatform - } - + name: string; /** - * Type of shared artifact: interactive prototype or developer-focused specs view + * Level of access protection */ - export enum ArtifactType { - PROTOTYPE, - SPECS - } - + accessLevel: AccessLevel; /** - * Target platform for published design specs + * True if stakeholders can post comments on this artifact */ - export enum TargetPlatform { - WEB, IOS, ANDROID - } + allowComments: boolean; +} +interface PrototypeArtifact extends BaseSharedArtifact { + type: ArtifactType.PROTOTYPE; + /** + * URL for embedding a view of the prototype inside an iframe (compact view with minimal surrounding UI) + */ + embedURL: string; + /** + * iframe width needed to display embedURL. May include room for navigation UI in addition to the prototype's content itself. + */ + embedWidth: number; + /** + * iframe height needed to display embedURL. May include room for navigation UI in addition to the prototype's content itself. + */ + embedHeight: number; /** - * Access level of the shared link: accessible to anyone with the link, anyone with the link + password, or only specific Creative Cloud user accounts + * True if prototype defaults to a view that fills the entire page, with no surrounding UI visible for navigation, commenting, etc. */ - export enum AccessLevel { - LINKABLE, PASSWORD_PROTECTED, INVITE_ONLY - } + fullscreenInPage: boolean; + /** + * True if clicking in non-interactive parts of the prototype flashes visual hints indicating the interactive spots + */ + hotspotHints: boolean; +} +interface SpecsArtifact extends BaseSharedArtifact { + type: ArtifactType.SPECS; /** - * Get a list of recently shared artifacts generated from this document. Older artifacts may not be included even if the shared links are still live. Shared links that have been deleted from the server (File > Manage Published Links) may still be listed here, as this API only provides a record of recent share actions from XD - not what the links' current status on the server may be. - * - * The list may contain a mix of PrototypeArtifact and/or SpecsArtifact, and items are listed in no particular order. If nothing has been shared from this document, an empty array is returned. - * - * @return {!Array} + * Target platform. Determines which information and measurement units are shown by default. */ - function getSharedArtifacts(): Array; + targetPlatform: TargetPlatform +} + +/** + * Type of shared artifact: interactive prototype or developer-focused specs view + */ +export enum ArtifactType { + PROTOTYPE = 'prototype', + SPECS = 'specs' +} + +/** + * Target platform for published design specs + */ +export enum TargetPlatform { + WEB = 'Web', + IOS = 'iOS', + ANDROID = 'Android' +} + + +/** + * Access level of the shared link: accessible to anyone with the link, anyone with the link + password, or only specific Creative Cloud user accounts + */ +export enum AccessLevel { + LINKABLE = 'linkable', + PASSWORD_PROTECTED = 'passwordProtected', + INVITE_ONLY = 'inviteOnly' } -export = cloud; \ No newline at end of file +/** + * Get a list of recently shared artifacts generated from this document. Older artifacts may not be included even if the shared links are still live. Shared links that have been deleted from the server (File > Manage Published Links) may still be listed here, as this API only provides a record of recent share actions from XD - not what the links' current status on the server may be. + * + * The list may contain a mix of PrototypeArtifact and/or SpecsArtifact, and items are listed in no particular order. If nothing has been shared from this document, an empty array is returned. + * + * @return {!Array} + */ +export function getSharedArtifacts(): Array; diff --git a/types/commands.d.ts b/types/commands.d.ts index e813a82..85d4281 100644 --- a/types/commands.d.ts +++ b/types/commands.d.ts @@ -1,112 +1,105 @@ /** - * You can make structural changes to the scenegraph, and perform other complex operations, by programmatically invoking the same commands as XD users have access to in the UI. These methods do not take arguments. Instead, set the selection to the objects you want the command to target, then invoke the command: - */ -declare class commands { - /** - * Wraps the selected objects in a Group, leaving the Group selected afterward. Equivalent to Object > Group in the UI. - */ - static group(): void; - - /** - * Ungroups any of the selected objects that are ungroupable containers (Group, SymbolInstance, RepeatGrid, etc.). Equivalent to _Object > Ungroup_. - */ - static ungroup(): void; - - /** - * Creates a masked Group from the selected objects, using the object that is highest in the z order as the mask shape. The mask shape must be a leaf node or Boolean Group. Equivalent to Object > Mask With Shape. - */ - static createMaskGroup(): void; - - /** - * Converts each selected object to a Path with the exact same visual appearance. Only applies to leaf nodes and Boolean Groups. Equivalent to Object > Path > Convert to Path. - */ - static convertToPath(): void; - - /** - * Duplicates all selected objects, leaving the duplicates selected afterward. - * - * - If the objects are artboards, the duplicates are positioned to not overlap any more artboards, and are placed at the top of the artboard z order. - * - If normal objects, each duplicate is in the exact same position as the original, and just above it in the z order (duplicates of a multiple selection will not be contiguous in the z order if the originals were not). - * - * Edit > Duplicate - */ - static duplicate(): void; - - /** - * Brings selected objects to the front of the z order. Equivalent to Object > Arrange > Bring to Front. - */ - static bringToFront(): void; - - /** - * Brings each selected object one step closer to the front of the z order. Equivalent to Object > Arrange > Bring Forward. - */ - static bringForward(): void; - - /** - * Sends selected objects to the back of the z order. Equivalent to Object > Arrange > Send to Back. - */ - static sendToBack(): void; - - /** - * Sends each selected object one step closer to the back of the z order. Equivalent to Object > Arrange > Send Backward. - */ - static sendBackward(): void; - - /** - * Aligns all selected objects flush left. Equivalent to Object > Align > Left. - */ - static alignLeft(): void; - - /** - * Aligns all selected objects flush right. Equivalent to Object > Align > Right. - */ - static alignRight(): void; - - /** - * Aligns all selected objects along their horizontal centerlines. Equivalent to Object > Align > Center (Horizontally). - */ - static alignHorizontalCenter(): void; - - /** - * Aligns all selected objects flush top. Equivalent to Object > Align > Top. - */ - static alignTop(): void; - - /** - * Aligns all selected objects flush bottom. Equivalent to Object > Align > Bottom. - */ - static alignBottom(): void; - - /** - * Aligns all selected objects along their vertical centerlines. Equivalent to Object > Align > Center (Vertically). - */ - static alignVerticalCenter(): void; - - /** - * Distributes all selected objects evenly along the X axis. Equivalent to Object > Distribute > Horizontally. - */ - static distributeHorizontal(): void; - - /** - * Distributes all selected objects evenly along the Y axis. Equivalent to Object > Distribute > Vertically. - */ - static distributeVertical(): void; - - /** - * Shifts all selected objects and their content so they align crisply with the pixel grid. Equivalent to Object > Align to Pixel Grid. - */ - static alignToPixelGrid(): void; - - - // /** - //* Flips the object horizontally. Some objects such as Symbols cannot be flipped. Equivalent to Object > Flip > Horizontally. - //*/ - //static filpHorizontal(): void; -// - // /** - // * Flips the object vertically. Some objects such as Symbols cannot be flipped. Equivalent to Object > Flip > Vertically. - //*/ - //static flipVertical(): void; -} + * Wraps the selected objects in a Group, leaving the Group selected afterward. Equivalent to Object > Group in the UI. + */ +export function group(): void; + +/** + * Ungroups any of the selected objects that are ungroupable containers (Group, SymbolInstance, RepeatGrid, etc.). Equivalent to _Object > Ungroup_. + */ +export function ungroup(): void; + +/** + * Creates a masked Group from the selected objects, using the object that is highest in the z order as the mask shape. The mask shape must be a leaf node or Boolean Group. Equivalent to Object > Mask With Shape. + */ +export function createMaskGroup(): void; + +/** + * Converts each selected object to a Path with the exact same visual appearance. Only applies to leaf nodes and Boolean Groups. Equivalent to Object > Path > Convert to Path. + */ +export function convertToPath(): void; + +/** + * Duplicates all selected objects, leaving the duplicates selected afterward. + * + * - If the objects are artboards, the duplicates are positioned to not overlap any more artboards, and are placed at the top of the artboard z order. + * - If normal objects, each duplicate is in the exact same position as the original, and just above it in the z order (duplicates of a multiple selection will not be contiguous in the z order if the originals were not). + * + * Edit > Duplicate + */ +export function duplicate(): void; -export = commands; +/** + * Brings selected objects to the front of the z order. Equivalent to Object > Arrange > Bring to Front. + */ +export function bringToFront(): void; + +/** + * Brings each selected object one step closer to the front of the z order. Equivalent to Object > Arrange > Bring Forward. + */ +export function bringForward(): void; + +/** + * Sends selected objects to the back of the z order. Equivalent to Object > Arrange > Send to Back. + */ +export function sendToBack(): void; + +/** + * Sends each selected object one step closer to the back of the z order. Equivalent to Object > Arrange > Send Backward. + */ +export function sendBackward(): void; + +/** + * Aligns all selected objects flush left. Equivalent to Object > Align > Left. + */ +export function alignLeft(): void; + +/** + * Aligns all selected objects flush right. Equivalent to Object > Align > Right. + */ +export function alignRight(): void; + +/** + * Aligns all selected objects along their horizontal centerlines. Equivalent to Object > Align > Center (Horizontally). + */ +export function alignHorizontalCenter(): void; + +/** + * Aligns all selected objects flush top. Equivalent to Object > Align > Top. + */ +export function alignTop(): void; + +/** + * Aligns all selected objects flush bottom. Equivalent to Object > Align > Bottom. + */ +export function alignBottom(): void; + +/** + * Aligns all selected objects along their vertical centerlines. Equivalent to Object > Align > Center (Vertically). + */ +export function alignVerticalCenter(): void; + +/** + * Distributes all selected objects evenly along the X axis. Equivalent to Object > Distribute > Horizontally. + */ +export function distributeHorizontal(): void; + +/** + * Distributes all selected objects evenly along the Y axis. Equivalent to Object > Distribute > Vertically. + */ +export function distributeVertical(): void; + +/** + * Shifts all selected objects and their content so they align crisply with the pixel grid. Equivalent to Object > Align to Pixel Grid. + */ +export function alignToPixelGrid(): void; + + +// /** +//* Flips the object horizontally. Some objects such as Symbols cannot be flipped. Equivalent to Object > Flip > Horizontally. +//*/ +//function filpHorizontal(): void; +// +// /** +// * Flips the object vertically. Some objects such as Symbols cannot be flipped. Equivalent to Object > Flip > Vertically. +//*/ +//function flipVertical(): void; diff --git a/types/index.d.ts b/types/index.d.ts index 611c68b..2d9e97a 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -1,6 +1,4 @@ -import {Artboard, SceneNode} from "scenegraph"; - -export {}; +import {Artboard, SceneNode} from "./scenegraph"; declare global { /** @@ -11,41 +9,6 @@ declare global { let module: {exports:any}; - /** - * Represents the children of a scenenode. Typically accessed via the SceneNode.children property. - */ - class SceneNodeList { - items: SceneNode[]; - readonly length: number; - - forEach( - callback: (sceneNode: SceneNode, index: number) => void, - thisArg?: object - ): void; - - forEachRight( - callback: (sceneNode: SceneNode, index: number) => void, - thisArg?: object - ): void; - - filter( - callback: (sceneNode: SceneNode, index: number) => boolean, - thisArg?: object - ): Array; - - map( - callback: (sceneNode: SceneNode, index: number) => any, - thisArg?: object - ): Array; - - some( - callback: (sceneNode: SceneNode, index: number) => boolean, - thisArg?: object - ): boolean; - - at(index: number): SceneNode | null; - } - /** * The selection object represents the currently selected set of nodes in the UI. You can set the selection to use it as input for commands, or to determine what is left selected for the user when your plugin’s edit operation completes. * @@ -95,17 +58,5 @@ declare global { * The artboard the user is currently most focused on (via recent selection or edit operations). May be null, for example if no artboards exist or if the user just deleted an artboard. */ focusedArtboard: Artboard | null | undefined; - - } - - /** - * To get an instance: `require("uxp").shell` - */ - class Shell { - /** - * Opens the url in an the system browser. - * @param url The url which should be opened - */ - openExternal(url: string); } } diff --git a/types/interactions.d.ts b/types/interactions.d.ts index c2c665e..724672c 100644 --- a/types/interactions.d.ts +++ b/types/interactions.d.ts @@ -1,47 +1,19 @@ -import {Artboard, SceneNode} from "./scenegraph"; +import {Artboard, SceneNode} from "scenegraph"; /** - * The `interactions` module and related APIs provide _read only_ information about the document's interactive prototype mode, including: - * - * * The blue "wires" seen in XD's prototyping UI, known as "interactions," which specify gestures/events which trigger actions to - occur in the prototype. Accessible as a single consolidated global listing via this module's [`allInteractions`](#module_interactions-allInteractions) API, - or you can access information from specific nodes in the scenegraph via [`SceneNode.triggeredInteractions`](./scenegraph.md#SceneNode-triggeredInteractions) - and [`Artboard.incomingInteractions`](./scenegraph.md#Artboard-incomingInteractions). - * * Which artboard the prototype experience begins on: [`homeArtboard`](#module_interactions-homeArtboard). - * * Properties that affect Artboard scrolling behavior: Artboard [`viewportHeight`](./scenegraph.md#Artboard-viewportHeight) and - node [`fixedWhenScrolling`](./scenegraph.md#SceneNode-fixedWhenScrolling). + * The starting Artboard seen when the interactive prototype is launched. + * @see Artboard.isHomeArtboard + */ +export const homeArtboard: Artboard | null; + +/** + * Returns a collection of *all* interactions across the entire document, grouped by triggering scenenode. Each entry in this array specifies a `triggerNode` and the result of getting [`triggerNode.triggeredInteractions`](./scenegraph.md#SceneNode-triggeredInteractions). * - * **Since**: XD 19 + * May include interactions that are impossible to trigger because the trigger node (or one of its ancestors) has `visible` = false. * - * @example ```javascript - * // Get all interactions in the entire document (grouped by triggering node) - var allInteractions = require("interactions").allInteractions; - // Get interactions triggered by the selected node - var nodeInteractions = selection.items[0].triggeredInteractions; - // Get all interactions leading to a particular artboard - var artboard = ... - var interactionsToArtboard = artboard.incomingInteractions; - // Print out details of one particular interaction - var interaction = ... - console.log("Trigger: " + interaction.trigger.type + " -> Action: " + interaction.action.type); - ``` + * Note: currently, this API excludes all of the document's keyboard/gamepad interactions. */ -declare class interactions { - /** - * The starting Artboard seen when the interactive prototype is launched. - * @see Artboard.isHomeArtboard - */ - static readonly homeArtboard?: Artboard; - - /** - * Returns a collection of *all* interactions across the entire document, grouped by triggering scenenode. Each entry in this array specifies a `triggerNode` and the result of getting [`triggerNode.triggeredInteractions`](./scenegraph.md#SceneNode-triggeredInteractions). - * - * May include interactions that are impossible to trigger because the trigger node (or one of its ancestors) has `visible` = false. - * - * Note: currently, this API excludes all of the document's keyboard/gamepad interactions. - */ - static readonly allInteractions: Array<{ triggerNode: SceneNode, interactions: Array }>; -} +export const allInteractions: Array<{ triggerNode: SceneNode, interactions: Array }>; /** * An interaction consists of a Trigger + Action pair and is attached to a single, specific scenenode. @@ -201,5 +173,3 @@ type Action = { */ voice?: string; } - -export = interactions; diff --git a/types/scenegraph.d.ts b/types/scenegraph.d.ts index e5042b7..4e1b4d0 100644 --- a/types/scenegraph.d.ts +++ b/types/scenegraph.d.ts @@ -1,14 +1,51 @@ +import {Interaction} from 'interactions'; + declare interface Point { x: number; y: number; } -interface ScaleFactor { +declare interface ScaleFactor { scaleX: number; scaleY: number; } -declare class Matrix { +/** + * Represents the children of a scenenode. Typically accessed via the SceneNode.children property. + */ +declare interface SceneNodeList { + items: SceneNode[]; + readonly length: number; + + forEach( + callback: (sceneNode: SceneNode, index: number) => void, + thisArg?: object + ): void; + + forEachRight( + callback: (sceneNode: SceneNode, index: number) => void, + thisArg?: object + ): void; + + filter( + callback: (sceneNode: SceneNode, index: number) => boolean, + thisArg?: object + ): Array; + + map( + callback: (sceneNode: SceneNode, index: number) => any, + thisArg?: object + ): Array; + + some( + callback: (sceneNode: SceneNode, index: number) => boolean, + thisArg?: object + ): boolean; + + at(index: number): SceneNode | null; +} + +export class Matrix { /** * Creates a new transform matrix with the following structure: * @@ -35,7 +72,7 @@ declare class Matrix { * Copies another matrix's values into this matrix. * @param otherMatrix The matrix to copy values from. */ - setFrom(otherMatrix: Matrix); + setFrom(otherMatrix: Matrix): void; /** * Returns a copy of the matrix @@ -51,13 +88,13 @@ declare class Matrix { * @param e The e component of an affine transform. * @param f The f component of an affine transform. */ - add(aOrOtherMatrix: number, b: number, c: number, d: number, e: number, f: number); + add(aOrOtherMatrix: number, b: number, c: number, d: number, e: number, f: number): void; /** * Multiplies a passed affine transform to the right: this * M. The result effectively applies the transform of the passed in matrix first, followed by the transform of this matrix second. Modifies this matrix object and also returns it so calls can be chained. * @param aOrOtherMatrix A Matrix or the a component of an affine transform. */ - add(aOrOtherMatrix: Matrix); + add(aOrOtherMatrix: Matrix): void; /** * Multiplies a passed affine transform to the left: M * this. The result effectively applies the transform of this matrix first, followed by the transform of the passed in matrix second. Modifies this matrix object and also returns it so calls can be chained. @@ -68,13 +105,13 @@ declare class Matrix { * @param e The e component of an affine transform. * @param f The f component of an affine transform. */ - multLeft(aOrOtherMatrix: number, b: number, c: number, d: number, e: number, f: number); + multLeft(aOrOtherMatrix: number, b: number, c: number, d: number, e: number, f: number): void; /** * Multiplies a passed affine transform to the left: M * this. The result effectively applies the transform of this matrix first, followed by the transform of the passed in matrix second. Modifies this matrix object and also returns it so calls can be chained. * @param aOrOtherMatrix A Matrix or the a component of an affine transform. */ - multLeft(aOrOtherMatrix: Matrix); + multLeft(aOrOtherMatrix: Matrix): void; /** * Returns an inverted version of the matrix. Returns a brand new matrix - does not modify this matrix object. @@ -158,7 +195,7 @@ declare class Matrix { hasSkew(): boolean; } -declare class Color { +export class Color { /** * Integer 0-255. Get/set the alpha channel value. */ @@ -203,11 +240,11 @@ declare class Color { clone(): Color; } -declare class LinearGradientFill { +export class LinearGradientFill { /** * Array of objects representing each color and its position along the gradient line. The position (stop value) is a number 0.0 - 1.0. */ - colorStops: {color:Color,stop:number}[]; + colorStops: { color: Color, stop: number }[]; /** * X position of the start of the gradient line, as a multiple of the object's bounding box: X=0 indicates the left edge of the bounding box and X=1 indicates the right edge. The gradient line may start or end outside the object's bounding box, so values may be < 0 or > 1. @@ -251,17 +288,17 @@ declare class LinearGradientFill { * @param endX * @param endY */ - setEndPoints(startX: number, startY: number, endX: number, endY: number); + setEndPoints(startX: number, startY: number, endX: number, endY: number): void; } /** * **The RadialGradientFill type is not documented and its API may change. Plugins currently cannot modify or otherwise work with radial gradients.** */ -declare class RadialGradientFill { +export class RadialGradientFill { // TODO: Waiting for documentation to arrive } -declare class ImageFill { +export class ImageFill { /** * The image is stretched (distorting its aspect ratio) so its edges line up exactly with the edges of the shape. (Similar to `object-fit: fill` in CSS). */ @@ -315,7 +352,7 @@ declare class ImageFill { } -declare class Shadow { +export class Shadow { /** * X offset of the shadow relative to the shape it is attached to, in global coordinates (i.e. independent of the shape's rotation or any parent's rotation). May be negative. */ @@ -344,7 +381,7 @@ declare class Shadow { constructor(x: number, y: number, blur: number, color: Color, visible: boolean) } -declare class Blur { +export class Blur { /** * The amount of blur * @@ -389,7 +426,7 @@ declare class Blur { constructor(blurAmount: number, brightnessAmount: number, fillOpacity: number, visible?: boolean, isBackgroundEffect?: boolean); } -declare interface Bounds { +export interface Bounds { x: number; y: number; width: number; @@ -399,7 +436,7 @@ declare interface Bounds { /** * Base class of all scenegraph nodes. Nodes will always be an instance of some subclass of SceneNode. */ -declare abstract class SceneNode { +export abstract class SceneNode { /** * Returns a unique identifier for this node that stays the same when the file is closed & reopened, or if the node is moved to a different part of the document. Cut-Paste will result in a new guid, however. */ @@ -524,8 +561,8 @@ declare abstract class SceneNode { * Currently, this API excludes any keyboard/gamepad interactions on this node. * * @example ```javascript - // Print all the interactions triggered by a node - node.triggeredInteractions.forEach(interaction => { + // Print all the interactions triggered by a node + node.triggeredInteractions.forEach(interaction => { console.log("Trigger: " + interaction.trigger.type + " -> Action: " + interaction.action.type); }); * ``` @@ -592,7 +629,7 @@ declare abstract class SceneNode { /** * Base class for nodes that have a stroke and/or fill. This includes leaf nodes such as Rectangle, as well as BooleanGroup which is a container node. If you create a shape node, it will not be visible unless you explicitly give it either a stroke or a fill. */ -declare class GraphicNode extends SceneNode { +export class GraphicNode extends SceneNode { /** * The fill applied to this shape, if any. If this property is null or fillEnabled is false, no fill is drawn. Freshly created nodes have no fill by default. * @@ -695,7 +732,7 @@ declare class GraphicNode extends SceneNode { * * If a node is changed to overlap an Artboard, it will automatically become a child of the artboard when the operation finishes, and similar if a node is changed to no longer overlap an Artboard. It is not possible to have a node overlapping an Artboard that does not become a child of the artboard, or vice versa, a node that falls entirely outside an Artboard’s bounds but remains its child. */ -declare class Artboard extends GraphicNode { +export class Artboard extends GraphicNode { /** * value must be >= 0 */ @@ -727,7 +764,7 @@ declare class Artboard extends GraphicNode { * @see SceneNode.triggeredInteractions * @see interactions.allInteractions */ - readonly incomingInteractions: Array<{triggerNode: SceneNode, interactions: Array}>; + readonly incomingInteractions: Array<{ triggerNode: SceneNode, interactions: Array }>; /** * **Since**: XD 19 @@ -768,7 +805,7 @@ declare class Artboard extends GraphicNode { /** * Rectangle leaf node shape, with or without rounded corners. Like all shape nodes, has no fill or stroke by default unless you set one. */ -declare class Rectangle extends GraphicNode { +export class Rectangle extends GraphicNode { /** * value must be >= 0 */ @@ -816,7 +853,7 @@ declare class Rectangle extends GraphicNode { /** * Ellipse leaf node shape. */ -declare class Ellipse extends GraphicNode { +export class Ellipse extends GraphicNode { radiusX: number; radiusY: number; /** @@ -828,7 +865,7 @@ declare class Ellipse extends GraphicNode { /** * Line leaf node shape. */ -declare class Line extends GraphicNode { +export class Line extends GraphicNode { /** * Start point of the Line in local coordinate space.TEMP: To change the start point, use setStartEnd. */ @@ -858,7 +895,7 @@ declare class Line extends GraphicNode { * * The path may not start at (0,0) in local coordinates, for example if it starts with a move (“M”) */ -declare class Path extends GraphicNode { +export class Path extends GraphicNode { /** * Representation of the path outline in SVG syntax. Unlike other node types, pathData is writable here. Syntax is automatically normalized, so the getter may return a slightly different string than what you passed to the setter. */ @@ -884,7 +921,7 @@ declare class Path extends GraphicNode { selection.items = [polygon]; * ``` */ -declare class Polygon extends GraphicNode { +export class Polygon extends GraphicNode { /** * > 0 */ @@ -907,7 +944,7 @@ declare class Polygon extends GraphicNode { * * To change corner count while guaranteeing the shape will not change size, save its original size first, set `cornerCount`, and then set size back to the saved values. */ - cornerCount: number = 3; + cornerCount: number; /** * True if any of the Polygon's corners is rounded (corner radius > 0). @@ -931,7 +968,7 @@ declare class Polygon extends GraphicNode { * * It is not currently possible for plugins to create a new BooleanGroup node, aside from using commands.duplicate to clone existing BooleanGroups. */ -declare class BooleanGroup extends GraphicNode { +export class BooleanGroup extends GraphicNode { /** * Which boolean operation is used to generate the path: BooleanGroup.PATH_OP_ADD, PATH_OP_SUBTRACT, PATH_OP_INTERSECT, or PATH_OP_EXCLUDE_OVERLAP. */ @@ -975,7 +1012,7 @@ declare class BooleanGroup extends GraphicNode { * * The bounds reported for a Text object leave enough space for descenders, uppercase letters, and accent marks, even if the current string does not contain any of those characters. This makes aligning text based on its bounds behave more consistently. */ -declare class Text extends GraphicNode { +export class Text extends GraphicNode { /** * The plaintext content of the node, including any hard line breaks but excluding soft line wrap breaks. * @@ -1053,7 +1090,7 @@ declare class Text extends GraphicNode { * * Set strikethrough across all style ranges, or get the strikethrough of the last style range (strikethrough of all the text if one range covers all the text). */ - strikethrough: boolean = false; + strikethrough: boolean; /** * @default "none" @@ -1061,7 +1098,7 @@ declare class Text extends GraphicNode { * * Set textTransform ("none", "uppercase", "lowercase", or "titlecase") across all style ranges, or get the textTransform of the last style range. */ - textTransform: 'none' | 'uppercase' | 'lowercase' | 'titlecase' = 'none'; + textTransform: 'none' | 'uppercase' | 'lowercase' | 'titlecase'; /** * @default "none" @@ -1069,7 +1106,7 @@ declare class Text extends GraphicNode { * * Set textScript ("none" or "superscript" or "subscript") across all style ranges, or get the textScript of the last style range. */ - textScript: 'none' | 'superscript' | 'subscript' = 'none'; + textScript: 'none' | 'superscript' | 'subscript'; static readonly ALIGN_LEFT: string; static readonly ALIGN_CENTER: string; @@ -1122,23 +1159,6 @@ declare class Text extends GraphicNode { * Always false for point text. For area text, true if the text does not fit in the content box and its bottom is being clipped. */ readonly clippedByArea: boolean; - - /** - * **Since:** XD 19 - * - * Set strikethrough across all style ranges, or get the strikethrough of the last style range (strikethrough of all the text if one range covers all the text). - * @default false - */ - strikethrough: boolean; - - /** - * **Since:** XD 19 - * - * Set textTransform ("none" or "uppercase" or "lowercase" or "titlecase") across all style ranges, or get the textTransform of the last style range. - * - * @default 'none' - */ - textTransform: 'none' | 'uppercase' | 'lowercase' | 'titlecase'; } /** @@ -1150,7 +1170,7 @@ declare class Text extends GraphicNode { * * In a Mask Group, the mask shape is included in the group’s children list, at the top of the z order. It is not visible - only its path outline is used, for clipping the group. */ -declare class Group extends SceneNode { +export class Group extends SceneNode { /** * The mask shape applied to this group, if any. This object is also present in the group’s children list. Though it has no direct visual appearance of its own, the mask affects the entire groups’s appearance by clipping all its other content. */ @@ -1194,7 +1214,7 @@ declare class Group extends SceneNode { * * It is not currently possible for plugins to *create* a new component definition or a new SymbolInstance node, aside from using {@link commands.duplicate} to clone existing SymbolInstances. */ -declare class SymbolInstance extends SceneNode { +export class SymbolInstance extends SceneNode { /** * An identifier unique within this document that is shared by all instances of the same component. */ @@ -1238,7 +1258,7 @@ declare class SymbolInstance extends SceneNode { * Each grid cell is a Group that is an immediate child of the RepeatGrid. These groups are automatically created and destroyed as needed when the RepeatGrid is resized. * It is not currently possible for plugins to create a new RepeatGrid node, aside from using commands.duplicate to clone existing RepeatGrids. */ -declare class RepeatGrid extends SceneNode { +export class RepeatGrid extends SceneNode { /** * Defines size of the RepeatGrid. Cells are created and destroyed as necessary to fill the current size. Cells that only partially fit will be clipped. */ @@ -1324,13 +1344,13 @@ declare class RepeatGrid extends SceneNode { /** * Container node whose content is linked to an external resource, such as Creative Cloud Libraries. It cannot be edited except by first ungrouping it, breaking this link. */ -declare class LinkedGraphic extends SceneNode { +export class LinkedGraphic extends SceneNode { } /** * Class representing the root node of the document. All Artboards are children of this node, as well as any pasteboard content that does not lie within an Artboard. Artboards must be grouped contiguously at the bottom of this node’s z order. The root node has no visual appearance of its own. */ -declare class RootNode extends SceneNode { +export class RootNode extends SceneNode { /** * Adds a child node to this container node. You can only add leaf nodes this way; to create structured subtrees of content, use commands. * @param {SceneNode} node Child to add @@ -1362,37 +1382,10 @@ declare class RootNode extends SceneNode { * **Since:** XD 14 * Object representing the current selection state and edit context. Also available as the first argument passed to your plugin command handler function. */ -const selection: SceneNodeList; +export const selection: SceneNodeList; /** * **Since:** XD 14 * Root node of the current document's scenegraph. Also available as the second argument passed to your plugin command handler function. */ -const root: RootNode; - -export { - RootNode, - SceneNode, - GraphicNode, - Artboard, - Rectangle, - Ellipse, - Line, - Path, - Polygon, - BooleanGroup, - Text, - Group, - SymbolInstance, - RepeatGrid, - LinkedGraphic, - Color, - ImageFill, - LinearGradientFill, - RadialGradientFill, - Matrix, - Shadow, - Blur, - selection, - root -} +export const root: RootNode; diff --git a/types/uxp.d.ts b/types/uxp.d.ts index 3f9d8c7..25f9db7 100644 --- a/types/uxp.d.ts +++ b/types/uxp.d.ts @@ -1,10 +1,21 @@ -declare const shell: Shell; +/** + * To get an instance: `require("uxp").shell` + */ +interface Shell { + /** + * Opens the url in an the system browser. + * @param url The url which should be opened + */ + openExternal(url: string): Promise; +} -declare module storage { +export const shell: Shell; + +export module storage { /** * An Entry is the base class for `File` and `Folder`. You'll typically never instantiate an `Entry` directly, but it provides the common fields and methods that both `File` and `Folder` share. */ - interface Entry { + interface Entry { /** * Indicates that this instance is an `Entry`. Useful for type-checking. */ @@ -42,24 +53,44 @@ declare module storage { /** * Copies this entry to the specified `folder`. + * + * The Entry object passed to this function will continue to reference the original item - it is not updated to reference the copy. + * * @param folder the folder to which to copy this entry - * @param {object} options additional options - * @param {boolean=false} options.overwrite if `true`, allows overwriting existing entries + * @param options additional options * * @throws errors.EntryExistsError if the attempt would overwrite an entry and `overwrite` is `false` * @throws errors.PermissionDeniedError if the underlying file system rejects the attempt * @throws errors.OutOfSpaceError if the file system is out of storage space */ - copyTo(folder: Folder, options?): Promise; + copyTo(folder: Folder, options?: { + /** + * if `true`, allows overwriting existing entries + * @default false + */ + overwrite?: boolean; + }): Promise; /** * Moves this entry to the target folder, optionally specifying a new name. + * + * The Entry object passed to this function is automatically updated to reference the new location, however any other Entry objects referencing the original item will not be updated, and will thus no longer point to an item that exists on disk. + * * @param folder the folder to which to move this entry - * @param {object} options - * @param {boolean=false} options.overwrite If true allows the move to overwrite existing files - * @param {string=} options.newName If specified, the entry is renamed to this name - */ - moveTo(folder: Folder, options?): Promise; + * @param options additional options + */ + moveTo(folder: Folder, options?: { + /** + * If true allows the move to overwrite existing files + * @default false + */ + overwrite?: boolean; + /** + * If specified, the entry is renamed to this name + * @default undefined + */ + newName?: string; + }): Promise; /** * Removes this entry from the file system. If the entry is a folder, all the contents will also be removed. @@ -88,7 +119,7 @@ declare module storage { * You'll not instantiate this directly; use Entry#getMetadata to do so. * @see {@link Entry.getMetadata} */ - interface EntryMetadata { + interface EntryMetadata { /** * The name of the entry. */ @@ -119,7 +150,7 @@ declare module storage { * Represents a file on a file system. Provides methods for reading from and writing to the file. You'll never instantiate a File directly; instead you'll get access via a FileSystemProvider. * @see {@link FileSystemProvider} */ - interface File extends Entry { + interface File extends Entry { /** * Indicates if the entry is a file */ @@ -137,11 +168,15 @@ declare module storage { /** * Reads data from the file and returns it. The file format can be specified with the `format` option. If a format is not supplied, the file is assumed to be a text file using UTF8 encoding. - * @param {object=} options - * @param {Symbol=} options.format The format of the file; see utf8 and blob. + * @param options additional options * @see {@link formats} */ - read(options?): Promise; + read(options?: { + /** + * Optional. Format to read: one of `storage.formats.utf8` or `storage.formats.binary`. + */ + format?: typeof formats.utf8 | typeof formats.binary; + }): Promise; /** * Writes data to a file, appending if desired. The format of the file is controlled via the `format` option, and defaults to UTF8. @@ -150,29 +185,45 @@ declare module storage { * @throws errors.OutOfSpaceError If writing to the file causes the file system to exceed the available space (or quota) * * @param data the data to write to the file - * @param {object=} options - * @param {Symbol=} options.format The format of the file; see utf8 and blob. - * @param {boolean=false} options.append if `true`, the data is written to the end of the file + * @param options additional options * @see {@link formats} */ - write(data: string | ArrayBuffer, options?): Promise; + write(data: string | ArrayBuffer, options?: { + /** + * Optional. Format to write: one of `storage.formats.utf8` or `storage.formats.binary`. + * @default formats.utf8 + */ + format?: typeof formats.utf8 | typeof formats.binary; + }): Promise; } /** * Provides access to files and folders on a file system. You'll typically not instantiate this directly; instead you'll use an instance of one that has already been created for you. This class is abstract, meaning that you'll need to provide your own implementation in order to use it effectively. */ - interface FileSystemProvider { + interface FileSystemProvider { /** - * Gets a file (or files) from the file system provider for the purpose of opening them. Files are read-only. + * Gets a file (or files) suitable for reading by displaying an "Open" file picker dialog to the user. File entries returned by this API are read-only - use getFileForSaving to get a File entry you can write to. * - * Multiple files can be returned if the `allowMultiple` option is `true`. - * @param {object} options - * @param {string[]} options.types the allowed file types - * @param {boolean} [options.allowMultiple=false] if `true`, multiple files can be returned (as an array) + * The user can select multiple files only if the `allowMultiple` option is `true`. + * @param options additional options * * @returns the selected files, or empty if no file were selected. */ - getFileForOpening(options?): Promise; + getFileForOpening(options?: { + /** + * Optional. Allowed file extensions, with no "." prefix; use `storage.fileTypes.all` to allow any file to be picked + * @default ['*'] + */ + types?: string[]; + /** + * Optional. If `true`, multiple files can be selected and this API returns `Array`. + * + * If `false`, only one file can be selected and this API returns a File directly. + * + * @default false + */ + allowMultiple?: boolean; + }): Promise; /** * Gets a file reference suitable for saving. The file is read-write. Any file picker displayed will be of the "save" variety. @@ -181,11 +232,16 @@ declare module storage { * * If the act of writing to the file would overwrite it, the file picker should prompt the user if they are OK with that action. If not, the file should not be returned. * - * @param {object} options - * @param {string[]} options.types Required. Allowed file extensions, with no "." prefix. + * @param suggestedName Required. The file extension should match one of the options specified in the `types` option. + * @param options additional options * @returns the selected file, or `null` if no file were selected. */ - getFileForSaving(options?): Promise; + getFileForSaving(suggestedName: string, options: { + /** + * Required. Allowed file extensions, with no "." prefix. + */ + types: string[]; + }): Promise; /** * Gets a folder from the file system via a folder picker dialog. The files and folders within can be accessed via {@link Folder.getEntries}. Any files within are read-write. @@ -224,14 +280,14 @@ declare module storage { getNativePath(entry: Entry): string; } - static class LocalFileSystemProvider extends FileSystemProvider { + interface LocalFileSystemProvider extends FileSystemProvider { // TODO: Waiting for documentation on `LocalFileSystemProvider` } /** * Represents a folder on a file system. You'll never instantiate this directly, but will get it by calling {@link FileSystemProvider.getTemporaryFolder}, {@link FileSystemProvider.getFolder}, or via {@link Folder.getEntries}. */ - static class Folder extends Entry { + interface Folder extends Entry { /** * Indicates if the entry is a file */ @@ -250,12 +306,17 @@ declare module storage { /** * Creates a File Entry object within this folder and returns the appropriate instance. Note that this method just create a file entry object and not the actual file on the disk. The file actually gets created when you call for eg: write method on the file entry object. * @param {string} name the name of the file to create - * @param {object} options - * @param {boolean=false} options.overwrite If `true`, the create attempt can overwrite an existing file + * @param options additional options * * @returns the created entry */ - createFile(name: string, options?): Promise; + createFile(name: string, options?: { + /** + * If `false`, the call will fail if the file already exists. If `true`, the call will succeed regardless of whether the file currently exists on disk. + * @default false + */ + overwrite?: boolean; + }): Promise; /** * Creates a Folder within this folder and returns the appropriate instance. @@ -273,76 +334,81 @@ declare module storage { getEntry(filePath: string): Promise; /** - * Renames an entry to a new name. - * @param {Entry} entry the entry to rename + * Renames an item on disk to a new name within the same folder. The Entry object passed to this function is automatically updated to reference the new name, however any other Entry objects referencing the original item will not be updated, and will thus no longer point to an item that exists on disk. + * @param {Entry} entry entry to rename (File or Folder). Must exist. * @param {string} newName the new name to assign - * @param {object} options - * @param {boolean=false} options.overwrite if `true`, renaming can overwrite an existing entry - */ - renameEntry(entry: Entry, newName: string, options?): Promise; + * @param options additional options + */ + renameEntry(entry: Entry, newName: string, options?: { + /** + * if `true`, renaming can overwrite an existing entry + * @default false + */ + overwrite?: boolean; + }): Promise; } - export const localFileSystem: LocalFileSystemProvider; + const localFileSystem: LocalFileSystemProvider; namespace errors { /** * Attempted to invoke an abstract method. */ - class AbstractMethodInvocationError extends Error { + class AbstractMethodInvocationError extends Error { } /** * Attempted to execute a command that required the providers of all entries to match. */ - class ProviderMismatchError extends Error { + class ProviderMismatchError extends Error { } /** * The object passed as an entry is not actually an {@link Entry}. */ - class EntryIsNotAnEntryError extends Error { + class EntryIsNotAnEntryError extends Error { } /** * The entry is not a folder, but was expected to be a folder. */ - class EntryIsNotAFolderError extends Error { + class EntryIsNotAFolderError extends Error { } /** * The entry is not a file, but was expected to be. */ - class EntryIsNotAFileError extends Error { + class EntryIsNotAFileError extends Error { } /** * The instance was expected to be a file system, but wasn't. */ - class NotAFileSystemError extends Error { + class NotAFileSystemError extends Error { } /** * The file system is out of space (or quota has been exceeded) */ - class OutOfSpaceError extends Error { + class OutOfSpaceError extends Error { } /** * The file system revoked permission to complete the requested action. */ - class PermissionDeniedError extends Error { + class PermissionDeniedError extends Error { } /** * An attempt was made to overwrite an entry without indicating that it was safe to do so via `overwrite: true`. */ - class EntryExistsError extends Error { + class EntryExistsError extends Error { } /** * An attempt was made to write to a file that was opened as read-only. */ - class FileIsReadOnlyError extends Error { + class FileIsReadOnlyError extends Error { } /** @@ -365,16 +431,16 @@ declare module storage { /** * Text file extensions */ - const text: string[]; + const text: string[]; /** * Image file extensions */ - const images: string[]; + const images: string[]; /** * All file types */ - const all: string[]; + const all: string[]; } /** @@ -384,11 +450,11 @@ declare module storage { /** * UTF8 File encoding */ - const utf8: unique symbol; + const utf8: unique symbol; /** * Binary file encoding */ - const binary: unique symbol; + const binary: unique symbol; } /** @@ -398,11 +464,11 @@ declare module storage { /** * The file is read-only; attempts to write will fail. */ - const readOnly: unique symbol; + const readOnly: unique symbol; /** * The file is read-write. */ - const readWrite: unique symbol; + const readWrite: unique symbol; } /** @@ -412,12 +478,10 @@ declare module storage { /** * A file; used when creating an entity */ - const file: unique symbol; + const file: unique symbol; /** * A folder; used when creating an entity */ - const folder: unique symbol; + const folder: unique symbol; } } - -export = {shell, storage}; diff --git a/types/viewport.d.ts b/types/viewport.d.ts index aa564b1..0ac2189 100644 --- a/types/viewport.d.ts +++ b/types/viewport.d.ts @@ -2,63 +2,59 @@ * The `viewport` module represents the current UI view of the XD document's content. * Since: XD 14 */ -import {SceneNode} from "./scenegraph"; +import {SceneNode} from "scenegraph"; -declare class viewport { - /** - * The current viewport bounds expressed in global coordinates. - */ - static readonly bounds: {x:number,y:number,width:number,height:number}; - - /** - * The current viewport zoom factor (where 1.0 = 100% zoom, 0.5 = 50% zoom, etc.). - */ - static readonly zoomFactor: number; +/** + * The current viewport bounds expressed in global coordinates. + */ +export const bounds: { x: number, y: number, width: number, height: number }; - /** - * Smoothly pan the viewport to bring the entire given region into view. If the region is already fully in view, does nothing. If the given region is too large to fit entirely in view, it is simply centered (zoom remains unchanged). - * - * The region can be defined by passing a {@link SceneNode}, or by explicitly specifying a rectangle in global coordinates. - * @param {!SceneNode} node The node that gets scrolled into view - */ - static scrollIntoView(node: SceneNode): void; +/** + * The current viewport zoom factor (where 1.0 = 100% zoom, 0.5 = 50% zoom, etc.). + */ +export const zoomFactor: number; - /** - * Smoothly pan the viewport to bring the entire given region into view. If the region is already fully in view, does nothing. If the given region is too large to fit entirely in view, it is simply centered (zoom remains unchanged). - * - * The region can be defined by passing a {@link SceneNode}, or by explicitly specifying a rectangle in global coordinates. - * @param x - * @param y - * @param width - * @param height - */ - static scrollIntoView(x: number, y:number, width:number, height:number): void; +/** + * Smoothly pan the viewport to bring the entire given region into view. If the region is already fully in view, does nothing. If the given region is too large to fit entirely in view, it is simply centered (zoom remains unchanged). + * + * The region can be defined by passing a {@link SceneNode}, or by explicitly specifying a rectangle in global coordinates. + * @param {!SceneNode} node The node that gets scrolled into view + */ +export function scrollIntoView(node: SceneNode): void; - /** - * Smoothly pan the viewport to center on a specific point in the document's global coordinates. Even if the point is already in view, the view pans until it is centered. - * @param {number} x The x-coordinate of the centered point (in the document's global coordinates) - * @param {number} y The y-coordinate of the centered point (in the document's global coordinates) - */ - static scrollToCenter(x: number, y:number): void; +/** + * Smoothly pan the viewport to bring the entire given region into view. If the region is already fully in view, does nothing. If the given region is too large to fit entirely in view, it is simply centered (zoom remains unchanged). + * + * The region can be defined by passing a {@link SceneNode}, or by explicitly specifying a rectangle in global coordinates. + * @param x + * @param y + * @param width + * @param height + */ +export function scrollIntoView(x: number, y: number, width: number, height: number): void; - /** - * Zoom & pan the view as needed so the given region fills the viewport (with some padding). If the region is large, zooms out as needed so it fits entirely in view. If the region is smaller, zooms in so the region fills the entire viewport - may zoom in past 100% to achieve this. - * - * The region can be defined by passing a {@link SceneNode}, or by explicitly specifying a rectangle in global coordinates. - * @param {!SceneNode} node - */ - static zoomToRect(node: SceneNode): void; +/** + * Smoothly pan the viewport to center on a specific point in the document's global coordinates. Even if the point is already in view, the view pans until it is centered. + * @param {number} x The x-coordinate of the centered point (in the document's global coordinates) + * @param {number} y The y-coordinate of the centered point (in the document's global coordinates) + */ +export function scrollToCenter(x: number, y: number): void; - /** - * Zoom & pan the view as needed so the given region fills the viewport (with some padding). If the region is large, zooms out as needed so it fits entirely in view. If the region is smaller, zooms in so the region fills the entire viewport - may zoom in past 100% to achieve this. - * - * The region can be defined by passing a {@link SceneNode}, or by explicitly specifying a rectangle in global coordinates. - * @param {number} x - * @param {number} y - * @param {number} width - * @param {number} height - */ - static zoomToRect(x: number, y:number, width:number, height:number): void; -} +/** + * Zoom & pan the view as needed so the given region fills the viewport (with some padding). If the region is large, zooms out as needed so it fits entirely in view. If the region is smaller, zooms in so the region fills the entire viewport - may zoom in past 100% to achieve this. + * + * The region can be defined by passing a {@link SceneNode}, or by explicitly specifying a rectangle in global coordinates. + * @param {!SceneNode} node + */ +export function zoomToRect(node: SceneNode): void; -export = viewport; +/** + * Zoom & pan the view as needed so the given region fills the viewport (with some padding). If the region is large, zooms out as needed so it fits entirely in view. If the region is smaller, zooms in so the region fills the entire viewport - may zoom in past 100% to achieve this. + * + * The region can be defined by passing a {@link SceneNode}, or by explicitly specifying a rectangle in global coordinates. + * @param {number} x + * @param {number} y + * @param {number} width + * @param {number} height + */ +export function zoomToRect(x: number, y: number, width: number, height: number): void;