Sometimes in ActionManager we need to get the structure of all layers of a document, taking into account the relative arrangement of layers and nested groups. I came across this task several times, but could not find a suitable solution and turned to the DOM functions.
Maybe someone will come in handy my solution to this problem using recursive function:
#target photoshop
s2t = stringIDToTypeID;
t2s = typeIDToStringID;
(r = new ActionReference()).putProperty(s2t('property'), p = s2t('hasBackgroundLayer'));
r.putEnumerated(s2t('document'), s2t('ordinal'), s2t('targetEnum'))
var indexFrom = executeActionGet(r).getBoolean(p) ? 0 : 1;
(r = new ActionReference()).putProperty(s2t('property'), p = s2t('numberOfLayers'));
r.putEnumerated(s2t('document'), s2t('ordinal'), s2t('targetEnum'))
var indexTo = executeActionGet(r).getInteger(p);
var layers = {}
parseLayerSets(indexFrom, indexTo, layers)
function parseLayerSets(from, to, parentObj) {
for (var i = from; i <= to; i++) {
(r = new ActionReference()).putProperty(s2t('property'), p = s2t('layerSection'));
r.putIndex(s2t("layer"), i)
var section = t2s(executeActionGet(r).getEnumerationValue(p))
if (section == 'layerSectionEnd') {
i = parseLayerSets(i + 1, to, parentObj[i] = {})
continue;
}
// get prorerties of layer here and put it to object
var properties = {};
(r = new ActionReference()).putProperty(s2t('property'), p = s2t('layerID'));
r.putIndex(s2t("layer"), i);
properties.id = executeActionGet(r).getInteger(p);
(r = new ActionReference()).putProperty(s2t('property'), p = s2t('name'));
r.putIndex(s2t("layer"), i);
properties.name = executeActionGet(r).getString(p)
if (section == 'layerSectionStart') {
for (o in properties) { parentObj[o] = properties[o] }
return i;
} else { parentObj[i] = properties }
}
}
(if someone has a better solution, I will be glad if you publish it)