Action

Select Tagged Draft

Posted by @mattgemmell, Last update over 4 years ago

Allows choosing from a list of drafts whose tags conform to the expression:
(a AND b AND c) AND (x OR y OR z)

(Edit the Define Template Tag step to specify tags to filter the list of drafts.)

Steps

  • defineTemplateTag

    name
    tag_filter
    template
    AND: dev
    OR: ideas documentation
  • script

    var rawTags = draft.getTemplateTag("tag_filter");
    
    var requiredTags = [], optionalTags = [];
    var tagsMatch = rawTags.match(/AND:\s*(.+)\s*/i);
    if (tagsMatch) {
    	requiredTags = tagsMatch[1].trim().toLowerCase().split(/\s+/);
    }
    
    tagsMatch = rawTags.match(/OR:\s*(.+)\s*/i);
    if (tagsMatch) {
    	optionalTags = tagsMatch[1].trim().toLowerCase().split(/\s+/);
    }
    
    // Get drafts with the required tags.
    var candidateDrafts = Draft.query("", "all", 
    												requiredTags, [], 
    												"accessed", true, false);
    
    // Exclude those without at least one of the optional tags.
    var matchingDrafts = [];
    for (var thisDraft of candidateDrafts) {
    	for (var tag of optionalTags) {
    		if (thisDraft.tags.includes(tag)) {
    			matchingDrafts.push(thisDraft);
    			continue;
    		}
    	}
    }
    
    if (matchingDrafts.length > 0) {
    	var p = Prompt.create();
    	p.title = "Choose a Draft to Open";
    	p.message = requiredTags.join(" AND ") + "\nAND (" + optionalTags.join(" OR ") + ")";
    	
    	let ix = 0;
    	for (var thisDraft of matchingDrafts) {
    		p.addButton(thisDraft.displayTitle, ix);
    		ix++;
    	}
    	
    	if (p.show()) {
    		var selectedIndex = p.buttonPressed;
    		editor.load(matchingDrafts[selectedIndex]);
    	}
    	
    } else {
    	app.displayInfoMessage("No drafts match the criteria.");
    }

Options

  • After Success Default
    Notification Info
    Log Level Info
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.