Select the top most layer

is it possible to select the top most layer via batchplay?

const batchPlay = require("photoshop").action.batchPlay;
const app = require('photoshop').app;
const currentDocument = app.activeDocument;
const layers = currentDocument.activeLayers;

await batchPlay(
    [{
        "_obj": "select",
        "_target": [{
            "_ref": "layer",
            "_id": currentDocument.layers[0]._id
        }],
        "makeVisible": false,

        "_isCommand": true,
        "_options": {
            // "dialogOptions": "dontDisplay"
        }
    }], {
        "synchronousExecution": false,
        "modalBehavior": "fail"
    });
1 Like

I believe this should be const layers = currentDocument.layerTree; if you really want the top layer and not the first selected one.

And then "_id": layers[0]._id instead of "_id": currentDocument.layers[0]._id, which I think would end in error

1 Like

thanks @Pierre_G and @Karmalakas , I thought there was a way without using the DOM. The purpose was to create a single batchplay. I am using 2.0 api in modal execution and I have noticed that if I use a single batchplay the execution is much faster. unfortunately at the moment the modal execution is too slow for my plugin and I am trying in every way to optimize the code.

There isn’t really much that the DOM API can do which batchPlay can’t, usually it’s the other way round.

Here’s how you’d select the top layer without any DOM API calls:

function __selectByIndex(_index) {
  return {
    _obj: 'select',
    _target: { _ref: 'layer', _index },
  }
}

function getNumberOfLayers() {
  return require("photoshop").action.batchPlay([
    {
      _obj: 'get',
      _target: [{ _ref: 'document', _enum: 'ordinal', _value: 'targetEnum' }],
    },
  ], { synchronousExecution: true })[0]["numberOfLayers"]
}

function __selectTopLayer() {
  return __selectByIndex(getNumberOfLayers())
}

require("photoshop").action.batchPlay([__selectTopLayer()], {})
2 Likes

@simonhenke thank you very much!

From what I experimented with, I see that require(‘photoshop’).app.activeDocument.layers[0]._id does the trick. app.activeDocument.layers gives an array of all layers, and the first index of it is the top one…

You could use this approach too:

   require("photoshop").action.batchPlay(
    [{
      "_obj": "select",
      "_target": [{
        "_ref": "layer",
        "_id": require('photoshop').app.activeDocument.layers[0]._id
      }],
    }], {});
1 Like

Ah, I see. Somehow didn’t encounter this. But anyway require('photoshop').app.activeDocument.layers[0]._id result is exactly the same as layers[0]._id (you already have layers defined and layers[0] is the same layer). Or is it not the layers taht’s used? :smiley: Usage of same names brings quite a bit of confusion :slight_smile: Anyway, issue is solved :wink: