Skip to content

Instantly share code, notes, and snippets.

@mrk21
Last active December 18, 2015 13:09
Show Gist options
  • Save mrk21/5788317 to your computer and use it in GitHub Desktop.
Save mrk21/5788317 to your computer and use it in GitHub Desktop.
Illustrator CS6 の JavaScript でセレクターにマッチする要素を返すjQuery的なものを適当に書いてみた。 誰かちゃんとしたの書いて?
#include "underscore/underscore.js"
function ItemQuery(selectorString) {
var selectorList = _(selectorString.split(/\s+/)).map(function(v){ return v.split('.'); });
var currentSelector = selectorList.pop();
var elements;
if (currentSelector[1]) {
var targets = currentSelector[0] ? [currentSelector[0]] : ItemQuery.TARGETS;
elements = _.chain(targets).map(function(target){
return _(activeDocument[target]).filter(function(v){
return v.name == currentSelector[1];
});
}).flatten();
}
else if (currentSelector[0] == '*') {
elements = _.chain(ItemQuery.TARGETS).map(function(target){
return _.toArray(activeDocument[target]);
}).flatten();
}
else {
elements = _.chain(activeDocument[currentSelector[0]]).toArray();
}
if (selectorList.length > 0) {
elements = elements.map(function(el){
return ItemQuery.checkElement(el, _.clone(selectorList));
});
}
return elements.compact().uniq() || _.chain([]);
}
ItemQuery.checkElement = function(element, selectorList){
var currentElement = element.parent;
currentSelector = selectorList.pop();
while (currentElement) {
var isMatchType = true;
var isMatchName = true;
if (currentSelector[0]) isMatchType = ((currentElement.typename+'s').toLowerCase() == currentSelector[0].toLowerCase());
if (currentSelector[1]) isMatchName = (currentElement.name == currentSelector[1]);
if (isMatchType && isMatchName) {
if (selectorList.length == 0) break;
currentSelector = selectorList.pop();
}
currentElement = currentElement.parent;
}
if (!currentElement || selectorList != 0) return null;
return element;
};
ItemQuery.TARGETS = [
'compoundPathItems','graphItems','groupItems','layers','legacyTextItems','meshItems',
'nonNativeItems','pageItems','pathItems','placedItems','pluginItems','rasterItems','symbolItems','textFrames'
];
$.writeln(ItemQuery('layers.レイヤー1 textFrames').value());
$.writeln(ItemQuery('textFrames.テキスト1').value());
$.writeln(ItemQuery('layers.レイヤー1').value());
$.writeln(ItemQuery('groupItems.グループ1 *').value());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment