2017-04-17 18:40:55 +09:00
|
|
|
import {EventEmitter} from 'events';
|
2017-04-18 15:48:50 +09:00
|
|
|
import {Menu, MenuItem} from 'electron';
|
2017-04-17 18:40:55 +09:00
|
|
|
import log from './log';
|
|
|
|
import {Account} from './config';
|
|
|
|
|
|
|
|
export function partitionForAccount(account: Account) {
|
|
|
|
return `persist:mstdn:${account.name}:${account.host}`;
|
|
|
|
}
|
|
|
|
|
|
|
|
export default class AccountSwitcher extends EventEmitter {
|
|
|
|
accounts: Account[];
|
|
|
|
current: Account;
|
|
|
|
|
2017-04-18 20:29:07 +09:00
|
|
|
constructor(accounts: Account[]) {
|
2017-04-17 18:40:55 +09:00
|
|
|
super();
|
|
|
|
const submenu = [] as Electron.MenuItemOptions[];
|
|
|
|
|
|
|
|
for (const account of accounts.filter(a => a.name !== '')) {
|
|
|
|
let name = account.name;
|
|
|
|
if (!name.startsWith('@')) {
|
|
|
|
name = '@' + name;
|
|
|
|
}
|
|
|
|
name += '@' + account.host;
|
|
|
|
submenu.push({
|
|
|
|
label: name,
|
|
|
|
type: 'radio',
|
|
|
|
checked: false,
|
2017-04-18 20:29:07 +09:00
|
|
|
click: () => this.switchTo(account),
|
2017-04-17 18:40:55 +09:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
this.accounts = accounts;
|
|
|
|
if (accounts.length === 0) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
submenu[0].checked = true;
|
|
|
|
this.current = accounts[0];
|
|
|
|
|
|
|
|
const item = new MenuItem({
|
|
|
|
label: 'Accounts',
|
|
|
|
type: 'submenu',
|
|
|
|
submenu,
|
|
|
|
});
|
|
|
|
|
|
|
|
const menu = Menu.getApplicationMenu();
|
|
|
|
// Insert item before 'Help'
|
|
|
|
menu.insert(menu.items.length - 1, item);
|
|
|
|
Menu.setApplicationMenu(menu);
|
|
|
|
}
|
|
|
|
|
2017-04-18 20:29:07 +09:00
|
|
|
switchTo(account: Account) {
|
2017-04-17 18:40:55 +09:00
|
|
|
if (this.current.name === account.name && this.current.host === account.host) {
|
|
|
|
log.debug('Current account is already @' + account.name);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
log.debug('Switch to account', account);
|
2017-04-18 20:29:07 +09:00
|
|
|
this.emit('switch', account, this.current);
|
2017-04-17 18:40:55 +09:00
|
|
|
this.current = account;
|
|
|
|
}
|
|
|
|
}
|