### 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 = `