Merge pull request #3 from bThink-BGU/refactor

Improved error handling
This commit is contained in:
Achiya Elyasaf
2023-08-06 09:51:39 +03:00
committed by GitHub
7 changed files with 126 additions and 153 deletions

View File

@@ -5,7 +5,7 @@
},
"content_scripts": [
{
"js": ["scripts/jquery.js", "scripts/content.js", "scripts/utils.js"],
"js": ["scripts/jquery.js", "scripts/content.js"],
"matches": ["https://*.overleaf.com/project/*"]
}
],
@@ -36,8 +36,7 @@
}
},
"background": {
"service_worker": "scripts/service-worker.js",
"type": "module"
"service_worker": "scripts/service-worker.js"
},
"permissions": ["storage", "tabs"],
"manifest_version": 3,

View File

@@ -8,14 +8,15 @@ body {
.extension-title {
font-size: 24px;
color: #4a4a4a;
margin-bottom: 20px;
margin-bottom: 10px;
}
.form-container {
background-color: #fff;
border-radius: 5px;
margin: 10px 0;
padding: 20px;
margin-bottom: 10px;
padding: 10px;
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
}
@@ -38,6 +39,14 @@ body {
margin-bottom: 10px;
}
.btn-container {
display: flex;
align-items: center;
justify-content: space-between;
margin-left: 3px;
margin-right: 3px;
}
.btn {
font-size: 14px;
padding: 8px 16px;
@@ -46,9 +55,9 @@ body {
border: none;
border-radius: 4px;
cursor: pointer;
margin: 5px 0;
margin: 5px 5px 0 5px;
transition: background-color 0.3s;
width: 300px;
width: 200px;
}
.btn:hover {
@@ -70,7 +79,6 @@ body {
}
#controls {
margin-top: 30px;
display: flex;
flex-direction: column;
}
@@ -78,7 +86,8 @@ body {
.control {
display: flex;
justify-content: space-between;
margin-bottom: 10px;
margin-bottom: 5px;
margin-top: 5px;
}
.input {
@@ -103,7 +112,7 @@ body {
.settings-text {
font-size: 18px;
color: #4a4a4a;
margin-bottom: 20px;
margin-bottom: 10px;
}
.settings-container {
@@ -115,7 +124,8 @@ body {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
margin-bottom: 3px;
margin-top: 3px;
}
.settings-item-text {
@@ -126,8 +136,8 @@ body {
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
width: 40px;
height: 24px;
}
.switch input {
@@ -150,8 +160,8 @@ body {
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
height: 16px;
width: 16px;
left: 4px;
bottom: 4px;
background-color: white;
@@ -163,11 +173,11 @@ input:checked + .slider {
}
input:checked + .slider:before {
transform: translateX(26px);
transform: translateX(16px);
}
.slider.round {
border-radius: 34px;
border-radius: 24px;
}
.slider.round:before {

View File

@@ -1,59 +1,62 @@
<html>
<head>
<head>
<script src="/scripts/jquery.js"></script>
<script src="/scripts/utils.js" type="module"></script>
<script src="/popup/popup.js" type="module"></script>
<link rel="stylesheet" href="/popup/popup.css" />
</head>
<body>
<h1 class="extension-title">LeafLLM: an AI-powered Overleaf</h1>
<div id="controls" class="form-container">
<link rel="stylesheet" href="/popup/popup.css"/>
</head>
<body>
<h1 class="extension-title">LeafLLM: an AI-powered Overleaf</h1>
<div id="controls" class="form-container">
<div class="control">
<div class="input"><span>ALT</span><span>I</span></div>
<div class="input" id="shortcut-Improve"><span>ALT</span><span>I</span></div>
<div class="effect">Improve selected text.</div>
</div>
<div class="control">
<div class="input"><span>ALT</span><span>C</span></div>
<div class="input" id="shortcut-Complete"><span>ALT</span><span>C</span></div>
<div class="effect">Complete selected text.</div>
</div>
<div class="control">
<div class="input"><span>ALT</span><span>A</span></div>
<div class="input" id="shortcut-Ask"><span>ALT</span><span>A</span></div>
<div class="effect">Ask GPT.</div>
</div>
</div>
<div id="settings-form" class="form-container">
</div>
<div id="settings-form" class="form-container">
<div class="settings-text">Settings</div>
<div class="settings-container">
<div class="settings-item">
<div class="settings-item-text">Text Improvement</div>
<label class="switch">
<input name="text-Improve" class="settings-item-checkbox" type="checkbox" />
<input name="text-Improve" class="settings-item-checkbox" type="checkbox"/>
<span class="slider round"></span>
</label>
</div>
<div class="settings-item">
<div class="settings-item-text">Text Completion</div>
<label class="switch">
<input name="text-Complete" class="settings-item-checkbox" type="checkbox" />
<input name="text-Complete" class="settings-item-checkbox" type="checkbox"/>
<span class="slider round"></span>
</label>
</div>
<div class="settings-item">
<div class="settings-item-text">Ask</div>
<label class="switch">
<input name="text-Ask" class="settings-item-checkbox" type="checkbox" />
<input name="text-Ask" class="settings-item-checkbox" type="checkbox"/>
<span class="slider round"></span>
</label>
</div>
</div>
</div>
<div id="api-token-form" class="form-container">
</div>
<div id="api-token-form" class="form-container">
<div class="api-token-text"><span>API Token is </span><span class="api-token-status">not set</span></div>
<input class="api-token-input" name="api-token" placeholder="OpenAI API Token" type="text" />
<div class="message">To get an API key, go to <a href="https://platform.openai.com/account/api-keys">https://platform.openai.com/account/api-keys</a> </div>
<input class="api-token-input" name="api-token" placeholder="OpenAI API Token" type="text"/>
<div class="message">To get an API key, go to <a href="https://platform.openai.com/account/api-keys">https://platform.openai.com/account/api-keys</a>
</div>
<div class="btn-container">
<button class="submit btn">Set API Token</button>
<button class="clear btn">Reset API Token</button>
</div>
<div id="message-box" class="message-box"></div>
</body>
</div>
<div id="message-box" class="message-box"></div>
</body>
</html>

View File

@@ -1,5 +1,3 @@
import {setSetting} from '../scripts/utils.js'
const apiKeyRegex = /sk-[a-zA-Z0-9]{48}/
function addMessage(message) {
@@ -25,10 +23,12 @@ async function refreshStorage() {
.map(({ key, shortcut }) => `${shortcut} for ${key}`)
.join(', ')
if (bindingFailures.length > 0) {
addErrorMessage(`Could not bound the following shortcuts:\n${bindingFailures}.\nYou can set it manually at <a href="chrome://extensions/shortcuts">chrome://extensions/shortcuts</a>.`)
addErrorMessage(`Could not bind the following shortcuts:\n${bindingFailures}.\nYou can set it manually at <a href="chrome://extensions/shortcuts">chrome://extensions/shortcuts</a>.`)
}
Object.values(settings).forEach(({ key, status }) => {
Object.values(settings).forEach(({ key, status, shortcut }) => {
$(`#settings-form input[name='text-${key}']:checkbox`).prop('checked', status === 'enabled')
let shortcut2 = status === 'error' ? 'not set' : shortcut
$(`#shortcut-${key}`).html(`<span>${shortcut2}</span>`)
})
})
}
@@ -48,13 +48,9 @@ async function handleAPITokenSet(event) {
return
}
try {
chrome.storage.local.set({ openAIAPIKey }).then(refreshStorage)
} catch (error) {
console.log(error)
addErrorMessage('Failed to set API Token.')
return
}
chrome.storage.local.set({ openAIAPIKey })
.then(refreshStorage)
.catch((error) => addErrorMessage(`Failed to remove API Token. Error: ${error}`))
}
async function handleAPITokenClear(event) {
@@ -63,29 +59,24 @@ async function handleAPITokenClear(event) {
clearMessages()
try {
chrome.storage.local.remove('openAIAPIKey').then(refreshStorage)
} catch (error) {
console.log(error)
addErrorMessage('Failed to remove API Token.')
return
}
chrome.storage.local.remove('openAIAPIKey')
.then(refreshStorage)
.catch((error) => addErrorMessage(`Failed to remove API Token. Error: ${error}`))
}
function makeHandleSettingChange(key) {
async function makeHandleSettingChange(key) {
return async (event) => {
event.preventDefault()
event.stopPropagation()
clearMessages()
const value = event.target.checked
chrome.storage.local.get(key).then(setting => {
if(setting[key].status !== 'error') {
const setting = await chrome.storage.local.get(key)
if (setting[key].status !== 'error') {
setting[key].status = value ? 'enabled' : 'disabled'
setSetting(setting[key].key, setting[key])
await chrome.storage.local.set({ [key]: setting[key] })
}
return refreshStorage()
})
}
}
@@ -97,5 +88,5 @@ $(document).ready(async function () {
commands.forEach((key) => {
$(`#settings-form input[name='text-${key}']:checkbox`).on('change', makeHandleSettingChange(key))
})
await refreshStorage()
return refreshStorage()
})

View File

@@ -39,9 +39,8 @@ class OpenAIAPI {
temperature: 0.5
}
const result = await this.query('completions', data)
return result[0].text
return this.query('completions', data)
.then(result => result[0].text)
}
async improveText(text) {
@@ -54,9 +53,8 @@ class OpenAIAPI {
temperature: 0.5
}
const result = await this.query('edits', data)
return result[0].text
return this.query('edits', data)
.then(result => result[0].text)
}
}
@@ -70,14 +68,10 @@ function replaceSelectedText(replacementText, selection) {
}
}
async function settingIsEnabled(setting) {
let result
try {
result = await chrome.storage.local.get(setting)
} catch (error) {
return false
}
return result[setting]
async function settingIsEnabled(key) {
return chrome.storage.local.get(key)
.then(setting => 'enabled' === setting[key].status)
.catch(() => false)
}
function commentText(text) {
@@ -91,7 +85,7 @@ function commentText(text) {
}
async function improveTextHandler(openAI) {
if (!(await settingIsEnabled('textImprovement'))) throw new Error('Text improvement is not enabled.')
if (!(await settingIsEnabled('Improve'))) throw new Error('Text improvement is not enabled.')
const selection = window.getSelection()
const selectedText = selection.toString()
if (!selectedText) return
@@ -101,20 +95,20 @@ async function improveTextHandler(openAI) {
}
async function completeTextHandler(openAI) {
if (!(await settingIsEnabled('textCompletion'))) throw new Error('Text completion is not enabled.')
if (!(await settingIsEnabled('Complete'))) throw new Error('Text completion is not enabled.')
const selection = window.getSelection()
const selectedText = selection.toString()
if (!selectedText) return
const editedText = await openAI.completeText(selectedText)
replaceSelectedText(selectedText + editedText, selection)
const editedText = (await openAI.completeText(selectedText)).trimStart()
replaceSelectedText(selectedText + '\n' + editedText, selection)
}
async function askHandler(openAI) {
if (!(await settingIsEnabled('textAsk'))) throw new Error('Text ask is not enabled.')
if (!(await settingIsEnabled('Ask'))) throw new Error('Ask is not enabled.')
const selection = window.getSelection()
const selectedText = selection.toString()
if (!selectedText) return
const editedText = await openAI.completeText('In Latex, ' + selectedText)
const editedText = (await openAI.completeText('In latex, ' + selectedText)).trimStart()
replaceSelectedText(editedText, selection)
}
@@ -130,28 +124,38 @@ function setAPIKey(key) {
currentAPIKey = key
if (currentAPIKey) {
openAI = new OpenAIAPI(currentAPIKey)
console.log('LeafLLM: OpenAI API key set, enabling LeafLLM features.')
log('OpenAI API key set, enabling LeafLLM features.')
} else {
openAI = undefined
console.log('LeafLLM: OpenAI API key is not set, LeafLLM features are disabled.')
log('OpenAI API key is not set, LeafLLM features are disabled.')
}
}
function handleCommand(command) {
if (command === 'Improve') {
improveTextHandler(openAI).catch(e => error(`Failed to execute the '${command}' command. Error message: ${e}`))
improveTextHandler(openAI).catch(e => error(`Failed to execute the '${command}' command.`, e))
} else if (command === 'Complete') {
completeTextHandler(openAI).catch(e => error(`Failed to execute the '${command}' command. Error message: ${e}`))
completeTextHandler(openAI).catch(e => error(`Failed to execute the '${command}' command.`, e))
} else if (command === 'Ask') {
askHandler(openAI).catch(e => error(`Failed to execute the '${command}' command. Error message: ${e}`))
askHandler(openAI).catch(e => error(`Failed to execute the '${command}' command.`, e))
}
}
function error(msg) {
function error(msg, error) {
if(error) {
msg += ` Error message: ${error.message}`
if(error.cause) {
console.error(`\nCause: ${JSON.stringify(error.cause)}`)
}
}
customAlert(msg)
console.error(`LeafLLM: ${msg}`)
}
function log(msg) {
console.log(`LeafLLM: ${msg}`)
}
function customAlert(msg,duration)
{
if(!duration) duration = 4000;
@@ -168,7 +172,7 @@ function customAlert(msg,duration)
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
console.log(`Received request: ${JSON.stringify(request)}`)
log(`Received request: ${JSON.stringify(request)}`)
if (request.command === 'setup') {
setAPIKey(request.apiKey)
} else {

View File

@@ -1,5 +1,3 @@
import {setSetting} from './utils.js'
const settings = [
{ key: 'Complete', shortcut: 'Alt+C', status: 'enabled', type: 'Command' },
{ key: 'Improve', shortcut: 'Alt+I', status: 'enabled', type: 'Command' },
@@ -9,7 +7,7 @@ const settings = [
async function sendMessage(message) {
const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true })
if (tab == null || tab.url?.startsWith('chrome://')) return undefined
const response = await chrome.tabs.sendMessage(tab.id, message)
chrome.tabs.sendMessage(tab.id, message)
// do something with response here, not outside the function
// console.log(response)
}
@@ -41,7 +39,7 @@ async function checkCommandShortcuts() {
if (shortcut === '') {
command.status = 'error'
}
setSetting(command.key, command)
chrome.storage.local.set({ [command.key]: command })
}
}
})

View File

@@ -1,32 +0,0 @@
/**
* Set a setting in storage {@link https://developer.chrome.com/docs/extensions/reference/storage/#type-StorageArea:~:text=to%20the%20callback.-,set,-void}
* @param key
* @param value
* @param {function}[callback] Optional callback function
*/
export async function setSetting(key, value, callback) {
let obj = {}
obj[key] = value
if (typeof callback === 'undefined') {
chrome.storage.local.set(obj).catch(error => {
console.log(`Failed to set ${key} setting. Error: ${error}`)
})
} else {
chrome.storage.local.set(obj, callback).catch(error => {
console.log(`Failed to set ${key} setting. Error: ${error}`)
})
}
}
/**
* Get a setting from storage
* @param {string | string[] | object} [keys=null] - The keys to get (see {@link https://developer.chrome.com/docs/extensions/reference/storage/#usage})
* @param {function}[callback] Optional callback function
*/
export async function getSetting(keys = null, callback) {
if (typeof callback === 'undefined') {
return chrome.storage.local.get(keys, (items) => Object.values(items))
}else {
return chrome.storage.local.get(keys, (items) => callback(Object.values(items)))
}
}