52 lines
2.5 KiB
JavaScript
52 lines
2.5 KiB
JavaScript
import { createDialogController } from './controller.js';
|
|
import { openChat } from '../background/open-chat.js';
|
|
|
|
const field = id => document.getElementById(id);
|
|
let controller;
|
|
let initialized = false;
|
|
let previousKind;
|
|
const close = () => window.close();
|
|
function render(state) {
|
|
const language = state.kind === 'language';
|
|
field('title').textContent = language ? 'Translate selected text' : 'Ask ChatGPT';
|
|
field('description').textContent = language ? 'Which language would you like to translate into?'
|
|
: state.kind === 'shortened' ? 'The selection is too long to send in full. Continue with a shortened selection, or cancel and select less text.'
|
|
: state.kind === 'error' ? state.message : 'Ready to open ChatGPT with your prompt.';
|
|
field('language-field').hidden = !language;
|
|
field('language').disabled = state.busy;
|
|
field('continue').hidden = state.kind === 'error';
|
|
field('continue').disabled = state.busy;
|
|
field('continue').textContent = state.kind === 'shortened' ? 'Continue with shortened text' : 'Continue';
|
|
field('cancel').disabled = state.busy;
|
|
field('message').textContent = state.kind === 'error' ? '' : state.message ?? '';
|
|
if (previousKind !== state.kind) {
|
|
(language ? field('language') : state.kind === 'error' ? field('cancel') : field('continue')).focus();
|
|
previousKind = state.kind;
|
|
}
|
|
}
|
|
function failed() {
|
|
if (initialized) return;
|
|
render({ kind: 'error', message: 'Could not prepare this action. Close this window and try the menu action again.' });
|
|
}
|
|
const id = new URL(location.href).searchParams.get('request');
|
|
const timer = setTimeout(failed, 15000);
|
|
const port = browser.runtime.connect({ name: 'action-dialog:' + id });
|
|
port.onMessage.addListener(message => {
|
|
if (initialized || message?.type !== 'initialize' || !message.payload?.request) return;
|
|
initialized = true;
|
|
clearTimeout(timer);
|
|
controller = createDialogController({ payload: message.payload, render, close,
|
|
open: (url, mode) => openChat(browser, url, mode) });
|
|
port.postMessage({ type: 'received' });
|
|
});
|
|
port.onDisconnect.addListener(() => { clearTimeout(timer); failed(); });
|
|
field('action-form').addEventListener('submit', event => {
|
|
event.preventDefault();
|
|
void controller?.submit(field('language').value);
|
|
});
|
|
function cancel() { if (controller) controller.cancel(); else close(); }
|
|
field('cancel').addEventListener('click', cancel);
|
|
document.addEventListener('keydown', event => {
|
|
if (event.key === 'Escape') { event.preventDefault(); cancel(); }
|
|
});
|