-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathmain.js
63 lines (51 loc) · 2.06 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import auth from './auth.js';
import ui from './ui.js';
// Commands should be an array of 'command' objects,
// which should have the properties: { name, desc, scopes, run }.
import commands from './commands.js';
// Set command options into UI.
ui.state.commands = commands.map((c, i) => { return { value: i, text: c.name }; });
// On RUN button click run the selected command, the <select>.value is the index into the commands array.
ui.elements.buttonRunCommand.addEventListener('click', () => runCommand(commands[ui.elements.selectCommands.value]));
// On REFRESH button click clear auth and reset UI.
ui.elements.buttonSigninReset.addEventListener('click', () => resetSignin());
const gapiScopes = distillCommandScopes(commands);
// Initialize the UI and then initialize Auth (with gapi & scopes).
ui.init(async (gapiClientId) => {
if (!gapiClientId) {
console.error('No GAPI ClientID provided');
return;
}
await auth.init(gapiClientId, gapiScopes, (usernameOrError) => { ui.state.identity = usernameOrError; });
auth.renderButton(ui.elements.containerSigninButton.id);
});
async function runCommand(selectedCommand) {
if (!selectedCommand.run || typeof selectedCommand.run !== 'function') {
console.error(`run command failed: no run function for '${selectedCommand.name}'`);
return;
}
ui.state.results = null;
ui.state.running = true;
try {
ui.state.results = await selectedCommand.run();
}
catch (err) {
throw err;
}
finally {
ui.state.running = false;
}
}
function resetSignin() {
auth.reset();
ui.state.identity = null;
ui.state.results = null;
}
function distillCommandScopes(commands) {
let scopes = commands
.map(cmd => cmd.scopes.split(' ')) // Get all the scopes split up into their own arrays.
.reduce((result, scopes) => result.concat(scopes), []); // Concat (flatten) into single array.
scopes = new Set(scopes); // The Set type will eliminate duplicates (kinda hacky).
scopes = [...scopes].join(' '); // Turn into array using spread operator (...) and join into space separated string.
return scopes;
}