feat: initial LexAI Chrome extension scaffold
- WXT + React 18 + TypeScript setup - Background service worker (LLM API proxy) - Content script (floating toolbar + text selection) - Options page (provider/model/API key config) - Popup UI - Gitea Actions workflows (CI, preview, release) - Vitest unit tests + Playwright E2E setup - Supports: OpenAI, Anthropic, Groq, OpenRouter
This commit is contained in:
105
entrypoints/background.ts
Normal file
105
entrypoints/background.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import { defineBackground } from 'wxt/sandbox';
|
||||
|
||||
export default defineBackground(() => {
|
||||
console.log('LexAI background service worker started');
|
||||
|
||||
// Handle messages from content scripts
|
||||
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
|
||||
if (message.type === 'ANALYZE_TEXT') {
|
||||
handleAnalyzeText(message.payload).then(sendResponse);
|
||||
return true; // Keep channel open for async response
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
async function handleAnalyzeText(payload: { text: string; action: string }) {
|
||||
try {
|
||||
const config = await chrome.storage.local.get(['provider', 'apiKey', 'model']);
|
||||
|
||||
if (!config.apiKey) {
|
||||
return { error: 'No API key configured. Please open LexAI settings.' };
|
||||
}
|
||||
|
||||
// Route to correct provider
|
||||
switch (config.provider) {
|
||||
case 'openai':
|
||||
return await callOpenAI(payload, config);
|
||||
case 'anthropic':
|
||||
return await callAnthropic(payload, config);
|
||||
case 'groq':
|
||||
return await callGroq(payload, config);
|
||||
default:
|
||||
return { error: 'Unknown provider. Please check settings.' };
|
||||
}
|
||||
} catch (err) {
|
||||
return { error: String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
async function callOpenAI(payload: { text: string; action: string }, config: any) {
|
||||
const res = await fetch('https://api.openai.com/v1/chat/completions', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${config.apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: config.model || 'gpt-4o-mini',
|
||||
messages: [
|
||||
{ role: 'system', content: getSystemPrompt(payload.action) },
|
||||
{ role: 'user', content: payload.text },
|
||||
],
|
||||
}),
|
||||
});
|
||||
const data = await res.json();
|
||||
return { result: data.choices?.[0]?.message?.content };
|
||||
}
|
||||
|
||||
async function callAnthropic(payload: { text: string; action: string }, config: any) {
|
||||
const res = await fetch('https://api.anthropic.com/v1/messages', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-api-key': config.apiKey,
|
||||
'anthropic-version': '2023-06-01',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: config.model || 'claude-3-5-haiku-20241022',
|
||||
max_tokens: 1024,
|
||||
system: getSystemPrompt(payload.action),
|
||||
messages: [{ role: 'user', content: payload.text }],
|
||||
}),
|
||||
});
|
||||
const data = await res.json();
|
||||
return { result: data.content?.[0]?.text };
|
||||
}
|
||||
|
||||
async function callGroq(payload: { text: string; action: string }, config: any) {
|
||||
const res = await fetch('https://api.groq.com/openai/v1/chat/completions', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${config.apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: config.model || 'llama-3.3-70b-versatile',
|
||||
messages: [
|
||||
{ role: 'system', content: getSystemPrompt(payload.action) },
|
||||
{ role: 'user', content: payload.text },
|
||||
],
|
||||
}),
|
||||
});
|
||||
const data = await res.json();
|
||||
return { result: data.choices?.[0]?.message?.content };
|
||||
}
|
||||
|
||||
function getSystemPrompt(action: string): string {
|
||||
const prompts: Record<string, string> = {
|
||||
grammar: 'You are a grammar checker. Fix grammar, spelling, and punctuation errors in the text. Return only the corrected text without explanations.',
|
||||
rephrase: 'You are a writing assistant. Rephrase the given text to be clearer and more professional. Return only the rephrased text.',
|
||||
tone: 'You are a writing coach. Analyze the tone of the text and suggest improvements. Be concise.',
|
||||
shorten: 'You are an editor. Shorten the text while keeping the key message. Return only the shortened version.',
|
||||
expand: 'You are a writer. Expand the given text with more detail and context. Return only the expanded version.',
|
||||
};
|
||||
return prompts[action] || prompts.grammar;
|
||||
}
|
||||
143
entrypoints/content.ts
Normal file
143
entrypoints/content.ts
Normal file
@@ -0,0 +1,143 @@
|
||||
import { defineContentScript } from 'wxt/sandbox';
|
||||
|
||||
export default defineContentScript({
|
||||
matches: ['<all_urls>'],
|
||||
main() {
|
||||
console.log('LexAI content script loaded');
|
||||
|
||||
let toolbar: HTMLElement | null = null;
|
||||
let selectedText = '';
|
||||
|
||||
// Listen for text selection
|
||||
document.addEventListener('mouseup', (e) => {
|
||||
const selection = window.getSelection();
|
||||
if (selection && selection.toString().trim().length > 10) {
|
||||
selectedText = selection.toString().trim();
|
||||
showToolbar(e.clientX, e.clientY);
|
||||
} else {
|
||||
hideToolbar();
|
||||
}
|
||||
});
|
||||
|
||||
function showToolbar(x: number, y: number) {
|
||||
hideToolbar();
|
||||
|
||||
toolbar = document.createElement('div');
|
||||
toolbar.id = 'lexai-toolbar';
|
||||
toolbar.style.cssText = `
|
||||
position: fixed;
|
||||
top: ${y - 50}px;
|
||||
left: ${x}px;
|
||||
z-index: 999999;
|
||||
background: #1e1e2e;
|
||||
border-radius: 8px;
|
||||
padding: 6px 8px;
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
box-shadow: 0 4px 20px rgba(0,0,0,0.3);
|
||||
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
|
||||
`;
|
||||
|
||||
const actions = [
|
||||
{ label: '✓ Fix', action: 'grammar' },
|
||||
{ label: '↺ Rephrase', action: 'rephrase' },
|
||||
{ label: '↓ Shorten', action: 'shorten' },
|
||||
{ label: '↑ Expand', action: 'expand' },
|
||||
];
|
||||
|
||||
actions.forEach(({ label, action }) => {
|
||||
const btn = document.createElement('button');
|
||||
btn.textContent = label;
|
||||
btn.style.cssText = `
|
||||
background: #313244;
|
||||
color: #cdd6f4;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
padding: 4px 10px;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
`;
|
||||
btn.addEventListener('mouseenter', () => btn.style.background = '#45475a');
|
||||
btn.addEventListener('mouseleave', () => btn.style.background = '#313244');
|
||||
btn.addEventListener('click', () => runAction(action));
|
||||
toolbar!.appendChild(btn);
|
||||
});
|
||||
|
||||
document.body.appendChild(toolbar);
|
||||
}
|
||||
|
||||
function hideToolbar() {
|
||||
if (toolbar) {
|
||||
toolbar.remove();
|
||||
toolbar = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function runAction(action: string) {
|
||||
if (!selectedText) return;
|
||||
|
||||
// Show loading state
|
||||
if (toolbar) {
|
||||
toolbar.innerHTML = '<span style="color:#cdd6f4;font-size:12px;padding:4px 8px;">⏳ LexAI thinking...</span>';
|
||||
}
|
||||
|
||||
const response = await chrome.runtime.sendMessage({
|
||||
type: 'ANALYZE_TEXT',
|
||||
payload: { text: selectedText, action },
|
||||
});
|
||||
|
||||
if (response.error) {
|
||||
showResult(`❌ ${response.error}`);
|
||||
} else {
|
||||
showResult(response.result, true);
|
||||
}
|
||||
}
|
||||
|
||||
function showResult(text: string, canReplace = false) {
|
||||
hideToolbar();
|
||||
|
||||
const modal = document.createElement('div');
|
||||
modal.style.cssText = `
|
||||
position: fixed;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
z-index: 999999;
|
||||
background: #1e1e2e;
|
||||
border-radius: 12px;
|
||||
padding: 20px;
|
||||
width: 400px;
|
||||
max-width: 90vw;
|
||||
box-shadow: 0 8px 32px rgba(0,0,0,0.5);
|
||||
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
|
||||
color: #cdd6f4;
|
||||
`;
|
||||
|
||||
modal.innerHTML = `
|
||||
<div style="font-size:11px;color:#a6adc8;margin-bottom:8px;">LexAI Suggestion</div>
|
||||
<div style="font-size:14px;line-height:1.6;margin-bottom:12px;">${text}</div>
|
||||
${canReplace ? '<button id="lexai-replace" style="background:#89b4fa;color:#1e1e2e;border:none;border-radius:6px;padding:6px 16px;font-size:13px;cursor:pointer;margin-right:8px;">Replace</button>' : ''}
|
||||
<button id="lexai-close" style="background:#313244;color:#cdd6f4;border:none;border-radius:6px;padding:6px 16px;font-size:13px;cursor:pointer;">Close</button>
|
||||
`;
|
||||
|
||||
document.body.appendChild(modal);
|
||||
|
||||
document.getElementById('lexai-close')?.addEventListener('click', () => modal.remove());
|
||||
document.getElementById('lexai-replace')?.addEventListener('click', () => {
|
||||
replaceSelectedText(text);
|
||||
modal.remove();
|
||||
});
|
||||
}
|
||||
|
||||
function replaceSelectedText(newText: string) {
|
||||
const selection = window.getSelection();
|
||||
if (selection && selection.rangeCount > 0) {
|
||||
const range = selection.getRangeAt(0);
|
||||
range.deleteContents();
|
||||
range.insertNode(document.createTextNode(newText));
|
||||
selection.removeAllRanges();
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
98
entrypoints/options/Options.tsx
Normal file
98
entrypoints/options/Options.tsx
Normal file
@@ -0,0 +1,98 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
|
||||
const PROVIDERS = [
|
||||
{ id: 'openai', name: 'OpenAI', models: ['gpt-4o', 'gpt-4o-mini', 'gpt-3.5-turbo'] },
|
||||
{ id: 'anthropic', name: 'Anthropic', models: ['claude-3-5-sonnet-20241022', 'claude-3-5-haiku-20241022'] },
|
||||
{ id: 'groq', name: 'Groq (Free tier)', models: ['llama-3.3-70b-versatile', 'mixtral-8x7b-32768'] },
|
||||
{ id: 'openrouter', name: 'OpenRouter', models: ['auto'] },
|
||||
];
|
||||
|
||||
function OptionsPage() {
|
||||
const [provider, setProvider] = useState('openai');
|
||||
const [apiKey, setApiKey] = useState('');
|
||||
const [model, setModel] = useState('gpt-4o-mini');
|
||||
const [saved, setSaved] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
chrome.storage.local.get(['provider', 'apiKey', 'model'], (result) => {
|
||||
if (result.provider) setProvider(result.provider);
|
||||
if (result.apiKey) setApiKey(result.apiKey);
|
||||
if (result.model) setModel(result.model);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleSave = () => {
|
||||
chrome.storage.local.set({ provider, apiKey, model }, () => {
|
||||
setSaved(true);
|
||||
setTimeout(() => setSaved(false), 2000);
|
||||
});
|
||||
};
|
||||
|
||||
const currentProvider = PROVIDERS.find((p) => p.id === provider);
|
||||
|
||||
return (
|
||||
<div style={{ maxWidth: 480, margin: '40px auto', fontFamily: 'system-ui, sans-serif', color: '#1e1e2e' }}>
|
||||
<h1 style={{ fontSize: 24, marginBottom: 4 }}>⚡ LexAI Settings</h1>
|
||||
<p style={{ color: '#6c6f85', marginBottom: 32 }}>Configure your own LLM provider and API key</p>
|
||||
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<label style={{ display: 'block', fontWeight: 600, marginBottom: 6 }}>LLM Provider</label>
|
||||
<select
|
||||
value={provider}
|
||||
onChange={(e) => { setProvider(e.target.value); setModel(''); }}
|
||||
style={{ width: '100%', padding: '8px 12px', borderRadius: 8, border: '1px solid #cdd6f4', fontSize: 14 }}
|
||||
>
|
||||
{PROVIDERS.map((p) => (
|
||||
<option key={p.id} value={p.id}>{p.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<label style={{ display: 'block', fontWeight: 600, marginBottom: 6 }}>Model</label>
|
||||
<select
|
||||
value={model}
|
||||
onChange={(e) => setModel(e.target.value)}
|
||||
style={{ width: '100%', padding: '8px 12px', borderRadius: 8, border: '1px solid #cdd6f4', fontSize: 14 }}
|
||||
>
|
||||
{(currentProvider?.models || []).map((m) => (
|
||||
<option key={m} value={m}>{m}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: 28 }}>
|
||||
<label style={{ display: 'block', fontWeight: 600, marginBottom: 6 }}>API Key</label>
|
||||
<input
|
||||
type="password"
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
placeholder="sk-..."
|
||||
style={{ width: '100%', padding: '8px 12px', borderRadius: 8, border: '1px solid #cdd6f4', fontSize: 14, boxSizing: 'border-box' }}
|
||||
/>
|
||||
<p style={{ fontSize: 12, color: '#6c6f85', marginTop: 6 }}>
|
||||
🔒 Stored locally on your device only. Never sent anywhere except the LLM provider.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleSave}
|
||||
style={{
|
||||
background: saved ? '#a6e3a1' : '#89b4fa',
|
||||
color: '#1e1e2e',
|
||||
border: 'none',
|
||||
borderRadius: 8,
|
||||
padding: '10px 28px',
|
||||
fontSize: 15,
|
||||
fontWeight: 600,
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
{saved ? '✓ Saved!' : 'Save Settings'}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
createRoot(document.getElementById('app')!).render(<OptionsPage />);
|
||||
12
entrypoints/options/index.html
Normal file
12
entrypoints/options/index.html
Normal file
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>LexAI Settings</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="./Options.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
65
entrypoints/popup/Popup.tsx
Normal file
65
entrypoints/popup/Popup.tsx
Normal file
@@ -0,0 +1,65 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
|
||||
function Popup() {
|
||||
const [configured, setConfigured] = useState(false);
|
||||
const [provider, setProvider] = useState('');
|
||||
const [model, setModel] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
chrome.storage.local.get(['provider', 'apiKey', 'model'], (result) => {
|
||||
if (result.apiKey) {
|
||||
setConfigured(true);
|
||||
setProvider(result.provider || 'openai');
|
||||
setModel(result.model || '');
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
const openSettings = () => chrome.runtime.openOptionsPage();
|
||||
|
||||
return (
|
||||
<div style={{ padding: 16, fontFamily: 'system-ui, sans-serif', color: '#1e1e2e' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
|
||||
<span style={{ fontSize: 20 }}>⚡</span>
|
||||
<span style={{ fontSize: 16, fontWeight: 700 }}>LexAI</span>
|
||||
</div>
|
||||
|
||||
{configured ? (
|
||||
<div>
|
||||
<div style={{ background: '#e8f5e9', borderRadius: 8, padding: '8px 12px', marginBottom: 12 }}>
|
||||
<div style={{ fontSize: 12, color: '#388e3c', fontWeight: 600 }}>✓ Active</div>
|
||||
<div style={{ fontSize: 12, color: '#555', marginTop: 2 }}>{provider} / {model}</div>
|
||||
</div>
|
||||
<p style={{ fontSize: 12, color: '#6c6f85', marginBottom: 12 }}>
|
||||
Select any text on a webpage to see LexAI options appear.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ background: '#fff3e0', borderRadius: 8, padding: '8px 12px', marginBottom: 12 }}>
|
||||
<div style={{ fontSize: 12, color: '#e65100', fontWeight: 600 }}>⚠ Setup Required</div>
|
||||
<div style={{ fontSize: 12, color: '#555', marginTop: 2 }}>Add your API key to get started</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={openSettings}
|
||||
style={{
|
||||
width: '100%',
|
||||
background: '#89b4fa',
|
||||
color: '#1e1e2e',
|
||||
border: 'none',
|
||||
borderRadius: 8,
|
||||
padding: '8px',
|
||||
fontSize: 13,
|
||||
fontWeight: 600,
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
⚙ Open Settings
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
createRoot(document.getElementById('app')!).render(<Popup />);
|
||||
13
entrypoints/popup/index.html
Normal file
13
entrypoints/popup/index.html
Normal file
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>LexAI</title>
|
||||
<style>body { margin: 0; width: 320px; }</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="./Popup.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user