feat: Implement Prompt Builder functionality in Popup and Options
Some checks failed
CI — Test & Build / Test & Build (push) Failing after 39s

- Added a new "Prompt Builder" tab in the Popup for generating AI prompts with customizable parameters.
- Introduced new state variables for managing prompt styles, personas, formats, and models.
- Enhanced the Options page to fetch and display models based on the provided API key.
- Updated the actions and types to include the new 'prompt' action and its associated parameters.
- Implemented migration logic for legacy plaintext API keys to encrypted storage.
- Updated the getSystemPrompt function to incorporate prompt parameters for better instruction generation.
- Added tests for the new functionality, including context menu entries and prompt generation logic.
This commit is contained in:
john kevin asprec
2026-07-15 15:27:41 +08:00
parent 0fef9848cb
commit acea99d7ad
40 changed files with 1971 additions and 177 deletions

View File

@@ -1,6 +1,6 @@
import { defineContentScript } from 'wxt/utils/define-content-script';
import { isExtensionValid, safeSendMessage } from '@lib/messaging';
import { MIN_SELECTION_LENGTH, WRITING_STYLES } from '@lib/actions';
import { MIN_SELECTION_LENGTH, WRITING_STYLES, PROMPT_STYLES, PROMPT_PERSONAS, PROMPT_FORMATS } from '@lib/actions';
export default defineContentScript({
matches: ['<all_urls>'],
@@ -19,6 +19,9 @@ export default defineContentScript({
// ─── State ───────────────────────────────────────────────────────────────
let toolbar: HTMLElement | null = null;
let modal: HTMLElement | null = null;
// Removes the document-level listeners registered for the current toolbar's
// "More" menu — without this every selection leaked two document listeners.
let toolbarListenerCleanup: (() => void) | null = null;
// Stored immediately on mouseup — used during Replace (selection is lost by then)
let selectedText = '';
@@ -217,6 +220,7 @@ export default defineContentScript({
{ label: '↓ Shorten', action: 'shorten', color: '#fab387' },
{ label: '↑ Expand', action: 'expand', color: '#cba6f7' },
{ label: '💡 Explain', action: 'explain', color: '#2dd4bf' },
{ label: '🪄 Prompt', action: 'prompt', color: '#f9e2af' },
];
actions.forEach(({ label, action, color }) => {
@@ -254,7 +258,12 @@ export default defineContentScript({
});
btn.addEventListener('click', (e) => {
e.stopPropagation();
runAction(action);
// Prompt opens the Prompt Builder dialog first — parameters, then run.
if (action === 'prompt') {
showPromptBuilderDialog();
} else {
runAction(action);
}
});
toolbar!.appendChild(btn);
@@ -350,24 +359,50 @@ export default defineContentScript({
toolbar!.appendChild(moreBtn);
// Close dropdown on outside click / scroll
// Close dropdown on outside click / scroll; hideToolbar unregisters these
// (and closes any open menu) so listeners never accumulate across selections.
document.addEventListener('click', closeMoveMenu);
document.addEventListener('scroll', closeMoveMenu, { passive: true });
toolbarListenerCleanup = () => {
closeMoveMenu();
document.removeEventListener('click', closeMoveMenu);
document.removeEventListener('scroll', closeMoveMenu);
};
document.body.appendChild(toolbar);
// Re-clamp with the real width — the pre-append estimate undershoots now
// that the toolbar has six action buttons, which could push the last
// ones (🪄 Prompt, ⋯ More) past the right edge of the viewport.
const actualW = toolbar.offsetWidth;
let clampedLeft = rect.left + window.scrollX + rect.width / 2 - actualW / 2;
clampedLeft = Math.max(
window.scrollX + 8,
Math.min(clampedLeft, window.scrollX + window.innerWidth - actualW - 8),
);
toolbar.style.left = `${clampedLeft}px`;
}
function hideToolbar() {
toolbarListenerCleanup?.();
toolbarListenerCleanup = null;
if (toolbar) {
toolbar.remove();
toolbar = null;
}
}
// Close the Prompt Builder dialog (also used as the loading indicator for
// prompt requests — see showPromptBuilderDialog's Make Prompt handler).
function closePromptBuilder() {
document.getElementById('lexai-promptbuilder-overlay')?.remove();
}
// Extension context guard: isExtensionValid is imported from ~/lib/messaging.
function showErrorToast(msg: string) {
const toast = document.createElement('div');
toast.setAttribute('data-lexai', 'true');
toast.style.cssText = `
position: fixed; bottom: 20px; right: 20px; z-index: 999999;
background: #f38ba8; color: #1e1e2e; padding: 10px 16px;
@@ -556,6 +591,218 @@ export default defineContentScript({
document.body.appendChild(overlay);
}
// ─── Prompt Builder dialog ────────────────────────────────────────────────
// Same parameters as the popup's Prompt Builder tab. Selections are saved
// to chrome.storage.local and the request is sent WITHOUT explicit params —
// the background applies the saved ones, so popup and page stay in sync.
function showPromptBuilderDialog() {
document.getElementById('lexai-promptbuilder-overlay')?.remove();
ensureLexAIStyles();
hideToolbar();
selectionLocked = true; // dialog clicks must not reset the stored selection
const overlay = document.createElement('div');
overlay.id = 'lexai-promptbuilder-overlay';
overlay.setAttribute('data-lexai', 'true');
Object.assign(overlay.style, {
position: 'fixed',
inset: '0',
zIndex: '2147483646',
background: 'rgba(0,0,0,0.25)',
});
const panel = document.createElement('div');
panel.setAttribute('data-lexai', 'true');
Object.assign(panel.style, {
position: 'fixed',
top: '50%',
left: '50%',
transform: 'translate(-50%,-50%)',
zIndex: '2147483647',
background: 'linear-gradient(135deg, #1e1e2e 0%, #181825 100%)',
borderRadius:'12px',
padding: '16px',
width: '320px',
boxShadow: '0 12px 40px rgba(0,0,0,0.55)',
border: '1px solid rgba(205,214,244,0.15)',
fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
});
const close = () => {
selectionLocked = false;
overlay.remove();
};
// Header
const header = document.createElement('div');
Object.assign(header.style, {
display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px',
});
const title = document.createElement('div');
title.innerHTML = '🪄 <strong style="color:#cdd6f4">Prompt Builder</strong>';
Object.assign(title.style, { fontSize: '13px', color: '#89b4fa' });
const closeX = document.createElement('button');
closeX.textContent = '✕';
closeX.setAttribute('data-lexai', 'true');
Object.assign(closeX.style, {
background: 'none', border: 'none', color: '#6c7086',
cursor: 'pointer', fontSize: '14px', padding: '0 2px', lineHeight: '1',
});
closeX.addEventListener('click', close);
header.appendChild(title);
header.appendChild(closeX);
panel.appendChild(header);
const hint = document.createElement('div');
hint.textContent = '"Auto" lets it decide from your selected text.';
Object.assign(hint.style, { fontSize: '11px', color: '#6c7086', marginBottom: '10px' });
panel.appendChild(hint);
const selectStyle = {
flex: '1', background: 'rgba(49,50,68,0.95)', border: '1px solid rgba(205,214,244,0.2)',
borderRadius: '6px', color: '#cdd6f4', fontSize: '12px', padding: '5px 8px',
cursor: 'pointer', outline: 'none', minWidth: '0',
};
function makeRow(labelText: string, control: HTMLElement) {
const row = document.createElement('div');
Object.assign(row.style, { display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' });
const label = document.createElement('span');
label.textContent = labelText;
Object.assign(label.style, { fontSize: '12px', color: '#a6adc8', width: '58px', flexShrink: '0' });
row.appendChild(label);
row.appendChild(control);
panel.appendChild(row);
return row;
}
function makeSelect(options: readonly string[]): HTMLSelectElement {
const sel = document.createElement('select');
sel.setAttribute('data-lexai', 'true');
Object.assign(sel.style, selectStyle);
options.forEach((o) => {
const opt = document.createElement('option');
opt.value = o;
opt.textContent = o;
sel.appendChild(opt);
});
return sel;
}
const selPromptStyle = makeSelect(PROMPT_STYLES);
makeRow('Style:', selPromptStyle);
const selPersona = makeSelect(PROMPT_PERSONAS);
makeRow('Persona:', selPersona);
const customInput = document.createElement('input');
customInput.type = 'text';
customInput.placeholder = 'e.g. senior UX researcher';
customInput.setAttribute('data-lexai', 'true');
Object.assign(customInput.style, { ...selectStyle, cursor: 'text' });
const customRow = makeRow('', customInput);
customRow.style.display = 'none';
selPersona.addEventListener('change', () => {
customRow.style.display = selPersona.value === 'Custom…' ? 'flex' : 'none';
});
const selFormat = makeSelect(PROMPT_FORMATS);
makeRow('Format:', selFormat);
// Model — 'Default' = the configured model; live list loads in the background.
const selModel = makeSelect([]);
const defaultOpt = document.createElement('option');
defaultOpt.value = '';
defaultOpt.textContent = 'Default';
selModel.appendChild(defaultOpt);
makeRow('Model:', selModel);
// Prefill from saved settings, then fetch the model list.
chrome.storage.local.get(
['promptStyle', 'promptPersona', 'customPersona', 'promptFormat', 'promptModel'],
(saved) => {
if (saved.promptStyle) selPromptStyle.value = saved.promptStyle as string;
if (saved.promptPersona) {
selPersona.value = saved.promptPersona as string;
customRow.style.display = selPersona.value === 'Custom…' ? 'flex' : 'none';
}
if (saved.customPersona) customInput.value = saved.customPersona as string;
if (saved.promptFormat) selFormat.value = saved.promptFormat as string;
const savedModel = (saved.promptModel as string) || '';
sendToBackground({ type: 'LIST_MODELS' }).then((res) => {
const models = (res as { models?: string[] } | null)?.models;
if (!Array.isArray(models)) return; // keep just 'Default' on failure
models.forEach((m) => {
const opt = document.createElement('option');
opt.value = m;
opt.textContent = m;
selModel.appendChild(opt);
});
if (savedModel && models.includes(savedModel)) selModel.value = savedModel;
});
},
);
// Buttons
const btnRow = document.createElement('div');
Object.assign(btnRow.style, { display: 'flex', gap: '8px', marginTop: '12px' });
const cancelBtn = document.createElement('button');
cancelBtn.textContent = 'Cancel';
cancelBtn.setAttribute('data-lexai', 'true');
Object.assign(cancelBtn.style, {
flex: '1', background: 'rgba(49,50,68,0.8)', color: '#a6adc8',
border: '1px solid rgba(205,214,244,0.15)', borderRadius: '8px',
padding: '8px', fontSize: '12px', fontWeight: '600', cursor: 'pointer',
});
cancelBtn.addEventListener('click', close);
const makeBtn = document.createElement('button');
makeBtn.textContent = '🪄 Make Prompt';
makeBtn.setAttribute('data-lexai', 'true');
Object.assign(makeBtn.style, {
flex: '2', background: 'linear-gradient(135deg, #f9e2af, #fab387)', color: '#1e1e2e',
border: 'none', borderRadius: '8px',
padding: '8px', fontSize: '12px', fontWeight: '700', cursor: 'pointer',
});
makeBtn.addEventListener('click', () => {
// Persist selections (shared with the popup), then run — the background
// reads these same keys for prompt requests without explicit params.
chrome.storage.local.set({
promptStyle: selPromptStyle.value,
promptPersona: selPersona.value,
customPersona: customInput.value,
promptFormat: selFormat.value,
promptModel: selModel.value,
});
// Turn the dialog into the progress indicator — runAction closes it
// (closePromptBuilder) when the result modal takes over.
panel.innerHTML = '';
const loading = document.createElement('div');
loading.setAttribute('data-lexai', 'true');
loading.innerHTML =
'<span style="font-size:18px;animation:lexai-spin 0.8s linear infinite;display:inline-block">⟳</span> Building your prompt…';
Object.assign(loading.style, {
display: 'flex', alignItems: 'center', justifyContent: 'center',
gap: '8px', padding: '14px 0', color: '#a6adc8', fontSize: '13px',
});
panel.appendChild(loading);
runAction('prompt'); // keep selectionLocked — runAction owns it from here
});
btnRow.appendChild(cancelBtn);
btnRow.appendChild(makeBtn);
panel.appendChild(btnRow);
overlay.appendChild(panel);
overlay.addEventListener('click', (e) => {
if (e.target === overlay) close();
});
document.body.appendChild(overlay);
}
// ─── Safe chrome.runtime.sendMessage wrapper ──────────────────────────────
// Shared implementation; on a stale extension context we toast and clean up.
@@ -563,6 +810,7 @@ export default defineContentScript({
return safeSendMessage(payload, () => {
showErrorToast('LexAI was updated — please refresh this page.');
hideToolbar();
closePromptBuilder();
});
}
@@ -619,6 +867,7 @@ export default defineContentScript({
}) as { error?: string; result?: string } | null;
hideToolbar();
closePromptBuilder();
if (response === null) return; // sendToBackground already handled the error
@@ -636,6 +885,7 @@ export default defineContentScript({
}
} catch (err) {
hideToolbar();
closePromptBuilder();
if (String(err).includes('Extension context invalidated') ||
String(err).includes('message channel closed')) {
showErrorToast('LexAI was updated — please refresh this page.');
@@ -686,7 +936,11 @@ export default defineContentScript({
width: '420px',
maxWidth: 'min(90vw, 420px)',
maxHeight: '70vh',
overflowY: 'auto',
// The result body scrolls, not the modal — header and action buttons
// must stay visible for long results (e.g. engineered prompts).
display: 'flex',
flexDirection: 'column',
overflow: 'hidden',
boxShadow: '0 12px 48px rgba(0,0,0,0.6)',
border: '1px solid rgba(205,214,244,0.15)',
fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
@@ -700,10 +954,15 @@ export default defineContentScript({
justifyContent:'space-between',
alignItems: 'center',
marginBottom: '12px',
flexShrink: '0',
});
const isPromptAction = action === 'prompt';
const title = document.createElement('div');
title.innerHTML = '⚡ <strong>LexAI</strong> Suggestion';
title.innerHTML = isPromptAction
? '🪄 <strong>LexAI</strong> Engineered Prompt'
: '⚡ <strong>LexAI</strong> Suggestion';
Object.assign(title.style, { fontSize: '13px', color: '#89b4fa' });
const closeBtn = document.createElement('button');
@@ -741,6 +1000,10 @@ export default defineContentScript({
marginBottom:'14px',
whiteSpace: 'pre-wrap',
wordBreak: 'break-word',
// Scroll long results inside the box; flex keeps buttons below visible.
overflowY: 'auto',
flex: '1 1 auto',
minHeight: '60px',
});
modal.appendChild(body);
@@ -753,6 +1016,7 @@ export default defineContentScript({
alignItems: 'center',
gap: '8px',
marginBottom:'12px',
flexShrink: '0',
});
const styleLabel = document.createElement('span');
@@ -808,10 +1072,14 @@ export default defineContentScript({
async function doRegenerate() {
if (!action || !textForRegenerate) return;
const chosenStyle = styleSelect.value;
// Save style
currentStyle = chosenStyle;
await chrome.storage.local.set({ writingStyle: chosenStyle });
let chosenStyle = currentStyle;
// The writing-style selector only exists for non-prompt results; prompt
// regeneration re-reads the saved Prompt Builder params in the background.
if (!isPromptAction) {
chosenStyle = styleSelect.value;
currentStyle = chosenStyle;
await chrome.storage.local.set({ writingStyle: chosenStyle });
}
// Show spinner
body.innerHTML = '<span style="font-size:18px;animation:lexai-spin 0.8s linear infinite;display:inline-block">⟳</span> Regenerating…';
regenBtn.disabled = true;
@@ -835,14 +1103,43 @@ export default defineContentScript({
styleSelect.addEventListener('change', () => doRegenerate());
regenBtn.addEventListener('click', () => doRegenerate());
styleRow.appendChild(styleLabel);
styleRow.appendChild(styleSelect);
styleRow.appendChild(regenBtn);
modal.appendChild(styleRow);
if (isPromptAction) {
// Prompt results: writing styles don't apply — offer the Prompt Builder
// parameters instead, plus regenerate with the current ones.
const editBtn = document.createElement('button');
editBtn.textContent = '✎ Edit Parameters';
editBtn.setAttribute('data-lexai', 'true');
Object.assign(editBtn.style, {
background: 'rgba(249,226,175,0.15)',
color: '#f9e2af',
border: '1px solid rgba(249,226,175,0.3)',
borderRadius: '6px',
padding: '5px 10px',
fontSize: '12px',
fontWeight: '600',
cursor: 'pointer',
flex: '1',
});
editBtn.addEventListener('click', () => {
overlay.remove();
modal?.remove();
modal = null;
showPromptBuilderDialog(); // selection stays locked; dialog re-runs from here
});
styleRow.appendChild(editBtn);
styleRow.appendChild(regenBtn);
modal.appendChild(styleRow);
} else {
styleRow.appendChild(styleLabel);
styleRow.appendChild(styleSelect);
styleRow.appendChild(regenBtn);
modal.appendChild(styleRow);
}
// Buttons
const btnRow = document.createElement('div');
Object.assign(btnRow.style, { display: 'flex', gap: '8px' });
Object.assign(btnRow.style, { display: 'flex', gap: '8px', flexShrink: '0' });
if (originalText !== null) {
const replaceBtn = document.createElement('button');
@@ -995,7 +1292,7 @@ export default defineContentScript({
const captured = captureSelectionNow();
setTimeout(() => {
if (!captured || !selectedText || selectedText.length <= 10) {
if (!captured || !selectedText || selectedText.length < MIN_SELECTION_LENGTH) {
hideToolbar();
return;
}
@@ -1045,7 +1342,9 @@ export default defineContentScript({
});
// ─── Context menu trigger from background ─────────────────────────────────
chrome.runtime.onMessage.addListener((message) => {
chrome.runtime.onMessage.addListener((message, sender) => {
// Only our own background worker may inject selections — ignore others.
if (sender.id !== chrome.runtime.id) return;
if (message.type === 'lexai-context-menu') {
selectedText = message.text as string;
currentStyle = (message.style as string) || 'Default';
@@ -1054,7 +1353,12 @@ export default defineContentScript({
storedEnd = -1;
storedElement = null;
storedRange = null;
runAction(message.action as string);
// Prompt goes through the Prompt Builder dialog like the toolbar button.
if (message.action === 'prompt') {
showPromptBuilderDialog();
} else {
runAction(message.action as string);
}
}
});
},