Use async/await on background

jh-changes
Shin'ya Ueoka 6 years ago
parent 88238005ab
commit 48e4bccf0d
  1. 68
      src/background/actions/command.js
  2. 13
      src/background/actions/setting.js
  3. 27
      src/background/actions/tab.js
  4. 15
      src/background/components/background.js
  5. 14
      src/background/components/indicator.js
  6. 7
      src/background/components/tab.js
  7. 18
      src/background/index.js
  8. 23
      src/background/shared/completions/bookmarks.js
  9. 27
      src/background/shared/completions/histories.js
  10. 116
      src/background/shared/completions/index.js
  11. 209
      src/background/shared/tabs.js
  12. 30
      src/background/shared/zooms.js

@ -5,56 +5,63 @@ import * as bookmarks from '../shared/bookmarks';
import * as parsers from 'shared/commands/parsers'; import * as parsers from 'shared/commands/parsers';
import * as properties from 'shared/settings/properties'; import * as properties from 'shared/settings/properties';
const openCommand = (url) => { const openCommand = async(url) => {
return browser.tabs.query({ let got = await browser.tabs.query({
active: true, currentWindow: true active: true, currentWindow: true
}).then((gotTabs) => {
if (gotTabs.length > 0) {
return browser.tabs.update(gotTabs[0].id, { url: url });
}
}); });
if (got.length > 0) {
return browser.tabs.update(got[0].id, { url: url });
}
}; };
const tabopenCommand = (url) => { const tabopenCommand = (url) => {
return browser.tabs.create({ url: url }); return browser.tabs.create({ url: url });
}; };
const tabcloseCommand = () => { const tabcloseCommand = async() => {
return browser.tabs.query({ let got = await browser.tabs.query({
active: true, currentWindow: true active: true, currentWindow: true
}).then((tabList) => {
return browser.tabs.remove(tabList.map(tab => tab.id));
}); });
return browser.tabs.remove(got.map(tab => tab.id));
}; };
const winopenCommand = (url) => { const winopenCommand = (url) => {
return browser.windows.create({ url }); return browser.windows.create({ url });
}; };
const bufferCommand = (keywords) => { const bufferCommand = async(keywords) => {
if (keywords.length === 0) { if (keywords.length === 0) {
return Promise.resolve([]); return Promise.resolve([]);
} }
let keywordsStr = keywords.join(' '); let keywordsStr = keywords.join(' ');
return browser.tabs.query({ let got = await browser.tabs.query({
active: true, currentWindow: true active: true, currentWindow: true
}).then((gotTabs) => {
if (gotTabs.length > 0) {
if (isNaN(keywordsStr)) {
return tabs.selectByKeyword(gotTabs[0], keywordsStr);
}
let index = parseInt(keywordsStr, 10) - 1;
return tabs.selectAt(index);
}
}); });
if (got.length === 0) {
return;
}
if (isNaN(keywordsStr)) {
return tabs.selectByKeyword(got[0], keywordsStr);
}
let index = parseInt(keywordsStr, 10) - 1;
return tabs.selectAt(index);
}; };
const addBookmarkCommand = (tab, args) => { const addbookmarkCommand = async(tab, args) => {
if (!args[0]) { if (!args[0]) {
return Promise.resolve(); return;
} }
let item = await bookmarks.create(args.join(' '), tab.url);
return bookmarks.create(args.join(' '), tab.url); if (!item) {
return browser.tabs.sendMessage(tab.id, {
type: messages.CONSOLE_SHOW_ERROR,
text: 'Could not create a bookmark',
});
}
return browser.tabs.sendMessage(tab.id, {
type: messages.CONSOLE_SHOW_INFO,
text: 'Saved current page: ' + item.url,
});
}; };
const setCommand = (args) => { const setCommand = (args) => {
@ -100,18 +107,7 @@ const exec = (tab, line, settings) => {
case 'bdeletes!': case 'bdeletes!':
return tabs.closeTabsByKeywordsForce(args.join(' ')); return tabs.closeTabsByKeywordsForce(args.join(' '));
case 'addbookmark': case 'addbookmark':
return addBookmarkCommand(tab, args).then((item) => { return addbookmarkCommand(tab, args);
if (!item) {
return browser.tabs.sendMessage(tab.id, {
type: messages.CONSOLE_SHOW_ERROR,
text: 'Could not create a bookmark',
});
}
return browser.tabs.sendMessage(tab.id, {
type: messages.CONSOLE_SHOW_INFO,
text: 'Saved current page: ' + item.url,
});
});
case 'set': case 'set':
return setCommand(args); return setCommand(args);
case 'q': case 'q':

@ -1,13 +1,12 @@
import actions from '../actions'; import actions from '../actions';
import * as settingsStorage from 'shared/settings/storage'; import * as settingsStorage from 'shared/settings/storage';
const load = () => { const load = async() => {
return settingsStorage.loadValue().then((value) => { let value = await settingsStorage.loadValue();
return { return {
type: actions.SETTING_SET_SETTINGS, type: actions.SETTING_SET_SETTINGS,
value, value,
}; };
});
}; };
const setProperty = (name, value) => { const setProperty = (name, value) => {

@ -1,19 +1,20 @@
import actions from './index'; import actions from './index';
const openNewTab = (url, openerTabId, background = false, adjacent = false) => { const openNewTab = async(
if (adjacent) { url, openerTabId, background = false, adjacent = false
return browser.tabs.query({ ) => {
active: true, currentWindow: true if (!adjacent) {
}).then((tabs) => { return browser.tabs.create({ url, active: !background });
return browser.tabs.create({
url,
openerTabId,
active: !background,
index: tabs[0].index + 1
});
});
} }
return browser.tabs.create({ url, active: !background }); let tabs = await browser.tabs.query({
active: true, currentWindow: true
});
return browser.tabs.create({
url,
openerTabId,
active: !background,
index: tabs[0].index + 1
});
}; };
const openToTab = (url, tab) => { const openToTab = (url, tab) => {

@ -56,13 +56,12 @@ export default class BackgroundComponent {
} }
} }
broadcastSettingsChanged() { async broadcastSettingsChanged() {
return browser.tabs.query({}).then((tabs) => { let tabs = await browser.tabs.query({});
for (let tab of tabs) { for (let tab of tabs) {
browser.tabs.sendMessage(tab.id, { browser.tabs.sendMessage(tab.id, {
type: messages.SETTINGS_CHANGED, type: messages.SETTINGS_CHANGED,
}); });
} }
});
} }
} }

@ -8,19 +8,17 @@ export default class IndicatorComponent {
messages.onMessage(this.onMessage.bind(this)); messages.onMessage(this.onMessage.bind(this));
browser.browserAction.onClicked.addListener(this.onClicked); browser.browserAction.onClicked.addListener(this.onClicked);
browser.tabs.onActivated.addListener((info) => { browser.tabs.onActivated.addListener(async(info) => {
return browser.tabs.query({ currentWindow: true }).then(() => { await browser.tabs.query({ currentWindow: true });
return this.onTabActivated(info); return this.onTabActivated(info);
});
}); });
} }
onTabActivated(info) { async onTabActivated(info) {
return browser.tabs.sendMessage(info.tabId, { let { enabled } = await browser.tabs.sendMessage(info.tabId, {
type: messages.ADDON_ENABLED_QUERY, type: messages.ADDON_ENABLED_QUERY,
}).then((resp) => {
return this.updateIndicator(resp.enabled);
}); });
return this.updateIndicator(enabled);
} }
onClicked(tab) { onClicked(tab) {

@ -4,10 +4,9 @@ export default class TabComponent {
constructor(store) { constructor(store) {
this.store = store; this.store = store;
browser.tabs.onActivated.addListener((info) => { browser.tabs.onActivated.addListener(async(info) => {
return browser.tabs.query({ currentWindow: true }).then(() => { await browser.tabs.query({ currentWindow: true });
return this.onTabActivated(info); return this.onTabActivated(info);
});
}); });
} }

@ -18,6 +18,15 @@ const store = createStore(reducers, (e, sender) => {
} }
}); });
const checkAndNotifyUpdated = async() => {
let updated = await versions.checkUpdated();
if (!updated) {
return;
}
await versions.notify();
await versions.commit();
};
/* eslint-disable no-unused-vars */ /* eslint-disable no-unused-vars */
const backgroundComponent = new BackgroundComponent(store); const backgroundComponent = new BackgroundComponent(store);
const operationComponent = new OperationComponent(store); const operationComponent = new OperationComponent(store);
@ -27,11 +36,4 @@ const indicatorComponent = new IndicatorComponent(store);
store.dispatch(settingActions.load()); store.dispatch(settingActions.load());
versions.checkUpdated().then((updated) => { checkAndNotifyUpdated();
if (!updated) {
return;
}
return versions.notify();
}).then(() => {
return versions.commit();
});

@ -1,15 +1,14 @@
const getCompletions = (keywords) => { const getCompletions = async(keywords) => {
return browser.bookmarks.search({ query: keywords }).then((items) => { let items = await browser.bookmarks.search({ query: keywords });
return items.filter((item) => { return items.filter((item) => {
let url = undefined; let url = undefined;
try { try {
url = new URL(item.url); url = new URL(item.url);
} catch (e) { } catch (e) {
return false; return false;
} }
return item.type === 'bookmark' && url.protocol !== 'place:'; return item.type === 'bookmark' && url.protocol !== 'place:';
}).slice(0, 10); }).slice(0, 10);
});
}; };
export { getCompletions }; export { getCompletions };

@ -61,23 +61,22 @@ const reduceByOrigin = (items, min) => {
return filtered; return filtered;
}; };
const getCompletions = (keyword) => { const getCompletions = async(keyword) => {
return browser.history.search({ let historyItems = await browser.history.search({
text: keyword, text: keyword,
startTime: 0, startTime: 0,
}).then((historyItems) => {
return [historyItems.map(item => [item, new URL(item.url)])]
.map(filterEmptyTitle)
.map(filterHttp)
.map(filterClosedPath)
.map(items => reduceByPathname(items, 10))
.map(items => reduceByOrigin(items, 10))
.map(items => items
.sort((x, y) => x[0].visitCount < y[0].visitCount)
.slice(0, 10)
.map(item => item[0])
)[0];
}); });
return [historyItems.map(item => [item, new URL(item.url)])]
.map(filterEmptyTitle)
.map(filterHttp)
.map(filterClosedPath)
.map(items => reduceByPathname(items, 10))
.map(items => reduceByOrigin(items, 10))
.map(items => items
.sort((x, y) => x[0].visitCount < y[0].visitCount)
.slice(0, 10)
.map(item => item[0])
)[0];
}; };
export { getCompletions }; export { getCompletions };

@ -12,76 +12,66 @@ const getSearchCompletions = (command, keywords, searchConfig) => {
return Promise.resolve(engineItems); return Promise.resolve(engineItems);
}; };
const getHistoryCompletions = (command, keywords) => { const getHistoryCompletions = async(command, keywords) => {
return histories.getCompletions(keywords).then((pages) => { let items = await histories.getCompletions(keywords);
return pages.map((page) => { return items.map((page) => {
return { return {
caption: page.title, caption: page.title,
content: command + ' ' + page.url, content: command + ' ' + page.url,
url: page.url url: page.url
}; };
});
}); });
}; };
const getBookmarksCompletions = (command, keywords) => { const getBookmarksCompletions = async(command, keywords) => {
return bookmarks.getCompletions(keywords).then((items) => { let items = await bookmarks.getCompletions(keywords);
return items.map((item) => { return items.map(item => ({
return { caption: item.title,
caption: item.title, content: command + ' ' + item.url,
content: command + ' ' + item.url, url: item.url,
url: item.url, }));
};
});
});
}; };
const getOpenCompletions = (command, keywords, searchConfig) => { const getOpenCompletions = async(command, keywords, searchConfig) => {
return Promise.all([ let engineItems = await getSearchCompletions(command, keywords, searchConfig);
getSearchCompletions(command, keywords, searchConfig), let historyItems = await getHistoryCompletions(command, keywords);
getHistoryCompletions(command, keywords), let bookmarkItems = await getBookmarksCompletions(command, keywords);
getBookmarksCompletions(command, keywords), let completions = [];
]).then(([engineItems, historyItems, bookmarkItems]) => { if (engineItems.length > 0) {
let completions = []; completions.push({
if (engineItems.length > 0) { name: 'Search Engines',
completions.push({ items: engineItems
name: 'Search Engines', });
items: engineItems }
}); if (historyItems.length > 0) {
} completions.push({
if (historyItems.length > 0) { name: 'History',
completions.push({ items: historyItems
name: 'History', });
items: historyItems }
}); if (bookmarkItems.length > 0) {
} completions.push({
if (bookmarkItems.length > 0) { name: 'Bookmarks',
completions.push({ items: bookmarkItems
name: 'Bookmarks', });
items: bookmarkItems }
}); return completions;
}
return completions;
});
}; };
const getBufferCompletions = (command, keywords, excludePinned) => { const getBufferCompletions = async(command, keywords, excludePinned) => {
return tabs.getCompletions(keywords, excludePinned).then((got) => { let items = await tabs.getCompletions(keywords, excludePinned);
let items = got.map((tab) => { items = items.map(tab => ({
return { caption: tab.title,
caption: tab.title, content: command + ' ' + tab.title,
content: command + ' ' + tab.title, url: tab.url,
url: tab.url, icon: tab.favIconUrl
icon: tab.favIconUrl }));
}; return [
}); {
return [ name: 'Buffers',
{ items: items
name: 'Buffers', }
items: items ];
}
];
});
}; };
const getCompletions = (line, settings) => { const getCompletions = (line, settings) => {

@ -1,143 +1,127 @@
import * as tabCompletions from './completions/tabs'; import * as tabCompletions from './completions/tabs';
const closeTab = (id) => { const closeTab = async(id) => {
return browser.tabs.get(id).then((tab) => { let tab = await browser.tabs.get(id);
if (!tab.pinned) { if (!tab.pinned) {
return browser.tabs.remove(id); return browser.tabs.remove(id);
} }
});
}; };
const closeTabForce = (id) => { const closeTabForce = (id) => {
return browser.tabs.remove(id); return browser.tabs.remove(id);
}; };
const queryByKeyword = (keyword, excludePinned = false) => { const queryByKeyword = async(keyword, excludePinned = false) => {
return browser.tabs.query({ currentWindow: true }).then((tabs) => { let tabs = await browser.tabs.query({ currentWindow: true });
return tabs.filter((t) => { return tabs.filter((t) => {
return t.url.toLowerCase().includes(keyword.toLowerCase()) || return t.url.toLowerCase().includes(keyword.toLowerCase()) ||
t.title && t.title.toLowerCase().includes(keyword.toLowerCase()); t.title && t.title.toLowerCase().includes(keyword.toLowerCase());
}).filter((t) => { }).filter((t) => {
return !(excludePinned && t.pinned); return !(excludePinned && t.pinned);
});
}); });
}; };
const closeTabByKeywords = (keyword) => { const closeTabByKeywords = async(keyword) => {
return queryByKeyword(keyword, false).then((tabs) => { let tabs = await queryByKeyword(keyword, false);
if (tabs.length === 0) { if (tabs.length === 0) {
throw new Error('No matching buffer for ' + keyword); throw new Error('No matching buffer for ' + keyword);
} else if (tabs.length > 1) { } else if (tabs.length > 1) {
throw new Error('More than one match for ' + keyword); throw new Error('More than one match for ' + keyword);
} }
browser.tabs.remove(tabs[0].id); return browser.tabs.remove(tabs[0].id);
});
};
const closeTabByKeywordsForce = (keyword) => {
return queryByKeyword(keyword, true).then((tabs) => {
if (tabs.length === 0) {
throw new Error('No matching buffer for ' + keyword);
} else if (tabs.length > 1) {
throw new Error('More than one match for ' + keyword);
}
browser.tabs.remove(tabs[0].id);
});
}; };
const closeTabsByKeywords = (keyword) => { const closeTabByKeywordsForce = async(keyword) => {
tabCompletions.getCompletions(keyword).then((tabs) => { let tabs = await queryByKeyword(keyword, true);
let tabs2 = tabs.filter(tab => !tab.pinned); if (tabs.length === 0) {
browser.tabs.remove(tabs2.map(tab => tab.id)); throw new Error('No matching buffer for ' + keyword);
}); } else if (tabs.length > 1) {
throw new Error('More than one match for ' + keyword);
}
return browser.tabs.remove(tabs[0].id);
}; };
const closeTabsByKeywordsForce = (keyword) => { const closeTabsByKeywords = async(keyword) => {
tabCompletions.getCompletions(keyword).then((tabs) => { let tabs = await tabCompletions.getCompletions(keyword);
browser.tabs.remove(tabs.map(tab => tab.id)); tabs = tabs.filter(tab => !tab.pinned);
}); return browser.tabs.remove(tabs.map(tab => tab.id));
}; };
const reopenTab = () => { const closeTabsByKeywordsForce = async(keyword) => {
let window = null; let tabs = await tabCompletions.getCompletions(keyword);
return browser.windows.getCurrent().then().then((w) => { return browser.tabs.remove(tabs.map(tab => tab.id));
window = w;
return browser.sessions.getRecentlyClosed();
}).then((sessions) => {
let session = sessions.find((s) => {
return s.tab && s.tab.windowId === window.id;
});
if (!session) {
return;
}
if (session.tab) {
return browser.sessions.restore(session.tab.sessionId);
}
return browser.sessions.restore(session.window.sessionId);
});
}; };
const selectAt = (index) => { const reopenTab = async() => {
return browser.tabs.query({ currentWindow: true }).then((tabs) => { let window = await browser.windows.getCurrent();
if (tabs.length < 2) { let sessions = await browser.sessions.getRecentlyClosed();
return; let session = sessions.find((s) => {
} return s.tab && s.tab.windowId === window.id;
if (index < 0 || tabs.length <= index) {
throw new RangeError(`tab ${index + 1} does not exist`);
}
let id = tabs[index].id;
return browser.tabs.update(id, { active: true });
}); });
if (!session) {
return;
}
if (session.tab) {
return browser.sessions.restore(session.tab.sessionId);
}
return browser.sessions.restore(session.window.sessionId);
};
const selectAt = async(index) => {
let tabs = await browser.tabs.query({ currentWindow: true });
if (tabs.length < 2) {
return;
}
if (index < 0 || tabs.length <= index) {
throw new RangeError(`tab ${index + 1} does not exist`);
}
let id = tabs[index].id;
return browser.tabs.update(id, { active: true });
}; };
const selectByKeyword = (current, keyword) => { const selectByKeyword = async(current, keyword) => {
return queryByKeyword(keyword).then((tabs) => { let tabs = await queryByKeyword(keyword);
if (tabs.length === 0) { if (tabs.length === 0) {
throw new RangeError('No matching buffer for ' + keyword); throw new RangeError('No matching buffer for ' + keyword);
}
for (let tab of tabs) {
if (tab.index > current.index) {
return browser.tabs.update(tab.id, { active: true });
} }
for (let tab of tabs) { }
if (tab.index > current.index) { return browser.tabs.update(tabs[0].id, { active: true });
return browser.tabs.update(tab.id, { active: true });
}
}
return browser.tabs.update(tabs[0].id, { active: true });
});
}; };
const selectPrevTab = (current, count) => { const selectPrevTab = async(current, count) => {
return browser.tabs.query({ currentWindow: true }).then((tabs) => { let tabs = await browser.tabs.query({ currentWindow: true });
if (tabs.length < 2) { if (tabs.length < 2) {
return; return;
} }
let select = (current - count + tabs.length) % tabs.length; let select = (current - count + tabs.length) % tabs.length;
let id = tabs[select].id; let id = tabs[select].id;
return browser.tabs.update(id, { active: true }); return browser.tabs.update(id, { active: true });
});
}; };
const selectNextTab = (current, count) => { const selectNextTab = async(current, count) => {
return browser.tabs.query({ currentWindow: true }).then((tabs) => { let tabs = await browser.tabs.query({ currentWindow: true });
if (tabs.length < 2) { if (tabs.length < 2) {
return; return;
} }
let select = (current + count) % tabs.length; let select = (current + count) % tabs.length;
let id = tabs[select].id; let id = tabs[select].id;
return browser.tabs.update(id, { active: true }); return browser.tabs.update(id, { active: true });
});
}; };
const selectFirstTab = () => { const selectFirstTab = async() => {
return browser.tabs.query({ currentWindow: true }).then((tabs) => { let tabs = await browser.tabs.query({ currentWindow: true });
let id = tabs[0].id; let id = tabs[0].id;
return browser.tabs.update(id, { active: true }); return browser.tabs.update(id, { active: true });
});
}; };
const selectLastTab = () => { const selectLastTab = async() => {
return browser.tabs.query({ currentWindow: true }).then((tabs) => { let tabs = await browser.tabs.query({ currentWindow: true });
let id = tabs[tabs.length - 1].id; let id = tabs[tabs.length - 1].id;
return browser.tabs.update(id, { active: true }); return browser.tabs.update(id, { active: true });
});
}; };
const selectTab = (id) => { const selectTab = (id) => {
@ -152,14 +136,11 @@ const reload = (current, cache) => {
}; };
const updateTabPinned = (current, pinned) => { const updateTabPinned = (current, pinned) => {
return browser.tabs.query({ currentWindow: true, active: true }) return browser.tabs.update(current.id, { pinned });
.then(() => {
return browser.tabs.update(current.id, { pinned: pinned });
});
}; };
const toggleTabPinned = (current) => { const toggleTabPinned = (current) => {
updateTabPinned(current, !current.pinned); return updateTabPinned(current, !current.pinned);
}; };
const duplicate = (id) => { const duplicate = (id) => {

@ -9,26 +9,20 @@ const ZOOM_SETTINGS = [
1.10, 1.25, 1.50, 1.75, 2.00, 2.50, 3.00 1.10, 1.25, 1.50, 1.75, 2.00, 2.50, 3.00
]; ];
const zoomIn = (tabId = undefined) => { const zoomIn = async(tabId = undefined) => {
return browser.tabs.getZoom(tabId).then((factor) => { let current = await browser.tabs.getZoom(tabId);
for (let f of ZOOM_SETTINGS) { let factor = ZOOM_SETTINGS.find(f => f > current);
if (f > factor) { if (factor) {
browser.tabs.setZoom(tabId, f); return browser.tabs.setZoom(tabId, factor);
break; }
}
}
});
}; };
const zoomOut = (tabId = undefined) => { const zoomOut = async(tabId = undefined) => {
return browser.tabs.getZoom(tabId).then((factor) => { let current = await browser.tabs.getZoom(tabId);
for (let f of [].concat(ZOOM_SETTINGS).reverse()) { let factor = [].concat(ZOOM_SETTINGS).reverse().find(f => f < current);
if (f < factor) { if (factor) {
browser.tabs.setZoom(tabId, f); return browser.tabs.setZoom(tabId, factor);
break; }
}
}
});
}; };
const neutral = (tabId = undefined) => { const neutral = (tabId = undefined) => {