<!doctype html> Bookmark | Drafts Script Reference

Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Bookmark

Bookmark objects are used to work with folder bookmarks and the FileManager object to provide access to folders outside the Drafts App Sandbox. Bookmarks are unique by name. A user-friendly name should be used, as the first time a bookmark is required, the user is prompted to select the folder in their file system to associate with the bookmark, and a useful name can help guide them to selecting the correct folder.

Learn more about Bookmarks in the User Guide

Example

// find or create a named Bookmark
let bookmark = Bookmark.findOrCreate("My-Folder");
let fm = FileManager.createForBookmark(bookmark);

// write to a file at the root of the bookmark folder let success = fm.writeString("/ScriptedFile.txt", "This is the file * content");

// read from file in bookmarked folder let content = fm.readString("/Test Folder/Test.txt")

Hierarchy

  • Bookmark

Index

Properties

Methods

Properties

Readonly name

name: string

The name of the bookmark.

Methods

forget

  • forget(): any
  • Forget the bookmark, resetting any associated permissions. Generally, this would be a function the user performs in the user interface, but could be useful in the case of an action which wishes to request and use a one-time bookmark and revoke permissions on completion of an action.

    Returns any

Static findOrCreate

  • Get a bookmark object with the specified name. If no bookmark with the specified name exists, a new one will be created.

    Parameters

    • name: string

    Returns Bookmark

Generated using TypeDoc

--- Credential | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Credential

Credential objects can be used in actions which require the user to provide a username, password and optionally a host name, to connect to a service. By using credentials objects, actions can be written to connect to arbitrary web services without hard coding credentials into the action.

When an authorize() call is made on a credential object for the first time, the user is prompted to enter their credentials, then Drafts stores those for later use. When the action is used again, there will be no prompt required and the stored credentials will be used.

Credentials objects have unique identifiers, and a single set of user credentials can be used across actions by using the same identifier.

The user can delete those credentials at any time by visiting Settings > Credentials and tapping the "Forget" button on a service.

Example

var credential = Credential.create("My Service", "Description of the service to  * appear in user prompt.");

credential.addTextField("username", "Username"); credential.addPasswordField("password", "Password");

credential.authorize();

var http = HTTP.create(); var response = http.request({ "url": "http://myurl.com/api", "username": credential.getValue("username"), "password": credential.getValue("password"), "method": "POST", "data": { "key":"value" }, "headers": { "HeaderName": "HeaderValue" } });

Hierarchy

  • Credential

Index

Constructors

constructor

  • new Credential(identifier: string, description?: string): Credential
  • Create new instance.

    Parameters

    • identifier: string

      Unique identifier for the credentials

    • Optional description: string

      Optional description

    Returns Credential

Methods

addPasswordField

  • addPasswordField(key: string, label: string): void
  • Add a secure entry text field for data entry.

    Parameters

    • key: string

      used to retrieve the value

    • label: string

      label is displayed to the user

    Returns void

addTextField

  • addTextField(key: string, label: string): void
  • Add a text field for data entry.

    Parameters

    • key: string

      used to retrieve the value

    • label: string

      label is displayed to the user

    Returns void

addURLField

  • addURLField(key: string, label: string): void
  • Add a text field for configured for URL data entry.

    Parameters

    • key: string

      used to retrieve the value

    • label: string

      label is displayed to the user

    Returns void

authorize

  • authorize(): boolean
  • Call this function after configuring, but before using host, username or password properties of a credential. If the credential object has not be previous authorized, the user will be prompted to enter their credentials before continuing. If the user has previously been prompt, this method will load previously provided information.

    Returns boolean

forget

  • forget(): void
  • Deletes the credentials provided by the user. This is the same as the user visiting settings and tapping "Forget" for the credentials.

    Returns void

getValue

  • getValue(key: string): string
  • Get the value the user stored for the key, as defined in a call to add the field.

    Parameters

    • key: string

    Returns string

Static create

  • create(identifier: string, description?: string): Credential
  • Create a credential object with the specified identifier and description. Identifiers should be unique, such that any two calls from different actions with the same identifier will return the same credentials

    Parameters

    • identifier: string

      Unique identifier for the credentials

    • Optional description: string

      Optional description

    Returns Credential

Static createWithHostUsernamePassword

  • createWithHostUsernamePassword(identifier: string, description: string): Credential
  • Create credential already configured with host url, username and password fields.

    Parameters

    • identifier: string

      Unique identifier for the credentials

    • description: string

      Optional description

    Returns Credential

Static createWithUsernamePassword

  • createWithUsernamePassword(identifier: string, description: string): Credential
  • Create credential already configured with username and password fields.

    Parameters

    • identifier: string

      Unique identifier for the credentials

    • description: string

      Optional description

    Returns Credential

Generated using TypeDoc

--- Calendar | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Calendar

Calendar objects are used to manipulate and create calendars in the built-in Calendars app and its associated accounts.

Example: Event Creation

var calendar = Calendar.findOrCreate("Activities");
var event = calendar.createEvent();
event.title = "Dinner Party";
event.notes = "Bring side dish.";
event.startDate = Date.parse("7pm next friday");
event.endDate = Date.parse("10pm next friday");
event.isAllDay = false;
if (!event.update()) {
  console.log(event.lastError);
}

Example: Reading Calendar Events

// load a calendar
let cal = Calendar.find("Test");
// loop over events in the last 30 days and alert the name of each.
if (cal) {
    let events = cal.events((30).days().ago(), new Date());
    for (let event of events) {
        alert(event.title);
    }
}

Hierarchy

  • Calendar

Index

Properties

allowsContentModificationx

allowsContentModificationx: boolean

A Boolean value that indicates whether you can add, edit, and delete items in the calendar.

isImmutable

isImmutable: boolean

A Boolean value indicating whether the calendar’s properties can be edited or deleted.

title

title: string

Methods

createEvent

events

  • events(startDate: Date, endDate: Date): Event[]
  • Returns array of events on the calendar between the start and end dates specified.

    Parameters

    • startDate: Date
    • endDate: Date

    Returns Event[]

update

  • update(): boolean

Static default

Static find

  • find(title: string): Calendar | undefined
  • Searches for a calendar matching the title. If none is found, return undefined.

    Parameters

    • title: string

    Returns Calendar | undefined

Static findOrCreate

  • Searches for a calendar matching the title. If none is found, creates a new list with that title in your default calendars account. If more than one calendar with the same name exist in Calendars, the first found will be returned.

    Parameters

    • title: string

    Returns Calendar

Static getAllCalendars

Generated using TypeDoc

--- CallbackURL | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class CallbackURL

CallbackURL objects can be used to open x-callback-url requests and wait for a response from the target app.

NOTE: If you want to open a URL in Safari or another app and do not need a response or x-callback-url support, use the app.openURL(url) method on the App object.

Example

// Open callback URL for each line in a draft
// Setup base Fantastical URL, with no parameters
const baseURL = "fantastical2://x-callback-url/parse/";

// split draft and loop over lines var lines = draft.content.split("\n"); for (var line of lines) { // create and configure callback object var cb = CallbackURL.create(); cb.baseURL = baseURL; cb.addParameter("sentence", line); // open and wait for result var success = cb.open(); if (success) { console.log("Event created"); } else { // something went wrong or was cancelled console.log(cb.status); if (cb.status == "cancelled") { context.cancel(); } else { context.fail(); } } }

Hierarchy

  • CallbackURL

Index

Constructors

constructor

Properties

baseURL

baseURL: string

The baseURL of the request. This should include the x-callback-url base URL and action, typically something like app-scheme://x-callback-url/actionName

callbackResponse

callbackResponse: {}

An object contain and URL query parameters returned by the target app along with it’s callback response. For example, if the target app called x-success with the query parameters result=MyTestText, callbackResponse would contain {"result": "MyTestText"}.

Type declaration

  • [x: string]: any

parameters

parameters: {}

Object containing string keys and values to be appended to the base url as query parameters. Values should not be pre-encoded, but will be encoded and added to the base URL automatically. Do not include x-callback parameters (x-success, x-error, x-cancel) as these will be generated by Drafts.

Type declaration

  • [x: string]: any

status

status: "created" | "success" | "cancelled" | "error" | "timeout" | "invalid"

The current status of the callback. Used to check outcome after open is called. Possible values:

  • created: open has not yet been called.
  • success: x-success callback was received from target app.
  • cancelled: x-cancel callback was received from target app.
  • error: x-error callback was received from target app.
  • timeout: Waiting for the response timed out without receiving a callback URL from the target app.
  • invalid: The URL was invalid and could not be opened.

url

url: string

The current URL. This is provided as a debugging property, and will output the URL including the baseURL property with any configured parameters added. This property will differ from the actual URL opened when calling open() in that it will not contain the x-success, x-error and x-cancel parameters which are added dynamically at the time open() is called.

waitForResponse

waitForResponse: boolean

If true, the script will pause and wait for the x-success, x-error or x-cancel response from the app being targeted by the URL. If false, execution of the script/action will continue immediately and no response/results will be available.

Methods

addParameter

  • addParameter(key: string, value: any): void
  • Add a query parameter for the outgoing URL. FIXME: can the value be anything?

    Parameters

    • key: string
    • value: any

    Returns void

open

  • open(): boolean
  • Opens the URL with associated parameters, and waits for a callback response. Returns true if an x-success response was received from the target app, otherwise false. If false, use the "status" property to determine the type of failure.

    Returns boolean

Static create

Generated using TypeDoc

--- Context | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Context

A single global "context" object is available to scripts to control flow of the currently running action.

It is important to understand that cancel() and fail() will not immediately stop script, just stop any further action steps from being performed.

Example: Control Flow

// test for logical condition before continuing
if (!validationCondition) {
  context.fail();
}
// code below will still run.

Example: Retreive values

// if a "Run Workflow" step preceded this script, lets look for a result
var response = context.callbackResponses[0];
if (response) {
  // Workflow returns one "result" parameter, other apps may use other values.
  var result = response["result"];
  if (result) {
    // so something with the result
  }
}

Hierarchy

  • Context

Index

Properties

appleScriptResponses

appleScriptResponses: {}

If AppleScripts run using the AppleScript object return values, they will be converted to JavaScript object and stored in this array. See AppleScript docs for details.

Type declaration

  • [x: string]: any

callbackResponses

callbackResponses: {}

If Callback URL or Run Shortcut action steps using the "Wait for response" option have been run in steps before the script step in an action, and the target app returned to Drafts using an x-success callback, this object will contain an array of objects with the parsed query parameters included in those responses, in the order they were received.

Type declaration

  • [x: string]: any

previewValues

previewValues: { string: any }

If HTML Preview makes calls to Drafts.send(key, value) those values are stored in this object by key.

Type declaration

  • string: any

Methods

addSuccessParameter

  • addSuccessParameter(name: string, value: string): void
  • Used only when calling a Drafts action from another app via x-callback-url with a /runAction URL. Any parameters set via this method will be included as query args when calling the provided x-success parameter. As an example, the below:

    context.addSuccessParameter("a", "1");
    context.addSuccessParameter("b", "2");
    

    Would result in the parameters ?a=1&b=2 being added to the x-success callback.

    Parameters

    • name: string

      The name for the parameter

    • value: string

      A string value for the parameter. Do not URL encode this value, it will be encoded when added to the callback URL.

    Returns void

cancel

  • cancel(message: string): void
  • Tell the context to cancel the action at the end of the script execution. If called, at the end of the script the action will be stopped. No subsequent action steps in the action will run, and the action still stop silently - no notification banners, sounds, etc. If a message is included it will be added to the action log to explain the cancellation.

    Parameters

    • message: string

    Returns void

fail

  • fail(message: string): void
  • Tell the context to fail the current action. In effect this is the same as cancel() but an error notification will be shown. If a message is included it will be added to the action log to explain the cancellation.

    Parameters

    • message: string

    Returns void

Generated using TypeDoc

--- Dropbox | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Dropbox

Dropbox objects can be used to work with files in a Dropbox account. The read and write methods are simple wrappers for uploading and reading content of files on Dropbox.

For advanced uses, the rpcRequest, contentUploadRequest and contentDownloadRequest methods enable direct use of any Dropbox API 2.0 endpoints. These methods are an advanced feature which return raw results from the Dropbox API and may require advanced understanding of the API to process the results. They do enable full access to the API, however, which enabled things like querying files, listing folder contents, uploading to Paper, etc. For details on availalbe methods, see Dropbox API documentation. In the case of all of these methods Drafts takes care of the OAuth request signing and authentication process when necessary.

Example

// create Dropbox object
var db = Dropbox.create();

// setup variables var path = "/test/file.txt"; var content = "text to place in file";

// write to file on Dropbox var success = db.write(path, content, "add", true);

if (success) { // write worked! var dbContent = db.read(path); if (dbContent) { // read worked! if (dbContent == content) { alert("File contents match!"); } else { console.log("File did not match"); context.fail(); } } else { // read failed, log error console.log(db.lastError); context.fail(); } } else { // write failed, log error console.log(db.lastError); context.fail(); }

Hierarchy

  • Dropbox

Index

Constructors

constructor

  • new Dropbox(identifier?: string): Dropbox

Properties

lastError

lastError: string | undefined

If a function fails, this property will contain the last error as a string message, otherwise it will be undefined.

Methods

contentDownloadRequest

  • Execute a request against the Dropbox API for an endpoint of Content Download type. For successful requests, the HTTPResponse object will contain an raw data in the responseData property and, if the data can be converted to a string value, the text version in the responseText property. The HTTPResponse otherData property will contain a Javascript object decoded from the JSON returned in the Dropbox-API-Result header. Refer to Dropbox's API documentation for details about the expected parameters and responses. Drafts will handle wrapping the request in the appropriate OAuth authentication flow.

    Parameters

    Returns HTTPResponse

contentUploadRequest

  • Execute a request against the Dropbox API for an endpoint of Content Upload type. For successful requests, the HTTPResponse object will contain an object or array or objects decoded from the JSON returned by Dropbox as appropriate to the request made. Refer to Dropbox's API documentation for details about the expected parameters and responses. Drafts will handle wrapping the request in the appropriate OAuth authentication flow.

    Parameters

    Returns HTTPResponse

read

  • read(path: string): string | undefined
  • Reads the contents of the file at the with the file name, in the parent folder, as a string. Returns undefined value if the file does not exist or could not be read.

    Parameters

    • path: string

      Path related to root of Dropbox folder.

    Returns string | undefined

rpcRequest

  • Execute a request against the Dropbox API for an endpoint of RPC type. For successful requests, the HTTPResponse object will contain an object or array or objects decoded from the JSON returned by Dropbox as appropriate to the request made. Refer to Dropbox's API documentation for details about the expected parameters and responses. Drafts will handle wrapping the request in the appropriate OAuth authentication flow.

    Parameters

    Returns HTTPResponse

write

  • write(path: string, content: string, mode: dropboxMode, autorename: boolean): boolean
  • Write the contents of the file at the path. Returns true if successful, false if the file could not be written successfully. This will override existing files!

    Parameters

    • path: string

      Path related to root of Dropbox folder.

    • content: string

      Text to write to file.

    • mode: dropboxMode

      Either "add" or "overwrite" to determine if the write method should overwrite an existing file at the path if it exists.

    • autorename: boolean

    Returns boolean

Static create

  • create(identifier?: string): Dropbox
  • Creates a new Dropbox object.

    Parameters

    • Optional identifier: string

      used to identify a Dropbox account. Typically this can be omitted if you only work with one Dropbox account in Drafts.

    Returns Dropbox

Generated using TypeDoc

--- Editor | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Editor

A global editor object is available in all action scripts. This object allows manipulation of the main editing window in Drafts, altering the text, text selections, or loading a different draft into the editor, etc.

Typically scripting actions that work like custom keyboard commands and similar will utilize the editor functions to manipulate text.

NOTE: Generally speaking, editor methods are best used for quick text manipulations of the type used in the extended keyboard. Most substantial updates to draft content are better applied using the draft object.

Hierarchy

  • Editor

Index

Deprecated Properties

focusModeEnabled

focusModeEnabled: boolean
deprecated

replaced by pinningEnabled.

Other Properties

isActive

isActive: boolean

Is editor current focused for editing.

linkModeEnabled

linkModeEnabled: boolean

Access or set current link mode status.

navigationMarkers

navigationMarkers: []

Array of navigation markers in the text. Navigation markers are defined by the syntax definition in use in the editor, and are used in the Navigation feature.

pinningEnabled

pinningEnabled: boolean

Access or set current pinning status for editor.

preferredTabString

preferredTabString: string

Returns the current tab string is use. This could be 2 spaces, 4 spaces, or \t depending on the editor preferences for the current syntax. Useful in actions, such as indent/outdent actions, which need to insert or remove indentation and want to match the options of the current syntax.

recentDrafts

recentDrafts: []

Array of recent drafts. This is the same list as used in the navigation features of the editor, and is in reverse order, so that the first index in the array is the previous draft loaded in the editor.

typewriterScrollingEnabled

typewriterScrollingEnabled: boolean

Access or set current typewriter scrolling status.

Methods

activate

  • activate(): void
  • Request focus for the editor. This will dismiss other views and show the keyboard on the currently loaded draft. Useful if an action opens user interface elements or otherwise causes the editor to resign focus and you would like to return to editing at the end of the action's execution.

    Returns void

arrange

  • arrange(text: string): string
  • Opens the arrange mode view with the passed text for arranging. Returns the arranged text if the user makes changes and taps "Done", the original text if the user cancels.

    Parameters

    • text: string

      The text to arrange

    Returns string

    String containing result of arrange. If user cancels, it will be the same as the original text passed.

deactivate

  • deactivate(): void
  • Resign focus for the editor. If the editor text view is currently focused for editing (e.g. showing keyboard), resign focus.

    Returns void

dictate

  • dictate(locale?: string): string
  • Open dictation interface, and return the result as a string. The string will be empty if user cancels.

    Parameters

    • Optional locale: string

      the preferred locale can be passed in the format "en-US" (U.S. English), "it-IT" (Italian-Italian), "es-MX" (Mexican Spanish), etc.

    Returns string

    The accepted dictation text.

getLineRange

  • Expand the range provided to the nearest beginning and end of the lines it encompasses.

    Parameters

    • location: number
    • length: number

    Returns selectionRange

getSelectedLineRange

  • Get the current selected text range extended to the beginning and end of the lines it encompasses.

    Returns selectionRange

getSelectedRange

getSelectedText

  • getSelectedText(): string
  • Get text range that was last selected.

    Returns string

getText

  • getText(): string
  • Get the full text currently loaded in the editor.

    Returns string

getTextInRange

  • getTextInRange(location: number, length: number): string
  • Get the substring in a range from the text in the editor.

    Parameters

    • location: number
    • length: number

    Returns string

load

  • load(draft: Draft): void
  • Loads an existing draft into the editor.

    Parameters

    Returns void

navigationMarkerAfter

  • The next navigation marker in the editor, relative to the character location. This is a convenience method to assist in navigating by marker.

    Parameters

    • location: number

    Returns navigationMarker

navigationMarkerBefore

  • The previous navigation marker in the editor, relative to the character location. This is a convenience method to assist in navigating by marker.

    Parameters

    • location: number

    Returns navigationMarker

new

  • new(): void
  • Creates a new blank draft and loads it into the editor.

    Returns void

redo

  • redo(): void
  • Apply redo action to editor, if one is available.

    Returns void

save

  • save(): void
  • Save any current changes to the draft.

    Returns void

scanDocument

  • scanDocument(): string
  • Open document scanning camera to scan documents and OCR, returning the result as a string. The string will be empty if user cancels, or document scanning is not available.

    Returns string

    The text recognized in the OCR of the scanned document.

setSelectedRange

  • setSelectedRange(location: number, length: number): void
  • Update the text selection in the editor by passing the start location and the length of the new selection.

    Parameters

    • location: number
    • length: number

    Returns void

setSelectedText

  • setSelectedText(text: string): void
  • Replace the contents of the last text selection with a string.

    Parameters

    • text: string

    Returns void

setText

  • setText(text: string): void
  • Replace the contents of the editor with a string.

    Parameters

    • text: string

    Returns void

setTextInRange

  • setTextInRange(location: number, length: number, text: string): void
  • Replace the text in the passed range with new text.

    Parameters

    • location: number
    • length: number
    • text: string

    Returns void

showArrange

  • showArrange(): void
  • Open arrange mode in editor. This is a non-blocking method and returns immediately. It is intended only to mimic the tapping of the arrange button. Use editor.arrange(text) to wait for a result.

    Returns void

showDictate

  • showDictate(): void
  • Open dictation mode in editor. This is a non-blocking method and returns immediately. It is intended only to mimic the tapping of the dictate button. Use editor.dictate() to wait for a result and use it in further scripting.

    Returns void

showFind

  • showFind(): void

transcribe

  • transcribe(): string
  • Open Opens audio transcription window. If file is selected and transcribed, returns text.

    Returns string

    The text recognized in the audio transcription.

undo

  • undo(): void
  • Apply undo action to editor, if one is available.

    Returns void

Generated using TypeDoc

--- HTML | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class HTML

Helper methods to escape and unescape HTML entities in a string.

Added: R15

Examples

let s = "<One> & Two";
let escaped = HTML.escape(s); // "&#x3C;One&#x3E &#x26; Two"
let unescaped = HTML.unescape(encoded); // "<One> & Two"

Hierarchy

  • HTML

Index

Methods

Methods

Static escape

  • escape(string: string): string
  • Escape HTML entities in a string to be HTML safe.

    Parameters

    • string: string

      the string to escape

    Returns string

Static unescape

  • unescape(string: string): string
  • Unescape HTML entities in a string.

    Parameters

    • string: string

      the string to unescape

    Returns string

Generated using TypeDoc

--- Event | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Event

Event object represent individual calendar events. For usage examples, see Calendar object documentation.

Hierarchy

  • Event

Index

Properties

alarms

alarms: Alarm[]

The alarms assigned to the event, if any.

Readonly attendees

attendees: Object[]

Attendees of the event as an array of objects in the format:

{
   "isCurrentUser": false,
   "name": "John Appleseed",
   "status": "accepted",
   "type": "person",
   "role": "required"
}

availability

availability: "busy" | "free" | "tentative" | "unavailable" | "notSupported"

Availability for scheduling. Not supported by all Calendar servers.

calendar

calendar: Calendar

The calendar which this event resides in.

Readonly creationDate

creationDate: Date

Original creation date of the event.

endDate

endDate: Date

End date of the event.

Readonly hasAlarms

hasAlarms: boolean

Returns true if the event has any alarms.

identifier

identifier: string

Unique identifier for the event

isAllDay

isAllDay: boolean

Flag for all day events.

lastError

lastError: string | undefined

If a function fails, this property will contain the last error as a string message, otherwise it will be undefined.

Readonly lastModifiedDate

lastModifiedDate: Date

Last change to the event.

location

location: string

Location of the event.

notes

notes: string

Notes associated with the event.

startDate

startDate: Date

Start date of the event.

title

title: string

The title of the event.

Optional url

url: string

URL associated with the event. Setting URL value will fail if the value is not a valid URL.

Methods

addAlarm

  • addAlarm(alarm: Alarm): void
  • Add an alarm object to the event. Be sure to update() to save after adding alarms.

    Parameters

    Returns void

edit

  • edit(): boolean
  • Open the event in the system event editing card. The user will be able to modify/edit the event values and add to a calendar from this view. Returns true if the event was saved, false if the user canceled or deleted the event.

    Returns boolean

removeAllAlarms

  • removeAllAlarms(): void
  • Remove any assigned alarms from the event.

    Returns void

update

  • update(): boolean
  • Save the event. Returns true if the event is successfully saved in Calendars.

    Returns boolean

Generated using TypeDoc

--- HTMLPreview | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class HTMLPreview

Display of HTML Preview window, the same as the HTMLPreview action step. Returns true if user closed preview with the "Continue" button, false if the user cancelled.

Example

let html = "<html><body>My Document</body></html>"

let preview = HTMLPreview.create(); if (preview.show(html)) { // continue button was pressed } else { // cancel button was pressed }

Hierarchy

  • HTMLPreview

Index

Constructors

Properties

Methods

Constructors

constructor

Properties

hideInterface

hideInterface: boolean

Hides the toolbars and Cancel / Continue buttons in the preview window. For use only when combined with JavaScript flow control in the HTML preview. See docs for details.

Methods

show

  • show(html: string): boolean
  • Open HTML Preview window displaying the HTML string passed.

    Parameters

    • html: string

      The HTML content to display. Should be complete HTML document.

    Returns boolean

Static create

Generated using TypeDoc

--- OutlookMessage | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class OutlookMessage

The OutlookMessage object can be used to create and send mail messages through Outlook.com integrated accounts, similar to those created by a Outlook action step. Creating and sending these messages happens in the background, with no user interface, so messages must be complete with recipients before calling send(). Sending is done via the Microsoft Graph API. Outlooks accounts are authenticated when used for the first time using OAuth - to use more than one account, call create with different identifier parameters.

Example

let message = OutlookMessage.create();
message.toRecipients = ["joe@sample.com", "Jim Test <jim@test.com>"];
message.subject = "My test message";
message.body = "Body text";

var success = message.send(); if (!success) { console.log("Sending outlook message failed"); context.fail(); }

Hierarchy

  • OutlookMessage

Index

Constructors

constructor

Properties

bccRecipients

bccRecipients: string[]

Array of email addresses to use as BCC: recipients. Each entry can be a valid email address, or a name and email in the format Name<email>.

body

body: string

Body text of the mail message. Can be plain text or HTML if the isBodyHTML property is set to true.

ccRecipients

ccRecipients: string[]

Array of email addresses to use as CC: recipients. Each entry can be a valid email address, or a name and email in the format Name<email>.

isBodyHTML

isBodyHTML: boolean

whether to treat the body string and plain text or HTML. When set to true, the body property should be set to full valid HTML.

subject

subject: string

toRecipients

toRecipients: string[]

Array of email addresses to use as To: recipients. Each entry can be a valid email address, or a name and email in the format Name<email>.

Methods

send

  • send(): boolean

Static create

  • create a new object.

    Parameters

    • Optional identifier: string

      notes which for Outlook account to use. This string is an arbitrary value, but we recommend using the email address you wish to associate with the script. Each unique identifier will be associated with its own Credential.

    Returns OutlookMessage

Generated using TypeDoc

--- MultiMarkdown | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class MultiMarkdown

Drafts includes a full version of the MultiMarkdown 6 engine to render Markdown text to HTML and other supported formats. For details on the meaning of the various options, refer to MultiMarkdown documentation.

Example

var inputString = "# Header\n\nMy **markdown** text";
var mmd = MultiMarkdown.create();

mmd.format = "html"; mmd.criticMarkup = true; var outputString = mmd.render(inputString);

Hierarchy

  • MultiMarkdown

Index

Constructors

constructor

Properties

completeDocument

completeDocument: boolean

defaults to false

criticMarkup

criticMarkup: boolean

defaults to false

criticMarkupAccept

criticMarkupAccept: boolean

defaults to false

criticMarkupReject

criticMarkupReject: boolean

defaults to false

footnotesEnabled

footnotesEnabled: boolean

defaults to true

format

format: "html" | "epub" | "latex" | "beamer" | "memoir" | "odt" | "mmd"

Specify output format. Valid values are:

  • html: HTML. This is the default Markdown output.
  • epub: ePub
  • latex: LaTeX
  • beamer
  • memoir
  • odt: Open document format
  • mmd

markdownCompatibilityMode

markdownCompatibilityMode: boolean

defaults to false

noLabels

noLabels: boolean

defaults to true

noMetadata

noMetadata: boolean

defaults to false

obfuscate

obfuscate: boolean

defaults to false

processHTML

processHTML: boolean

defaults to true

randomFootnotes

randomFootnotes: boolean

defaults to false

smartQuotesEnabled

smartQuotesEnabled: boolean

defaults to true

snippetOnly

snippetOnly: boolean

defaults to false

transclude

transclude: boolean

defaults to false

Methods

render

  • render(markdownStr: string): string
  • Takes Markdown string passed and processes it with MultiMarkdown based on the properties and format selections on the object.

    Parameters

    • markdownStr: string

    Returns string

Static create

Generated using TypeDoc

--- TJSContainer | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class TJSContainer

Wraps an array of todo and/or project items and encodes them into a URL for use to send the request to Things.

Things Integration Notes

  • Things is a popular task and project management app from Cultured Code. Things supports advanced URL schemes (required Things v3.4 or greater on iOS) which can accept multiple todos, projects, headings in a single call to the app. The scripting interfaces below are convenience wrappers that allow easy creation and encoding of the URLs needed to pass this type of information to Things.

The TJS* JavaScript objects are wrappers around an open source Swift library provided by Cultured Code, with a few modifications to work in JavaScript. In all cases, nothing is committed to Things until the the items are wrapped in a TJSContainer, and the URL it generates called to send the data to Things. This is best done with Drafts’ CallbackURL object (see example below).

For more information about what values Things understands in these objects, refer to their URL scheme documenation.

Example

// create a Things Project
var project = TJSProject.create();
project.title = "My Project From Drafts";
project.notes = "Let's do this stuff";

// create and add a heading to the project var heading = TJSHeading.create(); heading.title = "First Heading"; project.addHeading(heading);

// add todos to the project var todo1 = TJSTodo.create(); todo1.title = "My first todo"; todo1.when = "today"; project.addTodo(todo1);

var todo2 = TJSTodo.create(); todo2.title = "My second todo"; todo2.when = "tomorrow"; project.addTodo(todo2);

// create a container to handle creation of Things URL var container = TJSContainer.create([project]);

// Use CallbackURL object to open URL in Things. var cb = CallbackURL.create(); cb.baseURL = container.url; var success = cb.open(); if (success) { console.log("Project created in Things"); } else { context.fail(); }

Hierarchy

  • TJSContainer

Index

Properties

Methods

Properties

url

url: string

The full URL with encoded TJSContainer parameters.

Methods

Static create

Generated using TypeDoc

--- GoogleDrive | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class GoogleDrive

GoogleDrive objects can be used to work with files in Google Drive accounts.

Example

// create GoogleDrive object
var drive = GoogleDrive.create();

// setup variables var fileName = "MyTestFile"; var parent = ""; // root of drive var content = "text to place in file";

// write to file on GoogleDrive var success = drive.write(fileName, parent, content);

if (success) { // write worked! var driveContent = drive.read(fileName, parent); if (driveContent) { // read worked! if (driveContent == content) { alert("File contents match!"); } else { console.log("File did not match"); context.fail(); } } else { // read failed, log error console.log(drive.lastError); context.fail(); } } else { // write failed, log error console.log(drive.lastError); context.fail(); }

Hierarchy

  • GoogleDrive

Index

Constructors

Properties

Methods

Constructors

constructor

Properties

lastError

lastError: string | undefined

If a function fails, this property will contain the last error as a string message, otherwise it will be undefined.

Methods

read

  • read(fileName: string, parent: string): string | undefined
  • Reads the contents of the file at the with the file name, in the parent folder, as a string. Returns undefined value if the file does not exist or could not be read.

    Parameters

    • fileName: string
    • parent: string

      Name of folder in the root of the Google Drive, or "" for root. FIXME: optional?

    Returns string | undefined

write

  • write(fileName: string, parent: string, content: string): boolean
  • Write the contents of the file at the path. Returns true if successful, false if the file could not be written successfully. This will override existing files!

    Parameters

    • fileName: string
    • parent: string

      Name of folder in the root of the Google Drive, or "" for root.

    • content: string

      Text to write to file.

    Returns boolean

Static create

  • Creates a new GoogleDrive object.

    Parameters

    • Optional identifier: string

      used to identify a GoogleDrive account. Typically this can be omitted if you only work with one GoogleDrive account in Drafts.

    Returns GoogleDrive

Generated using TypeDoc

--- GitHubMarkdown | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class GitHubMarkdown

Drafts includes Discount-based, GitHub flavored Markdown parser based on GHMarkdownParser. For details on the meaning of the various options, refer to Markdown documentation.

Example

var inputString = "# Header\n\nMy **markdown** text";
var md = GitHubMarkdown.create();

var outputString = md.render(inputString);

Hierarchy

  • GitHubMarkdown

Index

Constructors

constructor

Properties

autoLinks

autoLinks: boolean

defaults to false

noImages

noImages: boolean

defaults to true

noLinks

noLinks: boolean

defaults to true

removeHTMLTags

removeHTMLTags: boolean

defaults to false

safeLinks

safeLinks: boolean

defaults to true

smartQuotesEnabled

smartQuotesEnabled: boolean

defaults to true

strict

strict: boolean

defaults to false

Methods

render

  • render(markdownStr: string): string
  • Takes Markdown string passed and processes it with GitHub Markdown parser based on the property selections on the object.

    Parameters

    • markdownStr: string

    Returns string

Static create

Generated using TypeDoc

--- Device | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Device

Drafts defines a single global device object which provides access to information about the current device.

Examples

// get system info from device object
var model = device.model;
var system = device.systemName;
var osVersion = device.systemVersion;
var batteryLevel = device.batteryLevel;

// create and display it in an alert var s = "Model: " + model + "\n"; s = s + "System: " + system + "\n"; s = s + "OS: " + osVersion + "\n"; s = s + "Battery: " + batteryLevel; alert(s);

// branch logic based on platform if (device.systemName == 'macOS') { // do something only on Mac } else { // do something only on iOS }

Hierarchy

  • Device

Index

Properties

batteryLevel

batteryLevel: number

Current battery level as a number between 0.0 and 1.0

model

model: "iPhone" | "iPad" | "Mac"

Model of current device.

systemName

systemName: "iOS" | "macOS"

Name of current OS.

systemVersion

systemVersion: string

Version of current OS.

Generated using TypeDoc

--- Notion | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Notion

Script integration with Notion. This object handles OAuth authentication and request signing. The entire Notion REST API can be used with the request method.

Example

// list pages which have been shared with the Drafts integration
// API Docs: https://developers.notion.com/reference/post-search
let endpoint = "https://api.notion.com/v1/search"

let notion = Notion.create(); let result = notion.request({ "url": endpoint, "method": "POST", "data": { "filter": { "value": "page", "property": "object" } } });

// result has JSON payload // with page properties if (result.statusCode == 200) { alert(`Notion Pages Loaded:

\({result.responseText}</span>`) } <span class="hljs-keyword">else</span> { alert(`Notion Error: <span class="hljs-variable">\){result.statusCode}

${notion.lastError}`); context.fail(); }

Hierarchy

  • Notion

Index

Constructors

Properties

Methods

Constructors

constructor

  • new Notion(identifier?: string): Notion
  • Create new instance.

    Parameters

    • Optional identifier: string

    Returns Notion

Properties

Optional lastError

lastError: string

If a function fails, this property will contain the last error as a string message, otherwise it will be undefined.

lastResponse

lastResponse: any

If a function succeeds, this property will contain the last response returned by Notion. The JSON returned by Notion will be parsed to an object and placed in this property. Refer to Notion API documentation for details on the contents of this object based on call made.

Methods

request

  • request(settings: { data?: {}; headers?: {}; method: string; parameters?: {}; url: string }): HTTPResponse
  • Execute a request against the Notion API. For successful requests, the HTTPResponse object will contain an object or array or objects decoded from the JSON returned by Notion as appropriate to the request made. Refer to Notion's API documentation for details about the expected parameters and responses. Drafts will handle wrapping the request in the appropriate OAuth authentication flow.

    Parameters

    • settings: { data?: {}; headers?: {}; method: string; parameters?: {}; url: string }

      an object configuring the request.

      • Optional data?: {}

        A JavaScript object containing data to be encoded into the HTTP body of the request. Refer to API documentation for appropriate information to include.

        • [x: string]: string
      • Optional headers?: {}

        An object contain key-values to be added as custom headers in the request. There is no need to provide authorization headers, Drafts will add those. Drafts will automatically include required authentication and versioning headers.

        • [x: string]: string
      • method: string

        The HTTP method, like "GET", "POST", etc.

      • Optional parameters?: {}

        An object containing key-values to be added to the request as URL parameters.

        • [x: string]: string
      • url: string

        The full URL to the endpoint in the Notion REST API.

    Returns HTTPResponse

Static create

  • create(identifier: string): Notion
  • Creates a new Notion object.

    Parameters

    • identifier: string

      Optional string value used to identify a Notion account. Typically this can be omitted if you only work with one Notion account in Drafts. Each unique identifier used for Notion accounts will share credentials - across both action steps and scripts.

    Returns Notion

Generated using TypeDoc

--- TJSHeading | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class TJSHeading

Represents a Things heading within a project. See TJSContainer documentation for details on making requests to Things.

Hierarchy

  • TJSHeading

Index

Properties

Methods

Properties

archived

archived: boolean

title

title: string

Methods

Static create

Generated using TypeDoc

--- Mail | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Mail

Hierarchy

  • Mail

Index

Constructors

constructor

Properties

bccRecipients

bccRecipients: string[]

Array of email addresses to use as BCC: recipients.

body

body: string

Body text of the mail message. Can be plain text or HTML if the isBodyHTML property is set to true.

ccRecipients

ccRecipients: string[]

Array of email addresses to use as CC: recipients.

isBodyHTML

isBodyHTML: boolean

whether to treat the body string and plain text or HTML. When set to true, the body property should be set to full valid HTML.

isSent

isSent: boolean

Indicates if the message object has already been sent.

sendInBackground

sendInBackground: boolean

If true, the mail will be sent in the background using a web service rather than via Mail.app - but will come from drafts5@drafts5.agiletortoise.com. Defaults to false.

status

status: mailStatus

One of the following values:

  • created: Initial value before send() has been called.
  • sent: The message was sent successfully.
  • savedAsDraft: On iOS, the user exited the Mail.app window saving as draft, but not sending.
  • mailUnavailable: On iOS, Mail.app services were not available.
  • userCancelled: The user cancelled the Mail.app window without sending.
  • invalid: Mail object is invalid. Common cause if of this is sendInBackground being true, but no recipient configured.
  • serviceError: Background mail service returned an error.
  • unknownError: An unknown error occurred.

subject

subject: string

Subject line

toRecipients

toRecipients: string[]

Array of email addresses to use as To: recipients.

Methods

send

  • send(): boolean
  • Send the mail message. This will open the Mail.app sending window. Returns true if the message was sent successfully or false if not - if, for example, the user cancelled the mail window.

    Returns boolean

Static create

Generated using TypeDoc

--- Message | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Message

The Message object can be used to create and send mail iMessages, similar to those created by a "Message" action step.

Examples

var msg = Message.create();
msg.toRecipients = ["joe@sample.com"];
msg.subject = "My test message";
msg.body = "Body text";

var success = msg.send();

Hierarchy

  • Message

Index

Constructors

Properties

Methods

Constructors

constructor

Properties

body

body: string

Body text of the mail message.

isSent

isSent: boolean

true/false flag indicated if the message object has already been sent.

status

status: "created" | "sent" | "messagesUnavailable" | "userCancelled" | "unknownError"

One of the following strings

  • created: Initial value before send() has been called.
  • sent: The message was sent successfully.
  • messagesUnavailable: On iOS, Mail.app services were not available.
  • userCancelled: The user cancelled the Mail.app window without sending.
  • unknownError: An unknown error occurred.

subject

subject: string

Subject line. Only used if subject is enabled in Messages settings on the device.

toRecipients

toRecipients: string[]

Array of phone numbers and email addresses to use as To: recipients.

Methods

send

  • send(): boolean
  • Send the message. This will open the Messages.app sending window. Returns true if the message was sent successfully or false if not - if, for example, the user cancelled the message window.

    Returns boolean

Static create

Generated using TypeDoc

--- GmailMessage | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class GmailMessage

The GmailMessage object can be used to create and send mail messages through Gmail accounts, similar to those created by a Gmail action step. Creating and sending these messages happens in the background, with no user interface, so messages must be complete with recipients before calling send(). Sending is done via the Gmail API. Gmail accounts are authenticated when used for the first time using OAuth - to use more than one account, call create with different identifier parameters.

Example

let message = GmailMessage.create();
message.toRecipients = ["joe@sample.com"];
message.subject = "My test message";
message.body = "Body text";

var success = message.send(); if (!success) { console.log("Sending gmail failed"); context.fail(); }

Hierarchy

  • GmailMessage

Index

Constructors

constructor

Properties

bccRecipients

bccRecipients: string[]

Array of email addresses to use as BCC: recipients. Each entry can be a valid email address, or a name and email in the format Name<email>.

body

body: string

Body text of the mail message. Can be plain text or HTML if the isBodyHTML property is set to true.

ccRecipients

ccRecipients: string[]

Array of email addresses to use as CC: recipients. Each entry can be a valid email address, or a name and email in the format Name<email>.

isBodyHTML

isBodyHTML: boolean

whether to treat the body string and plain text or HTML. When set to true, the body property should be set to full valid HTML.

subject

subject: string

toRecipients

toRecipients: string[]

Array of email addresses to use as To: recipients. Each entry can be a valid email address, or a name and email in the format Name<email>.

Methods

send

  • send(): boolean

Static create

  • create a new object.

    Parameters

    • Optional identifier: string

      notes which for Gmail account to use. This string is an arbitrary value, but we recommend using the email address you wish to associate with the script. Each unique identifier will be associated with its own Credential.

    Returns GmailMessage

Generated using TypeDoc

--- Twitter | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Twitter

Script integration with Twitter. The updateStatus method is a convenience method for posting a tweet, but the entire Twitter API can be used with the request method, which handles OAuth authentication and authorization.

Example

// create twitter object
var twitter = Twitter.create();
// post tweet
var success = twitter.updateStatus("My tweet content!");

if success { console.log(twitter.lastResponse); } else { console.log(twitter.lastError); context.fail(); }

Hierarchy

  • Twitter

Index

Constructors

Methods

Constructors

constructor

  • new Twitter(identifier?: string): Twitter

Methods

request

  • request(settings: { data?: {}; headers?: {}; method: string; parameters?: {}; url: string }): HTTPResponse
  • Execute a request against the Twitter API. For successful requests, the [[[HTTPResponse]] object will contain an object or array or objects decoded from the JSON returned by Twitter as appropriate to the request made. Refer to Twitter’s API documentation for details about the expected parameters and responses. Drafts will handle wrapping the request in the appropriate OAuth authentication flow.

    Parameters

    • settings: { data?: {}; headers?: {}; method: string; parameters?: {}; url: string }

      an object with the following properties:

      • url [string, required]: The full URL to the endpoint in the Twitter API.
      • method [string, required]: The HTTP method, like "GET", "POST", etc.
      • headers [object, optional]: An object contain key-values to be added as custom headers in the request. There is no need to provide authorization headers, Drafts will add those.
      • parameters [object, optional]: An object containing key-values to be added to the request as URL parameters.
      • data [object, optional]: An object containing data to be encoded into the HTTP body of the request.
      • Optional data?: {}
        • [x: string]: string
      • Optional headers?: {}
        • [x: string]: string
      • method: string
      • Optional parameters?: {}
        • [x: string]: string
      • url: string

    Returns HTTPResponse

updateStatus

  • updateStatus(content: string): boolean
  • Post a status update (tweet) to Twitter. Returns true if successful, false if not. After success the lastResponse object can be used to inspect response and get details such as the ID of the tweet created. Refer to Twitter API POST /status/update documentation for response details.

    Parameters

    • content: string

    Returns boolean

Static create

  • create(identifier: string): Twitter
  • Creates a new Twitter object. Identifier is a optional string value used to identify a Twitter account. Typically this can be omitted if you only work with one Twitter account in Drafts. Each unique identifier used for Twitter accounts will share credentials - across both action steps and scripts.

    Parameters

    • identifier: string

    Returns Twitter

Generated using TypeDoc

--- OneDrive | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class OneDrive

OneDrive objects can be used to work with files in a OneDrive account.

Example

// create OneDrive object
var drive = OneDrive.create();

// setup variables var path = "/test/file.txt"; var content = "text to place in file";

// write to file on OneDrive var success = drive.write(path, content, false);

if (success) { // write worked! var driveContent = drive.read(path); if (driveContent) { // read worked! if (driveContent == content) { alert("File contents match!"); } else { console.log("File did not match"); context.fail(); } } else { // read failed, log error console.log(drive.lastError); context.fail(); } } else { // write failed, log error console.log(drive.lastError); context.fail(); }

Hierarchy

  • OneDrive

Index

Constructors

Properties

Methods

Constructors

constructor

  • new OneDrive(identifier?: string): OneDrive

Properties

lastError

lastError: string | undefined

If a function fails, this property will contain the last error as a string message, otherwise it will be undefined.

Methods

read

  • read(path: string): string
  • Reads the contents of the file at the path as a string. Returns undefined value if the file does not exist or could not be read. Paths should begin with a / and be relative to the root directory of your OneDrive.

    Parameters

    • path: string

    Returns string

write

  • write(path: string, content: string, overwrite?: boolean): boolean
  • Write the contents of the file at the path. Returns true if successful, false if the file could not be written successfully. This will override existing files!

    Parameters

    • path: string

      Paths should begin with a / and be relative to the root directory of your OneDrive

    • content: string

      Text to place in the file

    • Optional overwrite: boolean

      If false, an existing file will not be overwritten

    Returns boolean

Static create

  • Parameters

    • Optional identifier: string

      Optional identifier for OneDrive account to use. This string is an arbitrary value, but we recommend using the email address you wish to associate with the script. Each unique identifier will be associated with its own Credential.

    Returns OneDrive

Generated using TypeDoc

--- ShellScript | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class ShellScript

macOS only. Requires Drafts 19 or greater.

ShellScript objects can be used to execute Unix shell scripts.

Bash Example

// define text of bash script
let script = `#!/bin/bash
echo "Total arguments : $#"
echo "1st Argument = $1"
echo "2nd argument = $2"
`;
let runner = ShellScript.create(script);

if (runner.execute(["1", "2"])) { alert("STDOUT: " + runner.standardOutput); } else { alert("STDERR: " + runner.standardError); }

Ruby Example

let script = #!/usr/bin/env ruby
ARGV.each do |a|
puts &quot;Argument: #{a}&quot;
end;
let runner = ShellScript.create(script);

if (runner.execute(["1", "2"])) { alert("STDOUT:\n" + runner.standardOutput); } else { alert("STDERR:\n" + runner.standardError); }

Note: When executed, scripts are saved to temporary files in the Drafts' script directory at ~/Library/Application Scripts/com.agiletortoise.Drafts-OSX and run. Scripts should not be written to make assumptions about their location in the file system (e.g. using relative paths). The first time a script is executed, the user will be asked to grant permissions to the script directory.

Hierarchy

  • ShellScript

Index

Constructors

Properties

Methods

Constructors

constructor

Properties

Optional standardError

standardError: string | undefined

Content sent to standard error during the execution of the script

Optional standardOutput

standardOutput: string | undefined

Content sent to standard output during the execution of the script

Methods

execute

  • execute(arguments: string[]): boolean
  • Executes the shell script.

    Parameters

    • arguments: string[]

      An array of string arguments to pass to the script. These will appear to the script as command line arguments would.

    Returns boolean

    true if the script was executed without error, false if not.

Static create

  • Convenience method to create a ShellScript object.

    Parameters

    • script: string

      A string containing the shell script. This should contain the appropriate "she bang" to trigger the appropriate scripting language/shell.

    Returns ShellScript

Generated using TypeDoc

--- TJSProject | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class TJSProject

Represents a Things project, with headings and todo items. See TJSContainer documentation for details on making requests to Things.

Hierarchy

  • TJSProject

Index

Properties

area

area: string

areaID

areaID: string

canceled

canceled: boolean

completed

completed: boolean

deadline

deadline: string

notes

notes: string

tags

tags: string[]

title

title: string

when

when: string

Methods

addHeading

addTag

  • addTag(tag: string): void

addTodo

Static create

Generated using TypeDoc

--- Medium | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Medium

Script integration with Medium.com. This object handles OAuth authentication and request signing. The entire Medium REST API can be used with the request method, and convenience methods are provided for common API endpoints to get user information, list publications and post.

If an API calls fails, typically the result will be an undefined value, and the lastError property will contains error detail information for troubleshooting.

Hierarchy

  • Medium

Index

Constructors

constructor

  • new Medium(identifier?: string): Medium
  • Create new instance.

    Parameters

    • Optional identifier: string

    Returns Medium

Properties

Optional lastError

lastError: string

If a function fails, this property will contain the last error as a string message, otherwise it will be undefined.

lastResponse

lastResponse: any

If a function success, this property will contain the last response returned by Medium. The JSON returned by Medium will be parsed to an object and placed in this property. Refer to Medium API documentation for details on the contents of this object based on call made.

Methods

createPost

  • createPost(userId: string, options: object): object
  • Create a post in the user's Medium stories. See API docs for details on what should be included in the options.

    Parameters

    • userId: string
    • options: object

    Returns object

getUser

  • getUser(): object
  • Get User information for current authenticated user. This will include the id property needed for other calls.

    Returns object

listPublications

  • listPublications(userId: string): object[]
  • Get list of publications for current authenticated user.

    Parameters

    • userId: string

    Returns object[]

request

  • request(settings: { data?: {}; headers?: {}; method: string; parameters?: {}; url: string }): HTTPResponse
  • Execute a request against the Medium API. For successful requests, the HTTPResponse object will contain an object or array or objects decoded from the JSON returned by Medium as appropriate to the request made. Refer to Medium API documentation for details about the expected parameters and responses. Drafts will handle wrapping the request in the appropriate OAuth authentication flow.

    Parameters

    • settings: { data?: {}; headers?: {}; method: string; parameters?: {}; url: string }

      an object configuring the request.

      • Optional data?: {}

        A JavaScript object containing data to be encoded into the HTTP body of the request.

        • [x: string]: string
      • Optional headers?: {}

        An object contain key-values to be added as custom headers in the request. There is no need to provide authorization headers, Drafts will add those.

        • [x: string]: string
      • method: string

        The HTTP method, like "GET", "POST", etc.

      • Optional parameters?: {}

        An object containing key-values to be added to the request as URL parameters.

        • [x: string]: string
      • url: string

        The full URL to the endpoint in the Medium REST API.

    Returns HTTPResponse

Static create

  • create(identifier: string): any
  • Creates a new Medium object.

    Parameters

    • identifier: string

      Optional string value used to identify a Medium account. Typically this can be omitted if you only work with one Medium account in Drafts. Each unique identifier used for Medium accounts will share credentials - across both action steps and scripts.

    Returns any

Generated using TypeDoc

--- Prompt | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Prompt

Prompts allow the creation and display of custom dialogs to request information or confirmation from the user.

Example

var p = Prompt.create();

p.title = "Hello"; p.message = "World!";

p.addTextField("textFieldName", "Label", "");

p.addDatePicker("myDate", "Start date", new Date(), { "mode": "date" }); p.addButton("First"); p.addButton("Second");

var didSelect = p.show();

var textFieldContents = p.fieldValues["textFieldName"]; var startDate = p.fieldValues["myDate"];

if (p.buttonPressed == "First") { // do something }

Hierarchy

  • Prompt

Index

Constructors

constructor

Display Properties

isCancellable

isCancellable: boolean

If true, a "Cancel" button will be included in the dialog. Defaults to true. If the user selects the cancel button, the show() method will return false. If false, no cancel button will be displayed and the user must select one of the button name options.

message

message: string

A longer message explaining the purpose of the dialog, if needed.

title

title: string

Short title.

Result Properties

buttonPressed

buttonPressed: string

After the show() method is called, this property will contain the name of the button selected by the user.

fieldValues

fieldValues: {}

After the show() method is called, this property will contain values from any fields added to the prompt. The dictionary keys will be the names of the fields as passed in when they were created, and the value will be the current contents of that field. They type of data depends on the type of field.

Type declaration

  • [x: string]: any

Field Methods

addButton

  • addButton(name: string, value?: object, isDefault?: boolean): void
  • Add a button to the array of buttons to be displayed. All buttons should be created before calling show().

    Parameters

    • name: string
    • Optional value: object

      only needed to associate a different value than will be displayed in the button. For example, if you call prompt.addButton("First Button", 1), after calling prompt.show() if that button is pressed, the prompt.buttonPressed will contain the number value 1.

    • Optional isDefault: boolean

      used to specify a single button which will be pinned to the bottom of the prompt and respond to cmd + return as the default button. If only one button is added to a prompt, it is assumed to be the default.

    Returns void

addDatePicker

  • addDatePicker(name: string, label: string, initialDate: Date, options?: { maximumDate?: Date; minimumDate?: Date; minuteInterval?: number; mode?: "date" | "time" | "dateAndTime" }): void
  • Add a date and/or time picker to the prompt, with the arguments as below. The fieldValues entry for this will be a date object.

    Parameters

    • name: string

      Identifier for the field. This will be used as the key in the fieldValues dictionary to access the contents of the field after calling show().

    • label: string

      User-friendly text label to place next to the field.

    • initialDate: Date

      The initial date to selected for the field. Minimum and maximum values should be defined in options.

    • Optional options: { maximumDate?: Date; minimumDate?: Date; minuteInterval?: number; mode?: "date" | "time" | "dateAndTime" }

      A dictionary of options for configuring the text field.

      • Optional maximumDate?: Date
      • Optional minimumDate?: Date
      • Optional minuteInterval?: number
      • Optional mode?: "date" | "time" | "dateAndTime"

    Returns void

addLabel

  • addLabel(name: string, label: string, options?: { textSize?: "body" | "caption" | "headline" }): void
  • Add an information text label to the prompt.

    Parameters

    • name: string

      Identifier for the field.

    • label: string

      The text of the label.

    • Optional options: { textSize?: "body" | "caption" | "headline" }

      A dictionary of options for configuring the text field.

      • Optional textSize?: "body" | "caption" | "headline"

    Returns void

addPasswordField

  • addPasswordField(name: string, label: string, initialValue: string): void
  • Same as addTextField, but the input field will be password masked.

    Parameters

    • name: string
    • label: string
    • initialValue: string

    Returns void

addPicker

  • addPicker(name: string, label: string, columns: string[][], selectedRows: number[]): void
  • Add a picker to the prompt, with the arguments as below. Picker can contain multiple rows. The fieldValues entry for this will be a array of selected index values object.

    Parameters

    • name: string

      Identifier for the field. This will be used as the key in the fieldValues dictionary to access the contents of the field after calling show().

    • label: string

      User-friendly text label to place next to the field.

    • columns: string[][]

      The values to display in the picker. Should be an array containing arrays of string values, each sub-array representing a column in the picker. Example two column picker: [["Item 1", "Item 2"],["Column 2 Item 1", "Column 2 Item 2"]]

    • selectedRows: number[]

      Array of zero-based index values to set the initial selected row in each column.

    Returns void

addSelect

  • addSelect(name: string, label: string, values: string[], selectedValues: string[], allowMultiple: boolean): void
  • Add a select control. Returns an array of string values in fieldValues.

    Parameters

    • name: string

      Identifier for the field. This will be used as the key in the fieldValues dictionary to access the contents of the field after calling show().

    • label: string

      User-friendly text label to place next to the field.

    • values: string[]

      The array of string values that will be available to select.

    • selectedValues: string[]

      Array of string values that should be initially selected when the prompt is displayed. All values in this array should match values in the values array.

    • allowMultiple: boolean

      If false, selecting a value will deselect all other values. If true, the user may select multiple items.

    Returns void

addSwitch

  • addSwitch(name: string, label: string, initialValue: boolean): void
  • Add an on/off toggle switch. The fieldValues entry for this item will be a boolean indicating whether the switch was on.

    Parameters

    • name: string

      Identifier for the field. This will be used as the key in the fieldValues dictionary to access the contents of the field after calling show().

    • label: string

      User-friendly text label to place next to the field.

    • initialValue: boolean

      indicate if the switch should be on or off when initially displayed.

    Returns void

addTextField

  • addTextField(name: string, label: string, initialText: string, options?: { autocapitalization?: capitalizationTypes; autocorrect?: boolean; keyboard?: keyboardTypes; placeholder?: string; wantsFocus?: boolean }): void
  • Add a text input field to the prompt

    Parameters

    • name: string

      Identifier for the field. This will be used as the key in the fieldValues dictionary to access the contents of the field after calling show().

    • label: string

      User-friendly text label to place next to the field.

    • initialText: string

      The initial text contents for the field.

    • Optional options: { autocapitalization?: capitalizationTypes; autocorrect?: boolean; keyboard?: keyboardTypes; placeholder?: string; wantsFocus?: boolean }

      A dictionary of options for configuring the text field.

      • Optional autocapitalization?: capitalizationTypes
      • Optional autocorrect?: boolean

        Should system autocorrect be enabled in field, Default: true

      • Optional keyboard?: keyboardTypes
      • Optional placeholder?: string

        Placeholder text to use when field is empty

      • Optional wantsFocus?: boolean

        If true, focus this field when prompt is displayed

    Returns void

addTextView

  • addTextView(name: string, label: string, initialText: string, options?: { autocapitalization?: capitalizationTypes; autocorrect?: boolean; height?: number; keyboard?: keyboardTypes; wantsFocus?: boolean }): void
  • Add a text input field to the prompt

    Parameters

    • name: string

      Identifier for the field. This will be used as the key in the fieldValues dictionary to access the contents of the field after calling show().

    • label: string

      User-friendly text label to place next to the field.

    • initialText: string

      The initial text contents for the field.

    • Optional options: { autocapitalization?: capitalizationTypes; autocorrect?: boolean; height?: number; keyboard?: keyboardTypes; wantsFocus?: boolean }

      A dictionary of options for configuring the text field.

      • Optional autocapitalization?: capitalizationTypes
      • Optional autocorrect?: boolean

        Should system autocorrect be enabled in field, Default: true

      • Optional height?: number
      • Optional keyboard?: keyboardTypes
      • Optional wantsFocus?: boolean

        If true, focus this field when prompt is displayed

    Returns void

Other Methods

show

  • show(): boolean
  • Displays the prompt. Returns true if the user selected one of the buttons in the buttons array, false if the user selected the "Cancel" button. After the dialog has been shown, the buttonPressed property will contain the name of the button selected by the user.

    Returns boolean

Static create

Generated using TypeDoc

--- Box | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Box

Box objects can be used to work with files in a Box.com account.

Examples

// create Box object
var drive = Box.create();

// setup variables var path = "/test/file.txt"; var content = "text to place in file";

// write to file on Box var success = drive.write(path, content, false);

if (success) { // write worked! var driveContent = drive.read(path); if (driveContent) { // read worked! if (driveContent == content) { alert("File contents match!"); } else { console.log("File did not match"); context.fail(); } } else { // read failed, log error console.log(drive.lastError); context.fail(); } } else { // write failed, log error console.log(drive.lastError); context.fail(); }

Hierarchy

  • Box

Index

Constructors

Properties

Methods

Constructors

constructor

  • new Box(identifier?: string): Box
  • Create new instance.

    Parameters

    • Optional identifier: string

    Returns Box

Properties

Optional Readonly lastError

lastError: string

Methods

read

  • read(path: string): string
  • Reads the contents of the file at the path as a string. Returns undefined value if the file does not exist or could not be read. Paths should begin with a / and be relative to the root directory of your Box.com account.

    Parameters

    • path: string

    Returns string

write

  • write(path: string, content: string, overwrite?: boolean): boolean
  • Write the contents of the file at the path. Returns true if successful, false if the file could not be written successfully. This will override existing files!

    Parameters

    • path: string

      Paths should begin with a / and be relative to the root directory of your Box

    • content: string

      Text to place in the file.

    • Optional overwrite: boolean

      If false, an existing file will not be overwritten.

    Returns boolean

Static create

  • create(identifier?: string): Box
  • Creates a new Box object. Identifier is a optional string value used to identify a Box.com account. Typically this can be omitted if you only work with one Box.com account in Drafts.

    Parameters

    • Optional identifier: string

    Returns Box

Generated using TypeDoc

--- Theme | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Theme

Represents a Theme definition available in the current installation of Drafts.

Example: Find and assign the active light theme

let theme = Theme.find("builtIn", "dark");
app.lightTheme = theme;

Hierarchy

  • Theme

Index

Identification Properties

Methods

Identification Properties

Readonly installURL

installURL: string

URL which can be used to install this Theme in another installation of Drafts. Useful for sharing and backups.

name

name: string

The name of the theme definition.

type

type: themeType

The type (builtIn, custom, file) of the theme definition.

Methods

Static find

  • Search for a theme definition matching the type and name passed and return it if found. Returns undefined if not found.

    Parameters

    Returns Theme | undefined

Static getAll

Generated using TypeDoc

--- XMLRPC | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class XMLRPC

The XMLRPC object is a convenience method to provide an easy way to XML-RPC web services. The request function takes care of converting native Javascript objects and values to the XML parameters required for the XML-RPC interface, and converts the XML responses returned to Javascript objects.

It will also return faults parsed to error messages in the response if necessary.

This object is suitable for communication with a number of popular XML-RPC interfaces, including the MetaWeblog API. WordPress also offers its own XML-RPC interface, which can be used via this object, or the convenience wrapper WordPress object.

Example: XML-RPC call

// DEMO of XML-RPC
// Calls example method on http://xml-rpc.net/index.html

let url = "http://www.cookcomputing.com/xmlrpcsamples/RPC2.ashx"; let methodName = "examples.getStateName"; let params = [20];

let response = XMLRPC.request(url, methodName, params);

if (response.success) { alert(JSON.stringify(response.params)); } else { alert("Fault: " + response.faultCode + ", " + response.error); context.fail(); }

Hierarchy

  • XMLRPC

Index

Methods

Methods

Static request

  • request(url: string, methodName: string, params: any[]): XMLRPCResponse
  • Make an XML-RPC request.

    Parameters

    • url: string

      The full URL of the XML-RPC host endpoint being called.

    • methodName: string

      Name of the method to call. Supported values are specific to the services provided by the host.

    • params: any[]

      The parameters to pass to the request. This should be an array of values, in the proper order, as specified by the documentation of the host being called. This array will be encoded into XML-RPC parameters in XML format by the method - only raw javascript values should be provided.

    Returns XMLRPCResponse

Generated using TypeDoc

--- TJSTodo | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class TJSTodo

Represents a Things todo item. Todos can be added a project or directly to a container. See TJSContainer documentation for details on making requests to Things.

Hierarchy

  • TJSTodo

Index

Properties

canceled

canceled: boolean

completed

completed: boolean

deadline

deadline: string

heading

heading: string

list

list: string

listID

listID: string

notes

notes: string

tags

tags: string[]

title

title: string

when

when: string

Methods

addChecklistItem

addTag

  • addTag(tag: string): void

Static create

Generated using TypeDoc

--- Script | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Script

When running a Script action step, a single script object will be in context to reference the currently running script.

Example

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}
async function f() {
  let promise = new Promise((resolve, reject) => {
    sleep(1000);
    resolve("done!")
  });
  let result = await promise; // wait until the promise resolves (*)
  alert(result); // "done!"
  script.complete();
}
f();

Hierarchy

  • Script

Index

Methods

Methods

complete

  • complete(): any
  • Inform Drafts the current script has completed execution. Used in combination with the "Allow asynchronous execution" option of the Script step type. If your script step has the asynchronous option enabled, you must call script.complete() to indicate completion or the script will timeout and fail.

    Returns any

Generated using TypeDoc

--- Todoist | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Todoist

Script integration with Todoist. This object handles OAuth authentication and request signing. The entire Todoist REST API can be used with the request method, and convenience methods are provided for common API endpoints to manage tasks, projects, comments and labels.

The quickAdd method is mostly likely what you are looking for to create tasks as it supports the shorthand the task entry box in Todoist supports to parse projects, etc.

Other methods are direct mappings of the REST API calls provided by Todoist. Most take an options parameter which is a javascript object containing the parameters to be passed to the API, and and the method decodes the JSON response from Todoist and returns it as a Javascript object (or array of objects) with the values as specified in the Todoist API docs.

If an API calls fails, typically the result will be an undefined value, and the lastError property will contains error detail information for troubleshooting.

Example

See Examples-Todoist action group in the Action Directory.

// create Todoist object
let todoist = Todoist.create();
// create task in inbox
todoist.createTask({
  "content": "My Task Name",
  "due_string": "Next wednesday"
});

Hierarchy

  • Todoist

Index

Constructors

constructor

  • new Todoist(identifier?: string): Todoist

Properties

Optional lastError

lastError: string

If a function fails, this property will contain the last error as a string message, otherwise it will be undefined.

lastResponse

lastResponse: any

If a function succeeds, this property will contain the last response returned by Todoist. The JSON returned by Todoist will be parsed to an object and placed in this property. Refer to Todoist API documentation for details on the contents of this object based on call made.

Comments Methods

createComment

  • createComment(options: object): object

getComment

  • getComment(commentId: string): object

getComments

  • getComments(options: object): object[]

updateComment

  • updateComment(commentId: string, options: object): object

Labels Methods

createLabel

  • createLabel(options: object): object

getLabel

  • getLabel(labelId: string): object

getLabels

  • getLabels(): object[]

updateLabel

  • updateLabel(labelId: string, options: object): object

Other Methods

quickAdd

  • quickAdd(text: string, note?: string, reminder?: string, options?: object): object
  • Parameters

    • text: string

      Text to use to create the task. Supports Todoist quick add notation for specifying projects, priority, labels, etc. just as if you were using the Todoist quick add window.

    • Optional note: string

      Optional text to attach as a comment with the task.

    • Optional reminder: string

      Optional natural language date specifying for creating a task reminder.

    • Optional options: object

      Optional dictionary of additional parameters to include in the request.

    Returns object

    Object containing respose data from Todoist.

request

  • request(settings: { data?: {}; headers?: {}; method: string; parameters?: {}; url: string }): HTTPResponse
  • Execute a request against the Todoist API. For successful requests, the HTTPResponse object will contain an object or array or objects decoded from the JSON returned by Todoist as appropriate to the request made. Refer to Todoist’s API documentation for details about the expected parameters and responses. Drafts will handle wrapping the request in the appropriate OAuth authentication flow.

    Parameters

    • settings: { data?: {}; headers?: {}; method: string; parameters?: {}; url: string }

      an object configuring the request.

      • Optional data?: {}

        A JavaScript object containing data to be encoded into the HTTP body of the request.

        • [x: string]: string
      • Optional headers?: {}

        An object contain key-values to be added as custom headers in the request. There is no need to provide authorization headers, Drafts will add those.

        • [x: string]: string
      • method: string

        The HTTP method, like "GET", "POST", etc.

      • Optional parameters?: {}

        An object containing key-values to be added to the request as URL parameters.

        • [x: string]: string
      • url: string

        The full URL to the endpoint in the Todoist REST API.

    Returns HTTPResponse

Static create

  • create(identifier: string): Todoist
  • Creates a new Todoist object.

    Parameters

    • identifier: string

      Optional string value used to identify a Todoist account. Typically this can be omitted if you only work with one Todoist account in Drafts. Each unique identifier used for Todoist accounts will share credentials - across both action steps and scripts.

    Returns Todoist

Projects Methods

createProject

  • createProject(options: object): object

getProject

  • getProject(projectId: string): object

getProjects

  • getProjects(): object[]

updateProject

  • updateProject(projectId: string, options: object): object

Sections Methods

createSection

  • createSection(options: object): object

getProjectSections

  • getProjectSections(projectId: string): object[]

getSection

  • getSection(sectionId: string): object

getSections

  • getSections(): object[]

updateSection

  • updateSection(sectionId: string, options: object): object

Tasks Methods

closeTask

  • closeTask(taskId: string): boolean
  • Close task (mark complete)

    Parameters

    • taskId: string

    Returns boolean

createTask

  • createTask(options: object): object

getTask

  • getTask(taskId: string): object

getTasks

  • getTasks(options?: object): object[]

reopenTask

  • reopenTask(taskId: string): boolean
  • Reopen task (mark incomplete)

    Parameters

    • taskId: string

    Returns boolean

updateTask

  • updateTask(taskId: string, options: object): object

Generated using TypeDoc

--- Alarm | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Alarm

Alarms are alerts which can be attached to Reminder and Event objects.

Examples

let list = ReminderList.findOrCreate("Errands");
let reminder = list.createReminder();
reminder.title = "Get more paper towels";

let alarm = Alarm.alarmWithDate((3).days().fromNow()); reminder.addAlarm(alarm); reminder.update();

Hierarchy

  • Alarm

Index

Methods

Static alarmWithDate

  • alarmWithDate(date: Date): Alarm
  • Alarm set to remind at a specific date/time.

    Parameters

    • date: Date

    Returns Alarm

Static alarmWithOffset

  • alarmWithOffset(seconds: Number): Alarm
  • Alarm set to remind at a specific number of seconds relative to the start date of the event. Note that alarms created with this methods are only supported on Event objects, not Reminder objects.

    Parameters

    • seconds: Number

    Returns Alarm

Generated using TypeDoc

--- ReminderList | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class ReminderList

ReminderList objects are used to manipulate and create lists in the built-in Reminders app.

Examples

const list = ReminderList.findOrCreate("Groceries");
let reminder = list.createReminder();
reminder.title = "Bananas";
reminder.notes = "Get slightly green ones."
reminder.update();

Hierarchy

  • ReminderList

Index

Properties

Readonly completeTasks

completeTasks: Reminder[]

Reminders in the list which have been marked completed.

Readonly incompleteTasks

incompleteTasks: Reminder[]

Reminders in the list which are NOT completed.

Readonly tasks

tasks: Reminder[]

All reminders in the list.

title

title: string

The name of the list.

Methods

createReminder

update

  • update(): boolean

Static default

Static find

  • Searches for a reminder lists matching the title. If none is found, return undefined.

    Parameters

    • title: string

    Returns ReminderList

Static findOrCreate

  • Searches for a list in the reminders app matching the title. If none is found, creates a new list with that title. If more than one list with the same name exist in Reminders, the first found will be returned.

    Parameters

    • title: string

    Returns ReminderList

Static getAllReminderLists

Generated using TypeDoc

--- Reminder | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Reminder

Reminder objects represent individual tasks in a list in the built-in Reminders app. For examples, see ReminderList documentation.

Hierarchy

  • Reminder

Index

Properties

alarms

alarms: Alarm[]

The alarms assigned to the reminder, if any.

Optional completionDate

completionDate: Date

Completion date of the reminder. This value is set automatically when the isCompleted property is set to true. Setting this property to nil will set isCompleted to false.

Optional dueDate

dueDate: Date

Due date of the reminder

dueDateIncludesTime

dueDateIncludesTime: Boolean

Does the dueDate property include an assigned time. If false, assignments to the dueDate property will ignore time components, making the reminder due on a specific date without a time assigned.

Readonly hasAlarms

hasAlarms: boolean

Returns true if the reminder has any alarms.

identifier

identifier: string

Unique identifier for the reminder.

isCompleted

isCompleted: boolean

Flag indicating if the task has been completed.

list

The list which this task resides in.

location

location: string

Location of the event.

notes

notes: string

Notes associated with the event.

priority

priority: 0 | 1 | 5 | 9

Integer number representing priority. Assign values matching those Apple uses as follows:

  • 0: No priority
  • 1: High
  • 5: Medium
  • 9: Low

Optional startDate

startDate: Date

Start date of the reminder

startDateIncludesTime

startDateIncludesTime: Boolean

Does the startDate property include an assigned time. If false, assignments to the startDate property will ignore time components, making the reminder start on a specific date without a time assigned.

title

title: string

The title of the event.

Methods

addAlarm

  • addAlarm(alarm: Alarm): boolean
  • Add an alarm object to the reminder. Be sure to update() to save after adding alarms. Return true if the alarm was successfully added. Note that reminders only support alarms created with the Alarm.alarmWithDate method.

    Parameters

    Returns boolean

removeAlarms

  • removeAlarms(): void
  • Remove any assigned alarms from the reminder.

    Returns void

update

  • update(): boolean
  • Save the task. Returns true if the task is successfully saved in Reminders.

    Returns boolean

Generated using TypeDoc

--- MicrosoftToDo | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class MicrosoftToDo

Script integration with Microsoft To Do. This object handles OAuth authentication and request signing. The entire Microsoft To Do Graph API can be used with the request method, and convenience methods are provided for common API endpoints to manage tasks and lists.

Working with the return values and parameters for these methods requires an understanding of the JSON objects created and returned by the API, so refer to type specifications in the API Reference for details on values supported in task and lists. Specifically, review the supported properties of the Task and TaskList objects to understand the values included in fetched objects, and to make modifications.

If an API calls fails, typically the result will be an undefined value, and the lastError property will contains error detail information for troubleshooting.

Example

See Examples-Microsoft To Do action group in the Drafts Directory. It contains several example scripted actions.

// create MicrosoftToDo object
let todo = MicrosoftToDo.create();
// create task in "Test" list
let list = todo.findList("Test");
// create task object, more properties available, see API docs
let task = {
"title": `Task Title`,
"importance": "high",
"body": {
"content": "Notes for the task",
"contentType": "text"
};
"dueDateTime": {
"dateTime": Date.today().addDays(1).toISOString(),
"timeZone": "UTC"
}
};
let t = todo.createTask(list, task);

Hierarchy

  • MicrosoftToDo

Index

Constructors

Properties

Linked Resource Methods

Lists Methods

Other Methods

Tasks Methods

Constructors

constructor

Properties

Optional lastError

lastError: string

If a function fails, this property will contain the last error as a string message, otherwise it will be undefined.

lastResponse

lastResponse: any

If a function succeeds, this property will contain the last response returned by the To Do API. The JSON returned by the API will be parsed to an object and placed in this property. Refer to To Do API documentation for details on the contents of this object based on call made.

Linked Resource Methods

createLinkedResource

Lists Methods

createList

findList

  • Get specific list by name. This is a convenience method which will fetch lists and return the first one found with a matching name.

    Parameters

    • name: string

    Returns microsoftToDoTaskList | undefined

getLists

Other Methods

request

  • request(settings: { data?: {}; headers?: {}; method: string; parameters?: {}; url: string }): HTTPResponse
  • Execute a request against the Microsoft To Do API. For successful requests, the HTTPResponse object will contain an object or array or objects decoded from the JSON returned by the API as appropriate to the request made. Refer to API documentation for details about the expected parameters and responses. Drafts will handle wrapping the request in the appropriate OAuth authentication flow. Requests should only be made to endpoints in the Microsoft Graph API which require the Task.ReadWrite authentication scope.

    Parameters

    • settings: { data?: {}; headers?: {}; method: string; parameters?: {}; url: string }

      an object configuring the request.

      • Optional data?: {}

        A JavaScript object containing data to be encoded into the HTTP body of the request.

        • [x: string]: string
      • Optional headers?: {}

        An object contain key-values to be added as custom headers in the request. There is no need to provide authorization headers, Drafts will add those.

        • [x: string]: string
      • method: string

        The HTTP method, like "GET", "POST", "PATCH", etc.

      • Optional parameters?: {}

        An object containing key-values to be added to the request as URL parameters.

        • [x: string]: string
      • url: string

        The full URL to the endpoint in the To Do API.

    Returns HTTPResponse

Static create

  • Creates a new MicrosoftToDo object.

    Parameters

    • identifier: string

      Optional string value used to identify a To Do account. Typically this can be omitted if you only work with one To Do account in Drafts. Each unique identifier used for To Do accounts will share credentials - across both action steps and scripts.

    Returns MicrosoftToDo

Tasks Methods

createTask

getTask

getTasks

updateTask

Generated using TypeDoc

--- WordPress | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class WordPress

Script integration with WordPress sites via the WordPress XML-RPC API. Currently this object has one runMethod function which can be used to call any method available in the XML-RPC interface.

The WordPress API offers access to a wide variety of functions, including posting, but also retrieving information about categories and tags, or reading posts contents.

Drafts WordPress object simplifies working with the XML-RPC interface by accepting input parameters as Javascript objects and converting them to the require XML to make requests of the WordPress site. Similarly, it converts to XML returned by WordPress to Javascript objects. Otherwise it is an exact passthrough, so the WordPress API reference should be used to determine method names (e.g. wp.newPost, wp.getTaxonomies) available, the appropriate parameters to send.

The WordPress XML-RPC API authenticates via username and password, so it is highly recommended you interact only over HTTPS secure connections, and use Credential objects to store host/username/password values, rather than hard-coding them in actions.

Example

// setup values to use in post
let title = "Title of Post"
let body = "Body of Post"

// create credentials for site let cred = Credential.createWithHostUsernamePassword("WordPress", "WordPress * credentials. Include full URL (with http://) of the home page of your WordPress * site in the host field."); cred.authorize();

// create WordPress object and make request let wp = WordPress.create(cred.getValue("host"), 1, "", ""); let method = "wp.newPost" let params = [ 1, // blog_id, in most cases just use 1 cred.getValue("username"), cred.getValue("password"), { "post_title": title, "post_content": body, "post_status": "draft", "terms_names" : { // assign categories and tags "category" : ["Cat1", "BAD"], "post_tag" : ["Test1", "NOT-TAG"] } } ];

let response = wp.runMethod(method, params); if (response.success) { let params = response.params; console.log("Create WordPress post id: " + params[0]); } else { console.log("HTTP Status: " + response.statusCode); console.log("Fault: " + response.error); context.fail(); }

Hierarchy

  • WordPress

Index

Constructors

constructor

  • new WordPress(siteURL: string, blogId: string, username?: string, password?: string): WordPress
  • Create new instance

    Parameters

    • siteURL: string

      This should be the full URL to the home page of the WordPress site. e.g. https://mysite.com or https://mysite.com/blog/.

    • blogId: string

      For most WordPress installations, use 1.

    • Optional username: string

      Username to login to the WordPress site. Optional if only using runMethod, as credentials will be required directly in parameters for those calls.

    • Optional password: string

      Password to login to the WordPress site. Optional if only using runMethod, as credentials will be required directly in parameters for those calls.

    Returns WordPress

Methods

getCategories

  • getCategories(): object[] | undefined

getPost

  • getPost(postId: string): object | undefined

getPostStatusList

  • getPostStatusList(): object[] | undefined

getPosts

  • getPosts(filter?: any): object[] | undefined
  • Parameters

    • Optional filter: any

    Returns object[] | undefined

getTags

  • getTags(): object[] | undefined

getTaxonomies

  • getTaxonomies(): object[] | undefined

getTaxonomy

  • getTaxonomy(taxonomy?: string): object | undefined
  • Parameters

    • Optional taxonomy: string

    Returns object | undefined

getTerms

  • getTerms(taxonomy?: string, filter?: any): object[] | undefined
  • Parameters

    • Optional taxonomy: string
    • Optional filter: any

    Returns object[] | undefined

newPost

  • newPost(content: string): string | undefined

runMethod

  • Run an XML-RPC API method on a WordPress site. Any method name supported by the WordPress XML-RPC API can be used, as long as the authentication information provided has appropriate permissions on the site.

    Parameters

    • methodName: string

      The method name as documented in the WordPress XML-RPC API, for example wp.newPost to create a new post.

    • parameters: any[]

      Parameters should be a Javascript array of parameters for the method being used. These vary depending on the method and should follow the documentation provided by WordPress.

    Returns XMLRPCResponse

Static create

  • create(siteURL: string, blogId: string, username?: string, password?: string): WordPress
  • Create new instance

    Parameters

    • siteURL: string

      This should be the full URL to the home page of the WordPress site. e.g. https://mysite.com or https://mysite.com/blog/.

    • blogId: string

      For most WordPress installations, use 1.

    • Optional username: string

      Username to login to the WordPress site. Optional if only using runMethod, as credentials will be required directly in parameters for those calls.

    • Optional password: string

      Password to login to the WordPress site. Optional if only using runMethod, as credentials will be required directly in parameters for those calls.

    Returns WordPress

Generated using TypeDoc

--- TJSChecklistItem | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class TJSChecklistItem

Represents a Things check list item, which can be added to a Todo. See TJSContainer documentation for details on making requests to Things.

Hierarchy

  • TJSChecklistItem

Index

Properties

Methods

Properties

canceled

canceled: boolean

completed

completed: boolean

title

title: string

Methods

Static create

Generated using TypeDoc

--- HTTP | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class HTTP

The HTTP and HTTPResponse objects are used to run synchronous HTTP requests to communicate with APIs, or just read pages from the web. A full set of custom settings can be passed, and all HTTP methods (GET, POST, PUT, DELETE, etc.) are supported.

Example

var http = HTTP.create(); // create HTTP object

var response = http.request({ "url": "http://myurl.com/api", "method": "POST", "data": { "key":"value" }, "headers": { "HeaderName": "HeaderValue" } });

if (response.success) { var text = response.responseText; var data = response.responseData; } else { console.log(response.statusCode); console.log(response.error); }

Hierarchy

  • HTTP

Index

Constructors

Methods

Constructors

constructor

Methods

request

  • request(settings: { data?: {}; encoding?: "json" | "form"; headers?: {}; method: string; parameters?: {}; password?: string; url: string; username?: string }): HTTPResponse
  • Parameters

    • settings: { data?: {}; encoding?: "json" | "form"; headers?: {}; method: string; parameters?: {}; password?: string; url: string; username?: string }

      An object configuring the request.

      • Optional data?: {}

        An object containing data to be encoded into the HTTP body of the request.

        • [x: string]: string
      • Optional encoding?: "json" | "form"

        Format to encode data in the body of request.

      • Optional headers?: {}

        An object contain key-values to be added as custom headers in the request.

        • [x: string]: string
      • method: string

        The HTTP method, like "GET", "POST", etc.

      • Optional parameters?: {}

        Query parameters to merge with the url. Query parameters can also be part of the original url value.

        • [x: string]: string
      • Optional password?: string

        A password to encode for Basic Authentication.

      • url: string

        The absolute HTTP URL for the request.

      • Optional username?: string

        A username to encode for Basic Authentication.

    Returns HTTPResponse

Static create

Generated using TypeDoc

--- Syntax | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Syntax

Represents a Syntax definition available in the current installation of Drafts.

Example: Find and Assign a Syntax

let syntax = Syntax.find("builtIn", "Markdown");
draft.syntax = syntax;
draft.update();

Hierarchy

  • Syntax

Index

Identification Properties

Methods

Identification Properties

Readonly installURL

installURL: string

URL which can be used to install this Syntax in another installation of Drafts. Useful for sharing and backups.

name

name: string

The name of the syntax definition.

type

The type (builtIn, custom, file) of the syntax definition.

Methods

Static find

  • Search for a syntax definition matching the type and name passed and return it if found. Returns undefined if not found.

    Parameters

    Returns Syntax | undefined

Static getAll

Generated using TypeDoc

--- Workspace | Drafts Script Reference
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Workspace

Represents a Workspace. Can be used to inquire and load workspaces and apply them using methods on the App object.

Example: Find and Load Workspace

// find workspace and load it in drafts list
let workspace = Workspace.find("Projects");
app.applyWorkspace(workspace);

Hierarchy

  • Workspace

Index

Constructors

constructor

Display Properties

archiveIncludesFlagged

archiveIncludesFlagged: boolean

Should flagged drafts be included in archive.

inboxIncludesFlagged

inboxIncludesFlagged: boolean

Should flagged drafts be included in inbox.

Optional loadActionBarGroup

loadActionBarGroup: ActionGroup

Action group to load in Action Bar when applying the workspace.

Optional loadActionListGroup

loadActionListGroup: ActionGroup

Action group to load in action list when applying the workspace.

Optional loadFolder

loadFolder: draftFolderTab

Folder tab to select when applying the workspace.

Optional preferredDarkTheme

preferredDarkTheme: Theme

Preferred dark theme to load when applying the workspace.

Optional preferredLightTheme

preferredLightTheme: Theme

Preferred light theme to load when applying the workspace.

showDate

showDate: boolean

Show date information in list.

showLastAction

showLastAction: boolean

Show last logged action for draft in list.

showPreview

showPreview: boolean

Show preview of draft body in list.

showTags

showTags: boolean

Show draft tags in list.

Filter Properties

endDate

endDate: QueryDate

A QueryDate specifying a date which all drafts in the workspace must be less than or equal to.

queryString

queryString: string

Search string to filter results.

startDate

startDate: QueryDate

A QueryDate specifying a date which all drafts in the workspace must be greater than or equal to.

tagFilter

tagFilter: string

Comma-delimited list tag string like "blue, !green" using "!" to omit a tag.

tagFilterRequireAll

tagFilterRequireAll: boolean

If true, all (AND) tags in the tag filter must match, if false match any of the tags (OR)

Identification Properties

Readonly installURL

installURL: string

URL which can be used to install this Workspace in another installation of Drafts. Useful for sharing and backups.

name

name: string

The n