Script: Sort selected Graphics by Name


#1

Hello!

Here is a little script to sort all selected graphics by its name.

// COPY & PASTE into editor app. EDIT & SAVE with “.omnijs” file extension.
/*{
 "type": "action",
 "targets": ["omnigraffle"],
 "author": "Gerd Weckenmann",
 "identifier": "com.gwecken.SortSelectedGraphicsByName",
 "description": "Sorts the selected graphics by name.",
 "label": "Sort Selected Graphics by Name",
 "paletteLabel": "Sort Selected Graphics by Name"
}*/
var _ = function(){
    var action = new PlugIn.Action(function(selection, sender){
	// action code
	// selection options: canvas, document, graphics, lines, solids, view

//	log('Operate on Canvas: ' + selection.canvas.name)

	// skip graphics with name = null
	graphics = selection.graphics.filter(graphic => graphic.name != null)

//	log('Selected Graphics:')
//	graphics.forEach(function(gfx){log(gfx.name + '(' + gfx.id + ',' + gfx.layer.name + ')')})

	// create setOfLayers
	let setOfLayers = new Set()
	graphics.forEach( function(graphic) { setOfLayers.add(graphic.layer) } )

//	log('SetOfLayers:')
//	setOfLayers.forEach( function(layer) { log(layer.name) } )

	// loop over layers
	for (let layer of setOfLayers)
	{
//		log('Operate on Layer:' + layer.name)

		// filter graphics of layer and store in Array
		let graphicsOfLayer = new Array()
		graphicsOfLayer = graphics.filter(graphic => graphic.layer == layer)

//		log('-> before sort')
//		for (let graphic of graphicsOfLayer)
//			log(graphic.name + '(' + graphic.id + ',' + graphic.layer.name + ')')

		// sort graphicsOfLayer Array by graphic.name
		graphicsOfLayer.sort(function (a, b) {
//			log('a=' + a.name + ', b=' + b.name + '->' + (a.name.localeCompare(b.name)))
			return a.name.localeCompare(b.name)
		} )

//		log('-> after sort')
//		for (let graphic of graphicsOfLayer)
//			log(graphic.name + '(' + graphic.id + ',' + graphic.layer.name + ')')

		// loop over graphics and reorder
		firstGraphic = graphicsOfLayer.shift(); // shift first graphic out of array
//		log('firstGraphic:' + firstGraphic.name + '(' + firstGraphic.id + ',' + firstGraphic.layer.name + ')')
		graphicsOfLayer.reverse() // reverse
		for (let graphic of graphicsOfLayer)
		{
			graphic.orderBelow(firstGraphic)
//			log('orderBelow:' + firstGraphic.name + ' above ' + graphic.name)
		}

//		log('-> after reorder')
//		graphicsOfLayer.reverse() // reverse
//		graphicsOfLayer.unshift(firstGraphic)
//		for (let graphic of graphicsOfLayer) {
//			log(graphic.name + '(' + graphic.id + ',' + graphic.layer.name + ')')
//		}
	}

	});

	action.validate = function(selection, sender){
		// validation code
		// selection options: canvas, document, graphics, lines, solids, view
		if(selection.graphics.length > 0){return true} else {return false}
	};

	return action;
}();
_;

function log(txt) {console.log(txt)}