You’re right @eskaybee875,
my fault, sorry.
I have a little different setup, so the error probably crept in, when I edited the code in the forum reply to match Your setup.
You can also remove the constants
assignment, since it’s never being used (a leftover from my script setup).
psAction
, psApp
, psCore
, etc. are basically just name aliases of the properties that belong to the required photoshop
instance.
I prefer using aliases, because it makes clear to me, what core
for example I’m jusing in my script.
You could also just stick to declaring the photoshop constants like this:
const { action, app, constants, core } = photoshop;
and use them in Your script.
So instead of writing
photoshop.core.doSomething()
each and eveytime again, You just need to write
core.doSomething()
Just log photoshop
to the console and You’ll see, what properties exist.
The documentation is also very helpful.
Also, if I may suggest, read a few javascript basics (MDN as a great documention) to better understand what You’re doing.
AI is not always very helpful to understand the basics, but that’s of course just my opinion.
You probably should do some more edge case testing (I didn’t do that very extensively), like what if a layer name already has some weird characters or the name ends with sth like artboard_nr°666_1200x300x340
?
Maybe You want another delimiter, like a double underscore __
, an emoji 💩
or whatever. I know, it’s probably unlikely, but You never know! =)
I’d also recommend, to keep the comments in Your code, because its much easier to understand what happens if You come back in a few months and need to tweak it again.
Anyway, I’m not sure, if my solution is the most elegant – I feel like I have so much to learn – and I’m always happy about suggestions, too.
I’m glad that it works for You now.
Happy coding! =)
EDIT: I can’t edit my original reply anymore, so here is the corrected code:
// Require everything we need to execute our function.
// Do this once outside Your function. You don't need to require
// everything again with each function call.
const photoshop = require("photoshop");
const { core: psCore, action: psAction, app: psApp } = photoshop;
const { batchPlay } = psAction;
// The delimiter for Your artboard names.
// We use this, to also replace old artboard dimensions, in case
// any of them get resized.
const DELIMITER = "_";
// A button to call the `rename` function.
const dimensionsButtonEl = document.getElementById("artboard-suffix-btn");
// If button exists, add a click listener with the `renameArtboards`
// callback function.
dimensionsButtonEl?.addEventListener("click", renameArtboards);
/**
* Returns the bounds of an artboard.
*
* @return {Object}
*/
const getArtboardRect = async (docID, artboardID) => {
if (!docID || !artboardID) {
throw new Error('Please provide a document ID and an ' +
'artboard ID');
}
// `batchPlay` requires an array, so it will return an array.
// Store it in the `result` variable.
const result = await batchPlay(
[
{
_obj: "get",
_target: [
{
_property: "artboard",
},
{
_ref: "layer",
_id: artboardID,
},
{
_ref: "document",
_id: docID,
},
],
_options: {
dialogOptions: "dontDisplay",
},
},
],
{}
);
// Return the artboard prop from the first array item of the
// result.
return result[0].artboard.artboardRect;
};
/**
* Helper to escape regex.
* @src: https://stackoverflow.com/a/3561711
*/
function escapeRegex(string) {
return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
}
/**
* Gets dimensions of all artboards of the document
* and appends them to their name in the layers panel.
*
* @return {void}
*/
const renameArtboards = async () => {
try {
await psCore.executeAsModal(async () => {
// Get the active Document right away.
const activeDoc = psApp.activeDocument;
// Get all artboards of the document.
const artboards = activeDoc.artboards;
// Loop through all artboards.
for (let i = 0; i < artboards.length; i++) {
const artboard = artboards[i];
// Get bounds for this artboard.
const artboardRect = await getArtboardRect(
activeDoc.id, artboard.id
);
// Calculate width and height from bounds.
const artboardW = artboardRect.right - artboardRect.left;
const artboardH = artboardRect.bottom - artboardRect.top;
// Get artboard name before renaming.
const oldArtboardName = artboard.name;
// Create a variable for the new name.
let newName = oldArtboardName;
// Some regex magic to get a sizes pattern, i.e. `_1920x1080`.
// If we have a match, we know, the layer already has a suffix,
// so we can replace it with the actual dimensions.
// By escaping the delimiter, we should be able to use any
// character that we like.
const p = escapeRegex(DELIMITER) + '\\d+\\s*x\\s*\\d+(?:\\s*x\\s*\\d+)?';
const rE = new RegExp(p, 'g');
// Extract last occurrence of old suffix from artboard
// name and also remove `DELIMITER` from string.
const oldSize = oldArtboardName
?.match(rE)
?.pop()
.slice(DELIMITER.length);
// Also remove old suffix from artboard name.
if(oldSize) {
newName = newName.slice(0, -(oldSize.length + DELIMITER.length))
}
// Build the new size string.
const newSize = `${artboardW}x${artboardH}`
// Size didn't change, don't need to rename anything,
// so skip to next artboard.
if(newSize === oldSize) {
console.log(`Nothing changed for artboard '${newName}'.`)
continue;
};
// Concatenate everything into a new string.
artboard.name = `${newName}${DELIMITER}${newSize}`;
}
}, {
commandName: "Rename Artboard"
});
} catch (e) {
console.error("[addSuffix]:\n", e);
// Display the error to the user
// psApp.showAlert(`An error occurred: ${e.message}`);
}
};