-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
181 lines (159 loc) · 4.6 KB
/
background.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import { modelRole } from "./prompt.js";
chrome.runtime.onInstalled.addListener(function () {
chrome.contextMenus.create({
id: "QAIRephraser",
title: "Rephrase with AI",
contexts: ["selection"],
});
});
chrome.contextMenus.onClicked.addListener(function (info, tab) {
if (info.menuItemId == "QAIRephraser") {
let selectedText = info.selectionText;
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: QAIModal,
args: [selectedText, modelRole],
});
}
});
function QAIModal(text, modelRole) {
const modalContainer = document.createElement("div");
modalContainer.id = "QAIModalContainer";
modalContainer.style.cssText = `
font-family: system-ui;
font-weight: 400;
line-height: 1.5em;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 10000;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
`;
const modalContent = document.createElement("div");
modalContent.id = "QAIModalContent";
modalContent.style.cssText = `
padding: 0.8em;
width: 55vw;
height: auto;
font-size: 17px;
background-color: #0e131e;
color: #eee;
overflow-y: auto;
box-sizing: border-box;
position: relative;
`;
const closeButton = document.createElement("button");
closeButton.innerText = "x";
closeButton.style.cssText = `
position: absolute;
top: 7px;
right: 7px;
background-color: transparent;
border: none;
color: white;
font-size: 15px;
cursor: pointer;
`;
closeButton.onclick = function () {
modalContainer.remove();
};
const modalInnerContent = document.createElement("div");
modalInnerContent.style.cssText = `
padding: 0.8em;
`;
modalInnerContent.ondblclick = () => {
modalInnerContent.innerText = "Waiting for AI...";
port.postMessage({ content: text });
};
modalInnerContent.onclick = () => copyToClipboard();
function copyToClipboard() {
let text = modalInnerContent.innerText;
(async () => await navigator.clipboard.writeText(text))();
}
modalInnerContent.innerHTML = "Waiting for AI...";
modalContent.appendChild(modalInnerContent);
modalContainer.appendChild(modalContent);
document.body.appendChild(modalContainer);
function handleEscKey(event) {
if (event.key === "Escape") {
removeModal();
}
}
function handleClickOutside(event) {
if (!modalContent.contains(event.target)) {
removeModal();
}
}
window.addEventListener("keydown", handleEscKey);
modalContainer.addEventListener("click", handleClickOutside);
function removeModal() {
copyToClipboard();
modalContainer.remove();
window.removeEventListener("keydown", handleEscKey);
window.removeEventListener("click", handleClickOutside);
}
function getStorageData(keys) {
return new Promise((resolve, reject) => {
chrome.storage.sync.get(keys, (items) => {
if (chrome.runtime.lastError) {
return reject(chrome.runtime.lastError);
}
resolve(items);
});
});
}
async function queryOpenAI(prompt, modelRole) {
let { openaiApiKey, model } = await getStorageData([
"openaiApiKey",
"model",
]);
model = model || "gpt-3.5-turbo";
console.log("Model: ", model, "API Key: ", openaiApiKey);
const url = "https://api.openai.com/v1/chat/completions";
const params = {
prompt: prompt,
temperature: Math.random() * 2 * 0.1 + 0.5
};
if (!openaiApiKey) {
alert("Please set your API Key in the options page.");
return; // Exit if no API key
}
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${openaiApiKey}`,
},
body: JSON.stringify({
model: model,
messages: [
{
role: "system",
content: modelRole + ` You will deliver the output in JSON.`,
},
{
role: "user",
content: prompt,
},
],
response_format: { type: "json_object" },
temperature: params.temperature,
}),
});
if (!response.ok) {
throw new Error("Failed to fetch from OpenAI: " + response.statusText);
}
return response.json();
}
queryOpenAI("Rephrase this text: " + text, modelRole)
.then((response) => {
const res = JSON.parse(response.choices[0].message.content);
modalInnerContent.innerHTML = res[Object.keys(res)[0]];
})
.catch((error) => console.error("Error with OpenAI API:", error));
}