423 lines
10 KiB
JavaScript
423 lines
10 KiB
JavaScript
const extractBtn = document.getElementById("extractBtn");
|
|
const analyzeBtn = document.getElementById("analyzeBtn");
|
|
const abortBtn = document.getElementById("abortBtn");
|
|
const taskSelect = document.getElementById("taskSelect");
|
|
const outputEl = document.getElementById("output");
|
|
const statusEl = document.getElementById("status");
|
|
const postingCountEl = document.getElementById("postingCount");
|
|
const promptCountEl = document.getElementById("promptCount");
|
|
const settingsBtn = document.getElementById("settingsBtn");
|
|
|
|
const state = {
|
|
postingText: "",
|
|
tasks: [],
|
|
port: null,
|
|
isAnalyzing: false,
|
|
outputRaw: ""
|
|
};
|
|
|
|
function getStorage(keys) {
|
|
return new Promise((resolve) => chrome.storage.local.get(keys, resolve));
|
|
}
|
|
|
|
function buildUserMessage(resume, task, posting) {
|
|
return [
|
|
"=== RESUME ===",
|
|
resume || "",
|
|
"",
|
|
"=== TASK ===",
|
|
task || "",
|
|
"",
|
|
"=== JOB POSTING ===",
|
|
posting || ""
|
|
].join("\n");
|
|
}
|
|
|
|
function escapeHtml(text) {
|
|
return text
|
|
.replace(/&/g, "&")
|
|
.replace(/</g, "<")
|
|
.replace(/>/g, ">");
|
|
}
|
|
|
|
function escapeAttribute(text) {
|
|
return text.replace(/&/g, "&").replace(/"/g, """);
|
|
}
|
|
|
|
function sanitizeUrl(url) {
|
|
const trimmed = url.trim().replace(/&/g, "&");
|
|
if (/^https?:\/\//i.test(trimmed)) return trimmed;
|
|
return "";
|
|
}
|
|
|
|
function applyInline(text) {
|
|
if (!text) return "";
|
|
const codeSpans = [];
|
|
let output = text.replace(/`([^`]+)`/g, (_match, code) => {
|
|
const id = codeSpans.length;
|
|
codeSpans.push(code);
|
|
return `@@CODESPAN${id}@@`;
|
|
});
|
|
|
|
output = output.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_match, label, url) => {
|
|
const safeUrl = sanitizeUrl(url);
|
|
if (!safeUrl) return label;
|
|
return `<a href="${escapeAttribute(
|
|
safeUrl
|
|
)}" target="_blank" rel="noreferrer">${label}</a>`;
|
|
});
|
|
|
|
output = output.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
|
|
output = output.replace(/\*([^*]+)\*/g, "<em>$1</em>");
|
|
output = output.replace(/_([^_]+)_/g, "<em>$1</em>");
|
|
|
|
output = output.replace(/@@CODESPAN(\d+)@@/g, (_match, id) => {
|
|
const code = codeSpans[Number(id)] || "";
|
|
return `<code>${code}</code>`;
|
|
});
|
|
|
|
return output;
|
|
}
|
|
|
|
function renderMarkdown(rawText) {
|
|
const { text, blocks } = (() => {
|
|
const escaped = escapeHtml(rawText || "");
|
|
const codeBlocks = [];
|
|
const replaced = escaped.replace(/```([\s\S]*?)```/g, (_match, code) => {
|
|
let content = code;
|
|
if (content.startsWith("\n")) content = content.slice(1);
|
|
const firstLine = content.split("\n")[0] || "";
|
|
if (/^[a-z0-9+.#-]+$/i.test(firstLine.trim()) && content.includes("\n")) {
|
|
content = content.split("\n").slice(1).join("\n");
|
|
}
|
|
const id = codeBlocks.length;
|
|
codeBlocks.push(content);
|
|
return `@@CODEBLOCK${id}@@`;
|
|
});
|
|
return { text: replaced, blocks: codeBlocks };
|
|
})();
|
|
|
|
const lines = text.split(/\r?\n/);
|
|
const result = [];
|
|
let paragraph = [];
|
|
let listType = null;
|
|
let inBlockquote = false;
|
|
let quoteLines = [];
|
|
|
|
const flushParagraph = () => {
|
|
if (!paragraph.length) return;
|
|
result.push(`<p>${applyInline(paragraph.join("<br>"))}</p>`);
|
|
paragraph = [];
|
|
};
|
|
|
|
const closeList = () => {
|
|
if (!listType) return;
|
|
result.push(`</${listType}>`);
|
|
listType = null;
|
|
};
|
|
|
|
const openList = (type) => {
|
|
if (listType === type) return;
|
|
if (listType) result.push(`</${listType}>`);
|
|
listType = type;
|
|
result.push(`<${type}>`);
|
|
};
|
|
|
|
const closeBlockquote = () => {
|
|
if (!inBlockquote) return;
|
|
result.push(`<blockquote>${applyInline(quoteLines.join("<br>"))}</blockquote>`);
|
|
inBlockquote = false;
|
|
quoteLines = [];
|
|
};
|
|
|
|
for (const line of lines) {
|
|
const trimmed = line.trim();
|
|
const isQuoteLine = /^\s*>\s?/.test(line);
|
|
|
|
if (trimmed === "") {
|
|
flushParagraph();
|
|
closeList();
|
|
closeBlockquote();
|
|
continue;
|
|
}
|
|
|
|
if (inBlockquote && !isQuoteLine) {
|
|
closeBlockquote();
|
|
}
|
|
|
|
if (/^@@CODEBLOCK\d+@@$/.test(trimmed)) {
|
|
flushParagraph();
|
|
closeList();
|
|
closeBlockquote();
|
|
result.push(trimmed);
|
|
continue;
|
|
}
|
|
|
|
const headingMatch = line.match(/^(#{1,6})\s+(.*)$/);
|
|
if (headingMatch) {
|
|
flushParagraph();
|
|
closeList();
|
|
closeBlockquote();
|
|
const level = headingMatch[1].length;
|
|
result.push(`<h${level}>${applyInline(headingMatch[2])}</h${level}>`);
|
|
continue;
|
|
}
|
|
|
|
if (isQuoteLine) {
|
|
if (!inBlockquote) {
|
|
flushParagraph();
|
|
closeList();
|
|
inBlockquote = true;
|
|
quoteLines = [];
|
|
}
|
|
quoteLines.push(line.replace(/^\s*>\s?/, ""));
|
|
continue;
|
|
}
|
|
|
|
const unorderedMatch = line.match(/^[-*+]\s+(.+)$/);
|
|
if (unorderedMatch) {
|
|
flushParagraph();
|
|
closeBlockquote();
|
|
openList("ul");
|
|
result.push(`<li>${applyInline(unorderedMatch[1])}</li>`);
|
|
continue;
|
|
}
|
|
|
|
const orderedMatch = line.match(/^\d+\.\s+(.+)$/);
|
|
if (orderedMatch) {
|
|
flushParagraph();
|
|
closeBlockquote();
|
|
openList("ol");
|
|
result.push(`<li>${applyInline(orderedMatch[1])}</li>`);
|
|
continue;
|
|
}
|
|
|
|
paragraph.push(line);
|
|
}
|
|
|
|
flushParagraph();
|
|
closeList();
|
|
closeBlockquote();
|
|
|
|
return result
|
|
.join("\n")
|
|
.replace(/@@CODEBLOCK(\d+)@@/g, (_match, id) => {
|
|
const code = blocks[Number(id)] || "";
|
|
return `<pre><code>${code}</code></pre>`;
|
|
});
|
|
}
|
|
|
|
function renderOutput() {
|
|
outputEl.innerHTML = renderMarkdown(state.outputRaw);
|
|
outputEl.scrollTop = outputEl.scrollHeight;
|
|
}
|
|
|
|
function setStatus(message) {
|
|
statusEl.textContent = message;
|
|
}
|
|
|
|
function applyTheme(theme) {
|
|
const value = theme || "system";
|
|
document.documentElement.dataset.theme = value;
|
|
}
|
|
|
|
function setAnalyzing(isAnalyzing) {
|
|
state.isAnalyzing = isAnalyzing;
|
|
analyzeBtn.disabled = isAnalyzing;
|
|
abortBtn.disabled = !isAnalyzing;
|
|
extractBtn.disabled = isAnalyzing;
|
|
}
|
|
|
|
function updatePostingCount() {
|
|
postingCountEl.textContent = `Posting: ${state.postingText.length} chars`;
|
|
}
|
|
|
|
function updatePromptCount(count) {
|
|
promptCountEl.textContent = `Prompt: ${count} chars`;
|
|
}
|
|
|
|
function renderTasks(tasks) {
|
|
state.tasks = tasks;
|
|
taskSelect.innerHTML = "";
|
|
|
|
if (!tasks.length) {
|
|
const option = document.createElement("option");
|
|
option.textContent = "No tasks configured";
|
|
option.value = "";
|
|
taskSelect.appendChild(option);
|
|
taskSelect.disabled = true;
|
|
return;
|
|
}
|
|
|
|
taskSelect.disabled = false;
|
|
for (const task of tasks) {
|
|
const option = document.createElement("option");
|
|
option.value = task.id;
|
|
option.textContent = task.name || "Untitled task";
|
|
taskSelect.appendChild(option);
|
|
}
|
|
}
|
|
|
|
function sendToActiveTab(message) {
|
|
return new Promise((resolve, reject) => {
|
|
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
|
|
const tab = tabs[0];
|
|
if (!tab?.id) {
|
|
reject(new Error("No active tab found."));
|
|
return;
|
|
}
|
|
|
|
chrome.tabs.sendMessage(tab.id, message, (response) => {
|
|
const error = chrome.runtime.lastError;
|
|
if (error) {
|
|
reject(new Error(error.message));
|
|
return;
|
|
}
|
|
resolve(response);
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
function ensurePort() {
|
|
if (state.port) return state.port;
|
|
|
|
const port = chrome.runtime.connect({ name: "analysis" });
|
|
port.onMessage.addListener((message) => {
|
|
if (message?.type === "DELTA") {
|
|
state.outputRaw += message.text;
|
|
renderOutput();
|
|
return;
|
|
}
|
|
|
|
if (message?.type === "DONE") {
|
|
setAnalyzing(false);
|
|
setStatus("Done");
|
|
return;
|
|
}
|
|
|
|
if (message?.type === "ABORTED") {
|
|
setAnalyzing(false);
|
|
setStatus("Aborted.");
|
|
return;
|
|
}
|
|
|
|
if (message?.type === "ERROR") {
|
|
setAnalyzing(false);
|
|
setStatus(message.message || "Error during analysis.");
|
|
}
|
|
});
|
|
|
|
port.onDisconnect.addListener(() => {
|
|
state.port = null;
|
|
setAnalyzing(false);
|
|
});
|
|
|
|
state.port = port;
|
|
return port;
|
|
}
|
|
|
|
async function loadTasks() {
|
|
const { tasks = [] } = await getStorage(["tasks"]);
|
|
renderTasks(tasks);
|
|
}
|
|
|
|
async function loadTheme() {
|
|
const { theme = "system" } = await getStorage(["theme"]);
|
|
applyTheme(theme);
|
|
}
|
|
|
|
async function handleExtract() {
|
|
setStatus("Extracting...");
|
|
try {
|
|
const response = await sendToActiveTab({ type: "EXTRACT_POSTING" });
|
|
if (!response?.ok) {
|
|
setStatus(response?.error || "No posting detected.");
|
|
return;
|
|
}
|
|
|
|
state.postingText = response.sanitized || "";
|
|
updatePostingCount();
|
|
updatePromptCount(0);
|
|
setStatus("Posting extracted.");
|
|
} catch (error) {
|
|
setStatus(error.message || "Unable to extract posting.");
|
|
}
|
|
}
|
|
|
|
async function handleAnalyze() {
|
|
if (!state.postingText) {
|
|
setStatus("Extract a job posting first.");
|
|
return;
|
|
}
|
|
|
|
const taskId = taskSelect.value;
|
|
const task = state.tasks.find((item) => item.id === taskId);
|
|
if (!task) {
|
|
setStatus("Select a task prompt.");
|
|
return;
|
|
}
|
|
|
|
const { apiKey, model, systemPrompt, resume } = await getStorage([
|
|
"apiKey",
|
|
"model",
|
|
"systemPrompt",
|
|
"resume"
|
|
]);
|
|
|
|
if (!apiKey) {
|
|
setStatus("Add your OpenAI API key in Settings.");
|
|
return;
|
|
}
|
|
|
|
if (!model) {
|
|
setStatus("Set a model name in Settings.");
|
|
return;
|
|
}
|
|
|
|
const promptText = buildUserMessage(resume || "", task.text || "", state.postingText);
|
|
updatePromptCount(promptText.length);
|
|
|
|
state.outputRaw = "";
|
|
renderOutput();
|
|
setAnalyzing(true);
|
|
setStatus("Analyzing...");
|
|
|
|
const port = ensurePort();
|
|
port.postMessage({
|
|
type: "START_ANALYSIS",
|
|
payload: {
|
|
apiKey,
|
|
model,
|
|
systemPrompt: systemPrompt || "",
|
|
resume: resume || "",
|
|
taskText: task.text || "",
|
|
postingText: state.postingText
|
|
}
|
|
});
|
|
}
|
|
|
|
function handleAbort() {
|
|
if (!state.port) return;
|
|
state.port.postMessage({ type: "ABORT_ANALYSIS" });
|
|
setAnalyzing(false);
|
|
setStatus("Aborted.");
|
|
}
|
|
|
|
extractBtn.addEventListener("click", handleExtract);
|
|
analyzeBtn.addEventListener("click", handleAnalyze);
|
|
abortBtn.addEventListener("click", handleAbort);
|
|
settingsBtn.addEventListener("click", () => chrome.runtime.openOptionsPage());
|
|
|
|
updatePostingCount();
|
|
updatePromptCount(0);
|
|
renderOutput();
|
|
loadTasks();
|
|
loadTheme();
|
|
|
|
chrome.storage.onChanged.addListener((changes) => {
|
|
if (changes.theme) {
|
|
applyTheme(changes.theme.newValue || "system");
|
|
}
|
|
});
|