From 4d4aaa2c4ba9f09e23882287ce868c820aa900ee Mon Sep 17 00:00:00 2001 From: Shin'ya Ueoka Date: Fri, 20 Jul 2018 22:42:21 +0900 Subject: Move commands to background/shared --- src/background/shared/commands/docs.js | 11 ++++++ src/background/shared/commands/parsers.js | 59 +++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 src/background/shared/commands/docs.js create mode 100644 src/background/shared/commands/parsers.js (limited to 'src/background/shared/commands') diff --git a/src/background/shared/commands/docs.js b/src/background/shared/commands/docs.js new file mode 100644 index 0000000..c73eb71 --- /dev/null +++ b/src/background/shared/commands/docs.js @@ -0,0 +1,11 @@ +export default { + set: 'Set a value of the property', + open: 'Open a URL or search by keywords in current tab', + tabopen: 'Open a URL or search by keywords in new tab', + winopen: 'Open a URL or search by keywords in new window', + buffer: 'Sekect tabs by matched keywords', + bdelete: 'Close a certain tab matched by keywords', + bdeletes: 'Close all tabs matched by keywords', + quit: 'Close the current tab', + quitall: 'Close all tabs', +}; diff --git a/src/background/shared/commands/parsers.js b/src/background/shared/commands/parsers.js new file mode 100644 index 0000000..fb37d2a --- /dev/null +++ b/src/background/shared/commands/parsers.js @@ -0,0 +1,59 @@ +const normalizeUrl = (args, searchConfig) => { + let concat = args.join(' '); + try { + return new URL(concat).href; + } catch (e) { + if (concat.includes('.') && !concat.includes(' ')) { + return 'http://' + concat; + } + let query = concat; + let template = searchConfig.engines[ + searchConfig.default + ]; + for (let key in searchConfig.engines) { + if (args[0] === key) { + query = args.slice(1).join(' '); + template = searchConfig.engines[key]; + } + } + return template.replace('{}', encodeURIComponent(query)); + } +}; + +const mustNumber = (v) => { + let num = Number(v); + if (isNaN(num)) { + throw new Error('Not number: ' + v); + } + return num; +}; + +const parseSetOption = (word, types) => { + let [key, value] = word.split('='); + if (value === undefined) { + value = !key.startsWith('no'); + key = value ? key : key.slice(2); + } + let type = types[key]; + if (!type) { + throw new Error('Unknown property: ' + key); + } + if (type === 'boolean' && typeof value !== 'boolean' || + type !== 'boolean' && typeof value === 'boolean') { + throw new Error('Invalid argument: ' + word); + } + + switch (type) { + case 'string': return [key, value]; + case 'number': return [key, mustNumber(value)]; + case 'boolean': return [key, value]; + } +}; + +const parseCommandLine = (line) => { + let words = line.trim().split(/ +/); + let name = words.shift(); + return [name, words]; +}; + +export { normalizeUrl, parseCommandLine, parseSetOption }; -- cgit v1.2.3