Action

Insert Local Image Ref

Last update over 3 years ago

Opens a preview window allowing you to select from images stored in the iCloud Drive/Drafts/Library/Previews/images folder, and insert a Markdown image reference to one of those images which will work in previews.

Learn more about using local assets in preview.

Steps

  • script

    // Configure variables
    
    // set to subdirectory of `iCloud Drive/Drafts/Library/Previews` folder containing images
    let imagesPath = "images/";
    
    let basePath = "Library/Previews/";
    let [st, len] = editor.getSelectedRange();
    
    let template = `<html>
    <head>
    
    <style>
    img {
      max-height: 120px;
      max-width: 120px;
    }
    ul {
    	list-style-type: none;
    	margin: auto;
    	width: 80%;
    	text-align: center;
    }
    li {
    	margin: 1em;
    }
    html {
       font-size: 100%;
       font-family: -apple-system, "helvetica neue", sans-serif;
       line-height: 1.4em;
       text-align: center;
    }
    a {
       text-decoration: none;
       padding: .5em 1em;
       background: #efefef;
       border-radius: 3px;
       display: block;
    }
    </style>
    
    <script>
    function select(img) {
    	Drafts.send("img", img);
    	Drafts.continue();
    	return false;
    }
    </script>
    
    </head>
    <body>
    
    <h2>Select Image to Insert Markdown Reference</h2>
    
    <p>
    <a href="#" onclick="Drafts.cancel();return false;">Cancel</a>
    </p>
    
    [[imageList]]
    
    </body>
    </html>
    `;
  • script

    let f = () => {
    	let fm = FileManager.createCloud();
    	let images = fm.listContents(`${basePath}${imagesPath}`);
    	
    	if (images.length == 0) {
    		alert("Place images in the `iCloud Drive/Drafts/Library/Previews/images` folder to use this action");
    		return false;
    	}
    		
    	let h = ["<ul>"];
    	for (let img of images) {
    		let trimmed = img.replace(basePath, "");
    		h.push("<li>");
    		h.push(`<a href='#' onclick='select("${trimmed}")'>`);
    		h.push(`<img src="${trimmed}" alt="${trimmed}">`);
    		h.push("</a>");
    		h.push("</li>");
    	}
    	h.push("</ul>"); 
    	draft.setTemplateTag("imageList", h.join("\n"));
    	
    	let html = draft.processTemplate(template)
    	let preview = new HTMLPreview();
    	preview.hideInterface = true;
    	if (!preview.show(html)) {
    		return false;
    	}
    	
    	let selected = context.previewValues["img"];
    	if (selected) {
    		let markup = `![${selected}](${selected})`
    		editor.activate();
    		editor.setSelectedText(markup);
    		editor.setSelectedRange(st, markup.length);
    	}
    	else {
    		return false;
    	}
    }
    
    if (!f()) {
    	context.cancel();
    }

Options

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