Preview/Print with CSS from Drafts


#1

This action has turned out to be really helpful to me. I originally had some CSS files in Dropbox, but I couldn’t pull the file names into Drafts without adding them to the script manually (as of now). So I thought, why not just maintain the CSS files in Drafts? If you have a few different CSS files you like to use, or if you like to be able to edit the CSS and see the results quickly, this is a whole lot faster than going into the action editor every time.

http://actions.getdrafts.com/a/1JN

    //Process MD with CSS from Drafts "css" tag:
    (() => {
    	const tag = 'css';
    	const draftsFound = Draft.query("", "all", ["css"]);
    	const draftAry = [];

    	//Sort drafts by modified date
    	draftsFound.sort((a, b) => {
    		return a.modifiedAt < b.modifiedAt;
    	});

    	//Create array with draft names and UUID
    	for (let d of draftsFound) {
    		draftAry.push([d.title.replace(/[*\/]/g, '').trim(), d.uuid]);
    	}
    	//Load array in to a Map
    	const draftMap = new Map(draftAry);

    	const p = Prompt.create();
    	p.title = "Choose CSS";
    	p.message = "Pick CSS file to render document"

    	draftMap.forEach((v, k) => {
    		p.addButton(k);
    	});

    	const response = p.show();

    	if (response) {
    		console.log("CSS Draft Title: " + p.buttonPressed);
    		const pickedDraft = draftMap.get(p.buttonPressed);
    		//Get draft CSS contents and load into template
    		if (pickedDraft == draft.uuid) {
    			context.fail("Cannot apply CSS file to itself!");
    		} else {
    			const css = Draft.find(pickedDraft).content;
    			draft.setTemplateTag("css", css);
    		}
    	} else {
    		context.cancel();
    	};
    })();

Inject the CSS into the HTML preview:

    //Simple HTML template
    <!DOCTYPE html>
    <html dir="auto">
    <head>
    <title>[[title]]</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
    [[css]]
    </style>
    </head>
    <body>
      %%[[draft]]%%
    </body>
    </html>

It’s been great so far. I’m absolutely loving drafts!

Nick