### Using prompt() Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/uxp-api/reference-js/Global Members/HTML DOM/prompt.md This example demonstrates how to use the prompt() method to get user input and display it. ```APIDOC ## prompt() ### Description Displays a dialog box that prompts the visitor for input. ### Syntax `returnValue = window.prompt(message, defaultValue)` ### Parameters #### message (optional) - **message** (string) - Optional - The message to display to the user. #### defaultValue (optional) - **defaultValue** (string) - Optional - The default value displayed in the text field. ### Return Value - **returnValue** (string or null) - The string entered by the user, or null if the user clicks "Cancel" or closes the dialog. ### Example ```javascript let userName = prompt("Please enter your name:", "John Doe"); if (userName != null) { console.log("Hello " + userName + "!"); } else { console.log("User cancelled the prompt."); } ``` ``` -------------------------------- ### Example: Recording a 'Hello Alert' Action Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/media/action-recording.md This example demonstrates recording an Action step that displays an alert. Ensure the `alertHandler` function is declared at the global level. An info argument is required, even if empty. ```javascript // Start recording an Action, then execute the code below. async function alertHandler(context, dataObj) { require('photoshop').core.showAlert(dataObj.message); return dataObj; }; require('photoshop').action.recordAction( { "name": "Hello Alert", "methodName": "alertHandler" }, {message: "Hello!"} ); // Stop recording, and play the Action. ``` -------------------------------- ### Example Manifest v5 Structure Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/guides/uxp_guide/uxp-misc/manifest-v5/index.md A comprehensive example of a manifest file using version 5, demonstrating various configurations including entrypoints, icons, and required permissions for network, clipboard, webview, and launchProcess. ```json { "manifestVersion": 5, "id": "YOUR_ID_HERE", "name": "Name of your plugin", "version": "1.0.0", "main": "index.html", "host": { "app": "PS", "minVersion": "23.3.0" }, "entrypoints": [ { "type": "command", "id": "commandFn", "label": { "default": "Show A Dialog" } }, { "type": "panel", "id": "panelName", "label": { "default": "Panel Name" }, "minimumSize": {"width": 230, "height": 200}, "maximumSize": {"width": 2000, "height": 2000}, "preferredDockedSize": {"width": 230, "height": 300}, "preferredFloatingSize": {"width": 230, "height": 300}, "icons": [ {"width":23,"height":23,"path":"icons/dark.png","scale":[1,2],"theme":["darkest","dark","medium"]}, {"width":23,"height":23,"path":"icons/light.png","scale":[1,2],"theme":["lightest","light"]} ] } ], "icons": [ { "width": 23, "height": 23, "path": "icons/icon_D.png", "scale": [ 1, 2 ], "theme": [ "dark", "darkest" ], "species": [ "generic" ] }, { "width": 23, "height": 23, "path": "icons/icon_N.png", "scale": [ 1, 2 ], "theme": [ "lightest", "light" ], "species": [ "generic" ] } ], "requiredPermissions": { "network": { "domains": [ "https://adobe.com", ] }, "clipboard": "readAndWrite", "webview": { "allow": "yes", "domains": [ "https://*.adobe.com", "https://*.google.com"] }, "launchProcess": { "schemes": [ "https", "slack"], "extensions": [ ".xd", ".psd" ] }, }, } ``` -------------------------------- ### Setup Plugin Entry Points with Promises Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/guides/uxp_guide/uxp-misc/manifest-v5/index.md Configure plugin lifecycle events like create, destroy, and panel interactions using promises for asynchronous operations. This setup defines handlers for plugin creation and destruction, as well as various states of panels. ```javascript import { entrypoints } from "uxp"; entrypoints.setup({ plugin: { create() { console.log("Plugin has been loaded, plugin.create has been triggered."); }, destroy() { return new Promise(function (resolve, reject) { console.log("Plugin has been loaded, plugin.create has been triggered."); resolve(); }); } }, panels: { panelA: { create(rootNode) { return new Promise(function (resolve, reject) { console.log("PanelA is created, panelA.create has been triggered."); resolve(); }); }, show(rootNode, data) { return new Promise(function (resolve, reject) { console.log("PanelA is about to be displayed, panelA.show has been triggered with data ", data); resolve(); }); }, hide(rootNode, data) { return new Promise(function (resolve, reject) { console.log("PanelA is about to be hidden, panelA.hide has been triggered with data ", data); resolve(); }); }, destroy(rootNode) { return new Promise(function (resolve, reject) { console.log("PanelA is about to be destroyed, panelA.destroy has been triggered."); resolve(); }); }, invokeMenu(menuId) { return new Promise(function (resolve, reject) { console.log("A menu item on PanelA has been invoked, panelA.invokeMenu has been triggered with menu id ", menuId); resolve(); }); }, menuItems: [...] }, "panelB": {..} }, commands: { "command1": { run() {..}, cancel() {..} }, "command2": function(){..} } }); ``` -------------------------------- ### Get All Document Properties Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/media/batchplay.md This example shows how to use batchPlay with the 'get' action without a target property to retrieve all possible properties of a document. This is primarily for development and debugging purposes. ```APIDOC ## Get All Document Properties ### Description When the `get` command is used without a specific target property, `batchPlay` returns all available properties for the specified target. This is useful for developers to understand the full range of properties supported by an element. ### Method `photoshop.action.batchPlay` ### Parameters - `commands`: An array containing the commands to execute. For getting all properties, it includes an object with `_obj: "get"` and a `_target` specifying the document. - `options`: An empty object `{}` in this example. ### Request Example ```javascript var target = {_ref: [ {_ref: "document", _id: someDocumentID}, {_ref: "application"} ]}; var command = {_obj: "get", _target: target}; let result = await photoshop.action.batchPlay([command], {}); ``` ### Response #### Success Response - `result`: An array containing an object with all properties of the target document. #### Response Example ```javascript [{"mode": {"_enum": "colorSpace", "_value": "RGBColor"}, "bigNudgeH": 655360, "bigNudgeV": 655360, "rulerOriginH": 0, "rulerOriginV": 0, "width": {"_unit": "distanceUnit", "_value": 504}, "height": {"_unit": "distanceUnit", "_value": 360}, "resolution": {"_unit": "densityUnit", "_value": 300}, "title": "Untitled-1", "fileInfo": {"_obj": "fileInfo"}, "numberOfPaths": 0, "numberOfChannels": 3, "numberOfLayers": 0, "targetPathIndex": -1, "workPathIndex": -1, "clippingPathInfo": {"_obj": "clippingInfo", "clippingPathIndex": -1, "clippingPathFlatness": 0}, . . . }] ``` ### Warning Using the "get all" command is not recommended for shipping plugins as it can be slow and may become slower in the future. ``` -------------------------------- ### Sample Pixel Example Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/media/batchplay.md This example shows how to use batchPlay to sample the color of a pixel at a specific coordinate within the active document. It also requires execution within a modal scope. ```APIDOC ## Sample Pixel ### Description Samples the color of a pixel at a specified point in the active document. ### Method `action.batchPlay` (within `core.executeAsModal`) ### Endpoint N/A (SDK method) ### Parameters #### Request Body (Descriptors) ```json { "_obj": "colorSampler", "_target": {"_ref": "document", "_enum": "ordinal", "_value": "targetEnum"}, "samplePoint": { "horizontal": 100, "vertical": 100 } } ``` #### Options An empty object `{}` is used in this example. ### Request Example ```javascript const {app, action, core} = require('photoshop'); async function samplePixel() { return await action.batchPlay([ { _obj: "colorSampler", _target: {_ref: "document", _enum: "ordinal", _value: "targetEnum"}, samplePoint: { horizontal: 100, vertical: 100 } } ], {}); } // Must be executed within a modal scope let result = await core.executeAsModal(samplePixel, {commandName: "Sample Pixel"}); ``` ### Response #### Success Response (200) Returns an array containing the sampled color information. #### Response Example ```json [ { "colorSampler": { "_obj": "CMYKColorClass", "black": 0, "cyan": 26.27, "magenta": 4.71, "yellowColor": 0 }, "sampledData": true } ] ``` ``` -------------------------------- ### Example Manifest v4 Structure Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/guides/uxp_guide/uxp-misc/manifest-v4/index.md This is an example of a manifest file for UXP version 4. It includes top-level metadata, host application information, and defines entry points for commands and panels. ```json { "manifestVersion": 4, "id": "YOUR_ID_HERE", "name": "Name of your plugin", "version": "1.0.0", "main": "index.html", "host": { "app": "PS", "minVersion": "23.0.0" }, "entrypoints": [ { "type": "command", "id": "commandFn", "label": { "default": "Show A Dialog" } }, { "type": "panel", "id": "panelName", "label": { "default": "Panel Name" }, "minimumSize": {"width": 230, "height": 200}, "maximumSize": {"width": 2000, "height": 2000}, "preferredDockedSize": {"width": 230, "height": 300}, "preferredFloatingSize": {"width": 230, "height": 300}, "icons": [ {"width":23,"height":23,"path":"icons/dark.png","scale":[1,2],"theme":["darkest","dark","medium"]}, {"width":23,"height":23,"path":"icons/light.png","scale":[1,2],"theme":["lightest","light"]} ] } ], "icons": [ { "width": 23, "height": 23, "path": "icons/icon_D.png", "scale": [ 1, 2 ], "theme": [ "dark", "darkest" ], "species": [ "generic" ] }, { "width": 23, "height": 23, "path": "icons/icon_N.png", "scale": [ 1, 2 ], "theme": [ "lightest", "light" ], "species": [ "generic" ] } ] } ``` -------------------------------- ### Multi-Get Properties from First Two Layers Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/media/batchplay.md This example shows how to get 'name', 'layerID', and 'opacity' from the first two layers of a document. ```APIDOC ## Multi-Get Properties from First Two Layers ### Description Retrieves multiple properties from a specified range of layers within a document. ### Method `batchPlay` ### Parameters `layerProperties` object: - `_obj`: "multiGet" - `_target`: Reference to the document. - `extendedReference`: A list containing a property list and an object specifying the layer range: `[["name", "layerID", "opacity"], {_obj: "layer", index: 1, count: 2}]`. - `options`: Optional settings for handling missing properties or elements. Example: `{failOnMissingProperty: false, failOnMissingElement: false}`. ### Request Example ```javascript layerProperties = { _obj: "multiGet", _target: {_ref: [{_ref: "document", _enum: "ordinal"}]}, extendedReference: [ ["name", "layerID", "opacity"], {_obj: "layer", index: 1, count: 2} ], options: {failOnMissingProperty: false, failOnMissingElement: false} }; result = await action.batchPlay([layerProperties], {}); ``` ### Response Example ```json [{"list": [ {"name": "Layer 1", "layerID": 2, "opacity": 255}, {"name": "Layer 2", "layerID": 3, "opacity": 255} ]}] ``` ``` -------------------------------- ### Getting All Open Documents Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/index.md This example shows how to get an array of all currently open documents in Photoshop. ```APIDOC ## Getting All Open Documents ### Description This code retrieves an array containing all documents that are currently open in Photoshop using `app.documents`. ### Code ```javascript const allDocuments = app.documents; ``` ``` -------------------------------- ### batchPlay Rejection Example Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/media/batchplay.md This example demonstrates an invalid initial argument provided to batchPlay, resulting in a promise rejection. The first argument is expected to be a descriptor list, not a boolean. ```javascript action.batchPlay(true, {}); ``` ```javascript [[PromiseState]]: "rejected" [[PromiseResult]]: Error: Argument 1 has an invalid type. Expected type: array actual type: boolean ``` -------------------------------- ### Install Yarn with npm Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/guides/uxp_guide/uxp-misc/uxp-toolchain/index.md Use this command to install Yarn globally after npm is installed. This is useful for managing project dependencies. ```bash npm install yarn --global ``` -------------------------------- ### Guide Class Methods Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/classes/guide.md Methods available for the Guide class, allowing interaction with guides in a Photoshop document. ```APIDOC ## Guide Methods ### delete 23.0 *void* Deletes the guide from the document. ``` -------------------------------- ### Creating and Using an AbortController Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/uxp-api/reference-js/Global Members/HTML DOM/AbortController.md This example demonstrates how to create an AbortController instance, associate it with a fetch request, and then abort the request. ```APIDOC ## Creating and Using an AbortController ### Description This example demonstrates how to create an `AbortController` instance, associate it with a fetch request, and then abort the request. ### Method `new AbortController()` ### Usage ```javascript const controller = new AbortController(); const signal = controller.signal; fetch('https://example.com/data', { signal: signal }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => { if (error.name === 'AbortError') { console.log('Fetch aborted'); } else { console.error('Fetch error:', error); } }); // To abort the request: controller.abort(); ``` ### Parameters #### Constructor - `AbortController()`: Creates a new `AbortController` instance. #### `AbortController.prototype.abort()` - **`abort()`**: Signals an abort event to the associated `AbortSignal`. This will cause any operation listening to the signal to be interrupted. ### Related - `AbortSignal` ``` -------------------------------- ### Photoshop Manifest Configuration Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/guides/uxp_guide/uxp-misc/manifest-v4/photoshop-manifest/index.md Example of a UXP plugin manifest file with Photoshop-specific configurations under the 'data' object. ```json { "manifestVersion": 4, "id": "YOUR_ID_HERE", "name": "Name of your plugin", "version": "1.0.0", "main": "index.html", "host": { "app": "PS", "minVersion": "23.0.0", "data" : { "apiVersion": 2, "loadEvent": "use", "enableMenuRecording": true }, }, "entrypoints": [ { "type": "command", "id": "MENU_ITEM_ID", "label": { "default": "menu item's text"} } ] } ``` -------------------------------- ### Importing and Using Constants Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/modules/constants.md Demonstrates how to import the `constants` object from the `photoshop` module and use it with an example function like `resizeImage`. ```APIDOC ## Importing and Using Constants ### Description To use any constant, import the `constants` object from the photoshop module first. ### Code Example ```javascript const {app, constants} = require("photoshop"); await app.activeDocument.resizeImage( 800, 600, 100, constants.InterpolationMethod.AUTOMATIC ); ``` ``` -------------------------------- ### observe() Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/uxp-api/reference-js/Global Members/HTML DOM/ResizeObserver.md Starts observing a target element for size changes. ```APIDOC ## observe(target[, options]) ### Description Starts observing the `target` element for size changes. ### Parameters #### target - **target** (Element) - Required - The element to observe. #### options - **options** (object) - Optional - An object specifying which element's dimensions to observe. It can have a `box` property with values 'content-box', 'border-box', or 'device-pixel-content-box'. ``` -------------------------------- ### createTextLayer with TextLayerCreateOptions Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/objects/createoptions/textlayercreateoptions.md Example of creating a text layer with custom options using Document.createTextLayer. ```APIDOC ## createTextLayer with TextLayerCreateOptions ### Description Creates a new text layer with specified properties. ### Method `Document.createTextLayer(options?: TextLayerCreateOptions)` ### Parameters #### Request Body - **name** (string) - Optional - Name of the newly created layer. If no value is provided, then a name will be generated following the template, "Layer #". - **contents** (string) - Optional - Text content of the newly created text layer. Defaults to "Lorem Ipsum". - **fontSize** (number) - Optional - Font size of the newly created text layer in pixels. Defaults to 12px. - **position** (Position) - Optional - Insertion coordinates of the newly created text layer, in pixels. Defaults to document center. - **fontName** (string) - Optional - Font PostScript name of the newly created text layer. Defaults to "MyriadPro-Regular". - **blendMode** (BlendMode) - Optional - Blend mode of the newly created layer or group. Defaults to NORMAL. - **color** (LabelColors) - Optional - Label color of the newly created layer or group. Defaults to NONE. - **group** (boolean) - Optional - Whether to use previous layer to create clipping mask. Defaults to false. - **opacity** (number) - Optional - Opacity of the newly created layer or group. Defaults to 100. - **textColor** (SolidColor) - Optional - Text color of the newly created text layer. Defaults to black. ### Request Example ```javascript const options = { name: "myTextLayer", contents: "Hello, World!", fontSize: 24, position: {x: 200, y: 300} }; await require('photoshop').app.activeDocument.createTextLayer(options); ``` ### Response #### Success Response (TextLayer) Returns the newly created TextLayer object. #### Response Example ```json { "id": 123, "name": "myTextLayer", "kind": "text" } ``` ``` -------------------------------- ### Flattening All Documents Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/index.md This example demonstrates how to flatten all currently open documents using `executeAsModal`. ```APIDOC ## Flattening All Documents ### Description This code snippet flattens all open documents in Photoshop. It utilizes `executeAsModal` to ensure the operation is performed safely. ### Method ```javascript const app = require('photoshop').app; const toFlatten = app.documents; async function flattenThem(executionContext) { toFlatten.forEach((photoshopDoc) => { photoshopDoc.flatten(); }); }; await require('photoshop').core.executeAsModal(flattenThem); ``` ``` -------------------------------- ### UXP Plugin Manifest and Entrypoints Setup Source: https://context7.com/adobedocs/uxp-photoshop/llms.txt Configure plugin lifecycle callbacks, panel management, and command execution using `entrypoints.setup()`. Inter-plugin communication requires enabling it in the manifest. ```javascript // index.js — panel lifecycle using entrypoints.setup() const { entrypoints } = require('uxp'); entrypoints.setup({ plugin: { create() { console.log("Plugin loaded"); }, destroy() { return new Promise((resolve) => { console.log("Plugin unloading — cleanup"); resolve(); }); } }, panels: { mainPanel: { create(rootNode) { // rootNode is the panel's DOM root rootNode.innerHTML = `Ready`; }, show(rootNode, data) { console.log("Panel shown with data:", data); }, hide(rootNode, data) { console.log("Panel hidden"); }, destroy(rootNode) { console.log("Panel destroyed"); }, invokeMenu(menuId) { if (menuId === "refreshAction") refreshData(); }, menuItems: [ { id: "refreshAction", label: "Refresh", enabled: true, checked: false } ] } }, commands: { runScript: { run() { require('photoshop').core.showAlert({ message: "Command triggered!" }); }, cancel() { console.log("Command cancelled"); } } } }); // Inter-plugin communication (requires "ipc.enablePluginCommunication": true in manifest) const { pluginManager } = require('uxp'); const target = Array.from(pluginManager.plugins).find(p => p.id === "com.other.plugin"); if (target) { target.showPanel("mainPanel"); target.invokeCommand("someCommand"); } ``` -------------------------------- ### Get Installed Fonts with app.fonts Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/changelog/index.md Access the `app.fonts` getter to retrieve a collection of all installed fonts on the system. ```javascript app.fonts ``` -------------------------------- ### UXP Developer Tool (UDT) Setup and Workflow Source: https://context7.com/adobedocs/uxp-photoshop/llms.txt This bash snippet outlines the initial steps for setting up the UXP Developer Tool (UDT) and creating a new plugin scaffold. It details how to load, watch, and debug plugins within Photoshop using UDT. ```bash # Install UDT via Creative Cloud Desktop App # Then create a plugin scaffold: # 1. Open UDT → "Create plugin..." # 2. Fill in: Plugin Name, Plugin ID, Version, Host=Adobe Photoshop # 3. Select template: "quick-layers-starter" # 4. Choose an empty folder # Resulting files: # ├── icons/ # ├── index.html ← panel UI # ├── index.js ← plugin logic # └── manifest.json ← plugin metadata # Load plugin in Photoshop: UDT → ••• → Load # Watch for live reload: UDT → ••• → Watch # Open DevTools debugger: UDT → ••• → Debug ``` -------------------------------- ### Get Document Title Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/media/batchplay.md This example demonstrates how to use batchPlay with the 'get' action to retrieve the title of a specific document. ```APIDOC ## Get Document Title ### Description Use the `batchPlay` function with the `get` action and a target property to obtain specific state information from Photoshop, such as the document title. ### Method `photoshop.action.batchPlay` ### Parameters - `commands`: An array containing the commands to execute. For getting the title, it includes an object with `_obj: "get"` and a `_target` specifying the property and document. - `options`: An empty object `{}` in this example. ### Request Example ```javascript var target = {_ref: [ {_property: "title"}, {_ref: "document", _id: someDocumentID}, {_ref: "application"} ]}; var command = {_obj: "get", _target: target}; let result = await photoshop.action.batchPlay([command], {}); ``` ### Response #### Success Response - `result`: An array containing the retrieved properties. For the title, it will be an array with an object containing the `title` key. #### Response Example ```javascript [{"title": "Untitled-1"}] ``` ``` -------------------------------- ### Manifest v5 Plugin Permissions and entrypoints.setup() Source: https://context7.com/adobedocs/uxp-photoshop/llms.txt Configures plugin lifecycle callbacks for panels and commands, and sets up declarative security permissions for network, clipboard, WebView, filesystem, and inter-plugin communication. ```APIDOC ## Manifest v5 Plugin Permissions and entrypoints.setup() Declarative security model for network, clipboard, WebView, filesystem, and inter-plugin communication. `entrypoints.setup()` wires lifecycle callbacks for panels and commands. ```javascript // index.js — panel lifecycle using entrypoints.setup() const { entrypoints } = require('uxp'); entrypoints.setup({ plugin: { create() { console.log("Plugin loaded"); }, destroy() { return new Promise((resolve) => { console.log("Plugin unloading — cleanup"); resolve(); }); } }, panels: { mainPanel: { create(rootNode) { // rootNode is the panel's DOM root rootNode.innerHTML = `Ready`; }, show(rootNode, data) { console.log("Panel shown with data:", data); }, hide(rootNode, data) { console.log("Panel hidden"); }, destroy(rootNode) { console.log("Panel destroyed"); }, invokeMenu(menuId) { if (menuId === "refreshAction") refreshData(); }, menuItems: [ { id: "refreshAction", label: "Refresh", enabled: true, checked: false } ] } }, commands: { runScript: { run() { require('photoshop').core.showAlert({ message: "Command triggered!" }); }, cancel() { console.log("Command cancelled"); } } } }); // Inter-plugin communication (requires "ipc.enablePluginCommunication": true in manifest) const { pluginManager } = require('uxp'); const target = Array.from(pluginManager.plugins).find(p => p.id === "com.other.plugin"); if (target) { target.showPanel("mainPanel"); target.invokeCommand("someCommand"); } ``` ``` -------------------------------- ### Get TextFont by Name Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/classes/textfont.md Retrieves a TextFont object by its name from the Photoshop application's font collection. Ensure the font is installed and available. ```javascript const arialMTFont = require('photoshop').app.fonts.getByName("ArialMT"); ``` -------------------------------- ### Get Multiple Properties from First Two Layers Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/media/batchplay.md Retrieve the name, layerID, and opacity from the first two layers of the active document. This example demonstrates using a target reference to a document and an extendedReference with a property list and an element range. ```javascript layerProperties = { _obj: "multiGet", _target: {_ref: [{_ref: "document", _enum: "ordinal"}]}, extendedReference: [ ["name", "layerID", "opacity"], {_obj: "layer", index: 1, count: 2} ], options: {failOnMissingProperty: false, failOnMissingElement: false} }; result = await action.batchPlay([layerProperties], {}); ``` -------------------------------- ### Acquiring Suites, Creating, and Sending Messages Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/media/cpp-pluginsdk.md Demonstrates acquiring necessary suites, creating an ActionDescriptor, populating it with data, and sending it to a UXP plugin. ```cpp // in your main method sSPBasic->AcquireSuite( kPSUXPSuite, kPSUXPSuiteVersion1, (const void**)&sUxpProcs); sSPBasic->AcquireSuite(kPSActionDescriptorSuite, kPSActionDescriptorSuiteVersion, (const void**)&sDescriptorProcs); PIActionDescriptor desc; sDescriptorProcs->Make(&desc); sDescriptorProcs->PutString(desc, 'helo', "Hello World!"); sDescriptorProcs->PutFloat(desc, 'fltp', 0.952); const char* UXP_MANIFEST_ID = "com.your.pluginId"; sUxpProcs->SendUXPMessage(gPlugInRef, UXP_MANIFEST_ID, desc); } ``` -------------------------------- ### Guides Collection Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/classes/guides.md Access the Guides collection through the Document.guides property. This collection provides methods to manage guides within a document. ```APIDOC ## Guides Collection Access this collection through [Document.guides](/ps_reference/classes/document/#guides) property. ### Example ```javascript app.activeDocument.guides.add(Constants.Direction.HORIZONTAL, 20); ``` ### Properties - **length** (*number*, R): Number of [Guide](/ps_reference/classes/guide/) elements in this collection. - **parent** ([*Document*](/ps_reference/classes/document/), R): The owner document of this Guide collection. ### Methods #### add [*Guide*](/ps_reference/classes/guide/) Adds a guide for the collection at the given coordinate and direction. ##### Parameters - **direction** ([*Direction*](/ps_reference/modules/constants/#direction)): Indicates whether the guide is vertical or horizontal. - **coordinate** (*number*): Position of the guide measured from the ruler origin in pixels. The value can be a decimal. Note: the user can move the ruler origin which will affect the position value of the guides. #### removeAll *void* Clears all guides from this collection. ``` -------------------------------- ### Create a Simple Dialog UI Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/scripting/samples/index.md Demonstrates creating a basic dialog element with UXP. This example creates a dialog with a header and appends it to the document body. ```javascript async function createDialog() { const dialog = document.createElement("dialog"); dialog.style.color = "white"; const div = document.createElement("div"); div.style.display = "block"; div.style.height = "200px"; div.style.width = "400px"; const header = document.createElement("h2"); header.id = "head"; header.style.color = "white"; header.textContent = "Sample Dialog"; div.appendChild(header); dialog.appendChild(div); await document.body.appendChild(dialog).showModal(); } // Wait for the dialog to render await createDialog(); ``` -------------------------------- ### Record and Execute a 'Make Layer' Action Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/media/batchplay.md This example demonstrates how to record a single Photoshop command, such as 'make layer', as a JavaScript action descriptor and then execute it using batchPlay. It utilizes executeAsModal for safe execution. ```javascript async function actionCommands() { let command; let result; let psAction = action; // Make layer command = {_obj: "make", _target: [{_ref: "layer"}], layerID: 2}; result = await psAction.batchPlay([command], {}); } async function runModalFunction() { await core.executeAsModal(actionCommands, {commandName: "Action Commands"}); } await runModalFunction(); ``` -------------------------------- ### Access Installed Fonts in Photoshop Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/scripting/samples/index.md Demonstrates how to access installed fonts in Photoshop. UXP falls back to the system-UI font if no font is specified or if the font is not installed. ```javascript async function createDialog() { const dialog = document.createElement("dialog"); dialog.style.color = "white"; const div = document.createElement("div"); div.style.display = "block"; div.style.height = "200px"; div.style.width = "450px"; const p1 = createParagraph("system-ui"); // use default OS font const p2 = createParagraph("non-existent-font"); // try using a non existent font. Will resolve to OS default. const p3 = createParagraph("Courier New"); // use any installed font div.appendChild(p1); div.appendChild(p2); div.appendChild(p3); dialog.appendChild(div); await document.body.appendChild(dialog).showModal(); } function createParagraph(fontFamily) { const p = document.createElement("p"); p.style.color = "white"; p.style.fontFamily = fontFamily; p.textContent = `font-family:${fontFamily}: A fox jumps over the lazy dog`; return p; } // Wait for the dialog to render await createDialog(); ``` -------------------------------- ### UXP File System Operations Source: https://context7.com/adobedocs/uxp-photoshop/llms.txt Demonstrates how to use `uxp.storage.localFileSystem` for cross-platform file I/O, including opening files, saving files, and managing plugin-specific storage. ```APIDOC ## UXP File System (`uxp.storage.localFileSystem`) Cross-platform file I/O: open/save dialogs, reading and writing files, creating folders, and navigating entries in the local filesystem. ```javascript const { storage } = require('uxp'); const fs = storage.localFileSystem; // Prompt user to pick a file to open const fileEntry = await fs.getFileForOpening({ allowMultiple: false, types: ['psd', 'png', 'jpg'] }); if (fileEntry) { const contents = await fileEntry.read({ format: storage.formats.binary }); // ArrayBuffer console.log(`Read ${contents.byteLength} bytes from ${fileEntry.name}`); } // Prompt user to save a file const saveEntry = await fs.getFileForSaving("layers-report.tsv"); if (saveEntry) { const { app } = require('photoshop'); let tsv = "Name\tOpacity\tVisible\n"; for (const layer of app.activeDocument.layers) { tsv += `${layer.name}\t${layer.opacity}\t${layer.visible ? "yes" : "no"}\n`; } await saveEntry.write(tsv); // write string console.log("Saved to:", saveEntry.nativePath); } // Write to plugin's own private storage (no permission needed) const pluginFolder = await fs.getDataFolder(); const logFile = await pluginFolder.createFile("plugin.log", { overwrite: true }); await logFile.write("Plugin started at " + new Date().toISOString()); // Read JSON config from plugin bundle const configFile = await (await fs.getPluginFolder()).getEntry("config.json"); const raw = await configFile.read({ format: storage.formats.utf8 }); const config = JSON.parse(raw); ``` ``` -------------------------------- ### Guide Class Properties Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/classes/guide.md Properties of the Guide class that define its characteristics and state within a Photoshop document. ```APIDOC ## Guide Properties Represents a single guide in the document. ### Properties | Name | Type | Access | Min Version | Description | | :------ | :------ | :------ | :------ | :------ | | coordinate | *number* | R W | 23.0 | Position of the guide measured from the ruler origin in pixels. The value can be a decimal. Note: the user can move the ruler origin which will affect the position value of the guides. ***Fixes in Photoshop 24.0:*** - *Return correct value when resolution is not 72 PPI* | | direction | [*Direction*](/ps_reference/modules/constants/#direction) | R W | 23.0 | Indicates whether the guide is vertical or horizontal. | | docId | *number* | R | 23.0 | The ID of the document of this guide. | | id | *number* | R | 23.0 | For use with batchPlay operations. This guide ID, along with its document ID can be used to represent this guide for the lifetime of this document or the guide. | | parent | [*Document*](/ps_reference/classes/document/) | R | 23.0 | Owner document of this guide. | | typename | *string* | R | 23.0 | The class name of the referenced object: *"Guide"*. | ``` -------------------------------- ### Windows Display Configuration Example Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/media/displayunits.md On Windows, `getDisplayConfiguration` returns pixel values for display bounds and physical resolution. The scale factor indicates the display scaling applied. ```JSON { "globalBounds": { "bottom": 2160, "left": 0, "right": 3840, "top": 0 }, "physicalResolution": { "horizontal": 163, "vertical": 163 }, "scaleFactor": 2, } ``` -------------------------------- ### Get User Idle Time Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/media/photoshopcore.md Get the current number of seconds the user has been idle. This can be used in conjunction with setUserIdleTime. ```javascript await core.getUserIdleTime(); ``` -------------------------------- ### Get Document Color Mode Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/changelog/index.md Access the read-only `mode` property to get the current color mode of the document. ```javascript Document.mode ``` -------------------------------- ### Define Flyout Menu Structure in UXP Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/guides/uxp_guide/uxp-misc/flyout-menus/index.md Use the `entrypoints.setup` method to define the structure and menu items for your plugin's flyout menu. The `invokeMenu` callback handles user selections. ```javascript const { entrypoints } = require("uxp"); // the setup() function tells UXP how to handle // the entrypoints defined in your manifest.json file. entrypoints.setup({ panels: { my_panel_entrypoint: { show() { // put any initialization code for your plugin here. }, menuItems: [ {id: "setWarpFactor", label: "Warp Factor 1"}, {id: "raiseShields", label: "Shields Up"}, {id: "makeItSo", label: "Engage"} ], invokeMenu(id) { handleFlyout(id); } } } }); ``` -------------------------------- ### Add a Vertical Guide Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/classes/guides.md Adds a new vertical guide to the active document at a specified pixel coordinate. Ensure Constants.Direction is imported. ```javascript app.activeDocument.guides.add(Constants.Direction.VERTICAL, 50); ``` -------------------------------- ### Add a Horizontal Guide Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/classes/guides.md Adds a new horizontal guide to the active document at a specified pixel coordinate. Ensure Constants.Direction is imported. ```javascript app.activeDocument.guides.add(Constants.Direction.HORIZONTAL, 20); ``` -------------------------------- ### Plugin UI Structure (index.html) Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/guides/getting-started/creating-your-first-plugin/index.md Sets up the user interface for the plugin panel using HTML and custom Spectrum UXP components. It includes a heading, a body for displaying content, and a button to trigger an action. ```html Layers No layers ``` -------------------------------- ### Get Document Dimensions and Resolution Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/index.md Access properties of the active document to get its height, width, and resolution. Logs the information to the console. ```javascript const app = require('photoshop').app; const myDoc = app.activeDocument; const height = myDoc.height; const width = myDoc.width; const resolution = myDoc.resolution; console.log(`Doc size is ${width} x ${height}. Resolution is ${resolution}`); ``` -------------------------------- ### Determine Host and OS Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/guides/how-to/index.md Access `uxp.host` to get information about the host application and its UI locale. Use the `os` module to determine the operating system platform. ```javascript const host = require('uxp').host; const locale = host.uiLocale; const hostName = host.name const hostVersion = host.version; const hostOS = require('os').platform(); // note that this is a method, not a property console.log(`locale: ${locale} host ${hostName} version ${hostVersion} running on ${hostOS}`); ``` -------------------------------- ### Create a New Document with Options Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/objects/createoptions/documentcreateoptions.md Use DocumentCreateOptions to specify properties for a new document. The 'name' and 'preset' properties are commonly used for basic document creation. ```javascript const options = { name: "Web mockup", preset: "Web Large" }; require('photoshop').app.createDocument(options); ``` -------------------------------- ### Hide Active Layer Example Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/media/batchplay.md This example demonstrates how to use batchPlay to hide the currently active layer in Photoshop. It requires execution within a modal scope. ```APIDOC ## Hide Active Layer ### Description Hides the currently active layer in the frontmost document. ### Method `action.batchPlay` (within `core.executeAsModal`) ### Endpoint N/A (SDK method) ### Parameters #### Request Body (Descriptors) ```json { "_obj": "hide", "_target": [ { "_ref": "layer", "_enum": "ordinal" }, { "_ref": "document", "_enum": "ordinal" } ] } ``` #### Options An empty object `{}` is used in this example. ### Request Example ```javascript const {app, action, core} = require('photoshop'); async function hideActiveLayer() { return await action.batchPlay([ { _obj: "hide", _target: [ {_ref: "layer", _enum: "ordinal"}, {_ref: "document", _enum: "ordinal"} ] } ], {}); } // Must be executed within a modal scope let result = core.executeAsModal(hideActiveLayer, {commandName: "Hide Layer"}); ``` ### Response #### Success Response Returns an empty array `[]` if successful, as the hide command does not return specific data. ``` -------------------------------- ### UXP Scripting (.psjs files) Source: https://context7.com/adobedocs/uxp-photoshop/llms.txt Details on creating and running standalone `.psjs` scripts directly from Photoshop's File menu, including accessing the DOM and using `executeAsModal` for modifications. ```APIDOC ## UXP Scripting (`.psjs` files) Scripts are standalone `.psjs` files executed directly from Photoshop's File menu, without a panel or manifest. Full DOM API access is available. ```javascript // hello-layers.psjs — run via File > Scripts > Browse const { app, core } = require('photoshop'); // Read-only access works without executeAsModal const doc = app.activeDocument; const names = doc.layers.map(l => `${l.name} (${l.opacity}%)`); await core.showAlert({ message: "Layers:\n" + names.join("\n") }); // Modifications require executeAsModal await core.executeAsModal(async (ctx) => { const newLayer = await doc.createLayer({ name: "Script Layer", opacity: 100 }); newLayer.visible = true; // Write results to a file using UXP storage const { storage } = require('uxp'); const file = await storage.localFileSystem.getFileForSaving("layer-list.txt"); await file.write(names.join("\n")); }, { commandName: "Hello Layers Script" }); ``` ``` -------------------------------- ### batchPlay Error Result Example Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/media/batchplay.md This example shows a successful batchPlay promise resolution that contains an error message. This occurs when a valid command cannot be processed by Photoshop, such as when the target element does not exist. ```javascript [ { _obj: "error" message: "The object “current document” is not currently available." result: -25922 } ] ``` -------------------------------- ### Sample Pixel using batchPlay Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/media/batchplay.md An example of using batchPlay to sample a pixel at a specific coordinate within the active document. This command requires specifying 'samplePoint' as a parameter and must be executed within a modal scope. ```javascript async function samplePixel() { return await action.batchPlay([{ _obj: "colorSampler", _target: {_ref: "document", _enum: "ordinal", _value: "targetEnum"}, samplePoint: { horizontal: 100, vertical: 100 } }], {}); } let result = await core.executeAsModal(samplePixel, {commandName: "Sample Pixel"}); ``` -------------------------------- ### Setting app background color Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/changelog/index.md Demonstrates setting the application's background color using its setter. ```javascript const newColor = new SolidColor(); newColor.rgb = { red: 128, green: 0, blue: 128 }; app.backgroundColor = newColor; ``` -------------------------------- ### Get Document Title with batchPlay Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/media/batchplay.md Use the 'get' action command with a target property to obtain specific state from Photoshop, such as the title of a target document. This requires specifying the property and the target document ID. ```javascript var target = {_ref: [ {_property: "title"}, {_ref: "document", _id: someDocumentID}, {_ref: "application"} ]}; var command = {_obj: "get", _target: target}; let result = await photoshop.action.batchPlay([command], {}); ``` ```javascript [{title: "Untitled-1"}] ``` -------------------------------- ### Add Layer Comp with Options Source: https://github.com/adobedocs/uxp-photoshop/blob/main/src/pages/ps_reference/classes/layercomps.md This example demonstrates how to add a Layer Comp with specific options such as name, comment, visibility, and position. Ensure the 'photoshop' module is required. ```javascript const options = { name: "mockup", comment: "First attempt", visibility: true, position: true }; await require('photoshop').app.activeDocument.layerComps.add(options); ```