InDesign Conditional Text - Create & apply condition to selected text

Figured I would share this, as I haven’t seen many scripts working with Conditional Text.

This script will apply a condition to selected text in an InDesign document or create and apply a new one, if a condition does not already exist for it. It will also create a new condition set for the condition, if needed.


tell application id "com.adobe.indesign" -- version independent approach 
	tell active document
		activate
		
		--first make sure some text is selected:
		if the selection = {} then
			display dialog "You must first select text to apply condition to." buttons "OK" default button "OK" with icon 0 giving up after 5
			return
		end if
		
		--now show dialog box listing available conditions:
		set theConditions to name of every condition as list
		set theConditions to theConditions & "NEW CONDITION"
		choose from list theConditions with title "Apply condition to selected text:" with prompt "Select condition:"
		copy the result as list to {the conditionName}
		if conditionName = "NEW CONDITION" then
			display dialog "Name of new condition:" default answer "" buttons {"Cancel", "OK"} default button 2
			if (the text returned of the result) ≠ "" then set conditionName to (the text returned of the result)
		end if
		
		--now apply condition, or create a new condition if needed:
		if not (condition conditionName exists) then
			make new condition with properties {name:conditionName, label:"", visible:true}
		end if
		set theCondition to (first condition whose name = conditionName)
		set theConditionID to id of theCondition
		
		set applied conditions of the selection to theCondition
		if not (condition set conditionName exists) then
			make new condition set with properties {name:conditionName, label:"", visible:true}
		end if
		
		set visible of condition id theConditionID of condition set conditionName to true
		redefine condition set conditionName
		
	end tell
end tell

Model: iMac (27-inch, Late 2013)
AppleScript: 10.13.6
Browser: Safari 605.1.15
Operating System: Mac OS X (10.13 Developer Beta 3)

Thanks!