Writing a script to add a note to Bear app

@martinperry

This will not abort current script, only abort other action steps that might be following this one.

Try to wrap the script in a self-invoking function.
Then you can abort script gracefully by adding return; after context.cancel(); :

(() => {
  ...
  if (p.show() === false) { 
    context.cancel(); 
    return;
  }
  ...
})()

// or if you want it less anonymous:

(function main() {
  ...
  if (p.show() === false) { 
    context.cancel();
    return;
  }
  ...
})()

Wrapping scripts in a function also stops variables for being global and leaking over to other script steps coming later in the same action. Global vars are accessible to other script steps in same Drafts action, which is great when you want to pass results from one step to another. Just read on this forum, thanks to @draft8

I also just learned in same tread that it will make your scripts run faster. See: js-simpler-interactions-between-2-or-more-script-steps

	cb.addParameter("add-text")
	cb.addParameter("create")

Are not valid parameters for Bear x-callback.
Do this instead:

...

let cb = CallbackURL.create();

switch (p.buttonPressed) {
  case "Append to note":
    cb.baseURL = "bear://x-callback-url/add-text";
    break;
  case "Create a new note":
    cb.baseURL = "bear://x-callback-url/create";
    break;
}

cb.addParameter("text", draft.processTemplate("[[draft]]"));

...

Have a look at the complete action: Create or Append draft in Bear, which also shows nesting of prompts.

Adding files to bear in your draft script will be quite difficult I believe.

Probably easier to open bear with a new url action step after this script, and then paste file (copied from Finder, macOS) or insert directly in Bear editor (using the paperclip icon, iOS)

Therefore the file fields and steps have been commented out. (It might be possible, but it’s above my paygrade;)

Hope that’s helpful.

2 Likes