Skip to content

Instantly share code, notes, and snippets.

@shaun-h shaun-h/ShortcutActions.js
Last active Mar 10, 2020

Embed
What would you like to do?
Script module to make creating Shortcuts Actions easier
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: purple; icon-glyph: magic;
var actionList = [];
const AddAction = (name, inputType, callback) => {
if(actionList == undefined) {
actionList = [];
}
var inputTypesArr = [];
if(Array.isArray(inputType)) {
inputTypesArr = inputType;
}
else if(inputType != undefined && inputType != null) {
inputTypesArr.push(inputType);
}
inputTypesArr.forEach(function (item, index) {
if (["text","url","image","file","name"].indexOf(item) == -1) {
throw new Error("Incorrect input type provided: " + item);
}
});
actionList.push({"name": name, "inputType": inputTypesArr, "callback":callback});
}
const GetActions = () => {
var actions = [];
if(actionList != undefined) {
for(var i = 0; i < actionList.length; i++) {
var action = actionList[i];
actions.push(action.name);
}
}
return {"Actions":actions};
}
const RunAction = async (name) => {
if(actionList == undefined) {
throw new Error("No actions have been defined");
}
for(var i = 0; i < actionList.length; i++) {
var action = actionList[i];
if(action.name == name) {
var params = [];
action.inputType.forEach(function (item, index) {
switch (item) {
case "text":
params.push(args.plainTexts);
break;
case "url":
params.push(args.urls);
break;
case "image":
params.push(args.images);
break;
case "file":
params.push(args.fileURLs);
break;
case "name":
params.push(name);
break;
};
});
switch(params.length) {
case 0:
return await action.callback();
break;
case 1:
return await action.callback(params[0]);
break;
case 2:
return await action.callback(params[0], params[1]);
break;
case 3:
return await action.callback(params[0], params[1], params[2]);
break;
case 4:
return await action.callback(params[0], params[1], params[2], params[3]);
break;
case 5:
return await action.callback(params[0], params[1], params[2], params[3], params[4]);
break;
}
}
}
}
const Run = async () => {
var actionParam = args.shortcutParameter;
if (actionParam == "Script:GetActions" || (module.exports.exposeHelpAsDefault && actionParam == undefined)) {
Script.setShortcutOutput(JSON.stringify(GetActions()));
}
else {
var result = await RunAction(actionParam);
if(result != undefined) {
var output = result;
if(Array.isArray(result)) {
if(result.length > 1) {
output = {"Values":result};
}
else {
output = result[0];
}
}
Script.setShortcutOutput(JSON.stringify(output));
}
else {
Script.setShortcutOutput("No output");
}
}
Script.complete();
}
module.exports.exposeHelpAsDefault = true;
module.exports.AddAction = AddAction;
module.exports.Run = Run;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.