Compare commits

...

12 commits

6 changed files with 404 additions and 8 deletions

View file

@ -542,5 +542,9 @@
"StorageSpace": { "StorageSpace": {
"message": "Total storage space occupied", "message": "Total storage space occupied",
"description": "" "description": ""
},
"SearchPrompt": {
"message": "Search a prompt",
"description": ""
} }
} }

View file

@ -0,0 +1,80 @@
#mzta_search_banner{
background-color: rgb(122, 180, 255);
color:black;
border-radius: 5px;
width: 15em;
height: 2em;
position: absolute;
top: 5px;
right: 5px;
z-index: 1000;
display: flex;
justify-content: center;
align-items: center;
}
#mzta_search_icon{
position: absolute;
left: 0.7em;
}
#mzta_search_input{
width: 12em;
}
#mzta_autocomplete-items {
position: absolute;
top: 2em;
left: 2em;
border: 1px solid #ccc;
border-top: none;
z-index: 1001;
background-color: #fff;
overflow-y: auto;
width: 12em;
max-height: 11em;
}
.mzta_autocomplete-item {
padding: 8px;
cursor: pointer;
}
.mzta_autocomplete-item:hover {
background-color: #e9e9e9;
}
.mzta_autocomplete-item-active {
background-color: #e9e9e9;
}
@media (prefers-color-scheme: dark) {
input {
background-color: #27272a;
color: #ffffff;
}
#mzta_search_banner{
background-color: #27272a;
color:#ffffff;
}
#mzta_autocomplete-items {
border: 1px solid #555;
background-color: #2c2c2c;
}
.mzta_autocomplete-item {
color: #ffffff;
}
.mzta_autocomplete-item:hover {
background-color: #444444;
}
.mzta_autocomplete-item-active {
background-color: #444444;
}
}

View file

@ -16,6 +16,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
browser.runtime.onMessage.addListener(async (message) => { browser.runtime.onMessage.addListener(async (message) => {
switch (message.command) { switch (message.command) {
case "getSelectedText": case "getSelectedText":
@ -62,8 +63,240 @@ switch (message.command) {
alert(message.message); alert(message.message);
break; break;
case 'searchPrompt':
let filtering = 0;
switch(message._tab_type){
case "mail":
case "messageDisplay":
filtering = 1;
break;
case "messageCompose":
filtering = 2;
break;
default:
filtering = 0;
break;
}
let active_prompts = filterPromptsForTab(message._prompts_data, filtering);
searchPrompt(active_prompts, message.tabId, message._tab_type);
break;
default: default:
// do nothing // do nothing
break; break;
} }
}); });
async function searchPrompt(allPrompts, tabId, tabType){
console.log(">>>>>>>>>>>>>> allPrompts: " + JSON.stringify(allPrompts));
console.log(">>>>>>>>>>>>>>> tabType: " + tabType);
const banner = document.createElement('div');
banner.id = 'mzta_search_banner';
const img = document.createElement('img');
img.src = browser.runtime.getURL('images/icon-16px.png');
img.id="mzta_search_icon";
img.title = "ThunderAI";
img.width = 16;
img.height = 16;
banner.appendChild(img);
const input = document.createElement('input');
input.type = 'text';
input.id = 'mzta_search_input';
input.placeholder = browser.i18n.getMessage('SearchPrompt');
banner.appendChild(input);
const autocompleteList = document.createElement('div');
autocompleteList.id = 'mzta_autocomplete-items';
autocompleteList.style.display = 'none';
banner.appendChild(autocompleteList);
// Initialize variables to track focus and selection
let currentFocus = -1; // Tracks the currently highlighted item
let selectedId = null; // Tracks the ID of the selected item
// Function to filter and display autocomplete suggestions
input.addEventListener('input', function() {
const query = this.value.trim().toLowerCase();
autocompleteList.innerHTML = ''; // Clear previous suggestions
currentFocus = -1; // Reset the highlighted index
selectedId = null; // Reset the selected ID since input has changed
// Uncomment the following lines if you want to hide suggestions when input is empty
/*
if (query === '') {
autocompleteList.style.display = 'none';
return;
}
*/
// Filter data based on the query
const filteredData = allPrompts.filter(item =>
item.label.toLowerCase().startsWith(query)
);
if (filteredData.length === 0) {
autocompleteList.style.display = 'none';
return;
}
// Prepend numbers to the first 10 items
Array.from(filteredData).slice(0, 10).forEach((item, index) => {
const number = (index < 9) ? (index + 1).toString() : '0';
// Check if the number is already prepended to avoid duplication
if (!item.numberPrepended) {
item.label = `${number}. ${item.label}`;
item.numberPrepended = 'true'; // Mark as prepended
}
});
// Create a div for each filtered result
filteredData.forEach(item => {
const itemDiv = document.createElement('div');
itemDiv.classList.add('mzta_autocomplete-item');
itemDiv.textContent = item.label;
itemDiv.setAttribute('data-id', item.id);
// Add a mousedown event to select the item
itemDiv.addEventListener('mousedown', function(e) { // Use mousedown instead of click
e.preventDefault(); // Prevents the input from losing focus
input.value = item.label;
selectedId = item.id; // Store the selected item's ID
console.log('>>>>>>>>>>>>> mousedown selectedId:', selectedId);
autocompleteList.style.display = 'none';
});
autocompleteList.appendChild(itemDiv);
});
autocompleteList.style.display = 'block';
});
// Add a keydown event listener to handle arrow navigation and selection
input.addEventListener('keydown', function (e) {
// Handle Escape key to remove the banner
if (e.key === 'Escape') {
e.preventDefault(); // Prevent any default behavior
banner.remove(); // Remove the banner
return; // Exit the handler
}
const items = autocompleteList.getElementsByClassName('mzta_autocomplete-item');
if ((autocompleteList.style.display === 'none' || items.length === 0)
&& (e.key !== 'Enter')
&& !['1','2','3','4','5','6','7','8','9','0'].includes(e.key))
{
return; // Do nothing if the autocomplete list is not visible
}
// Handle number key presses (1-9,0) to select the corresponding item directly
if (['1','2','3','4','5','6','7','8','9','0'].includes(e.key)) {
// Map '1' to index 0, '2' to 1, ..., '9' to 8, '0' to 9
const numIndex = (e.key === '0') ? 9 : parseInt(e.key, 10) - 1;
if (items[numIndex]) {
e.preventDefault(); // Prevent any default behavior
// Dispatch a mousedown event to simulate a click/select action
items[numIndex].dispatchEvent(new Event('mousedown'));
return; // Exit after handling the number key
}
}
if (e.key === 'ArrowDown') {
// Navigate down the list
currentFocus++;
if (currentFocus >= items.length) currentFocus = 0; // Wrap to the first item
addActive(items);
e.preventDefault(); // Prevent cursor from moving to the end
} else if (e.key === 'ArrowUp') {
// Navigate up the list
currentFocus--;
if (currentFocus < 0) currentFocus = items.length - 1; // Wrap to the last item
addActive(items);
e.preventDefault(); // Prevent cursor from moving to the start
} else if (e.key === 'Enter') {
console.log(">>>>>>>>>>>>>> keydown == enter selectedId: " + selectedId);
if (selectedId) {
// If an item is already selected, call sendPrompt with the selected ID
e.preventDefault();
sendPrompt(selectedId, tabId); // Call your sendPrompt function
banner.remove(); // Optionally remove the banner after sending the prompt
} else {
// If no item is selected yet, select the highlighted item
// Select the highlighted item, or the first item if none is highlighted
e.preventDefault(); // Prevent form submission if inside a form
if (currentFocus > -1) {
if (items[currentFocus]) {
items[currentFocus].dispatchEvent(new Event('mousedown')); // Trigger the mousedown event
}
} else if (items.length > 0) {
// If no item is highlighted, select the first item
items[0].dispatchEvent(new Event('mousedown'));
}
}
}
});
// Function to add the "active" class to the current item
function addActive(items) {
removeActive(items); // Remove the "active" class from all items
if (currentFocus >= items.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = items.length - 1;
items[currentFocus].classList.add('mzta_autocomplete-item-active'); // Add "active" class to the current item
// Ensure the active item is visible within the scrollable list
items[currentFocus].scrollIntoView({
behavior: 'auto', // You can change to 'smooth' if you prefer smooth scrolling
block: 'nearest', // Align the item to the nearest edge of the visible area
});
}
// Function to remove the "active" class from all items
function removeActive(items) {
for (let i = 0; i < items.length; i++) {
items[i].classList.remove('mzta_autocomplete-item-active');
}
}
// Handle the input field losing focus to hide the banner
input.addEventListener('blur', function() {
// Use a timeout to allow clicking on suggestions before hiding
setTimeout(() => {
banner.remove();
}, 200);
});
document.body.insertBefore(banner, document.body.firstChild);
setTimeout(() => {
input.dispatchEvent(new InputEvent('input', { bubbles: true }));
input.focus();
}, 100);
}
function sendPrompt(prompt_id, tabId){
console.log(">>>>>>>>>>>>> [ThunderAI] sendPrompt: " + prompt_id);
browser.runtime.sendMessage({command: "shortcut_do_prompt", tabId: tabId, promptId: prompt_id});
}
function filterPromptsForTab(prompts_data, filtering){
// If filtering is 0, return the original array without any filters (btw it should not happen)
if (filtering === 0) {
return prompts_data;
}
// Define the types to include based on the value of filtering
let allowedTypes;
if (filtering === 1) {
allowedTypes = ["0", "1"];
} else if (filtering === 2) {
allowedTypes = ["0", "2"];
} else {
// If filtering has an unexpected value, return the original data
return prompts_data;
}
// Filter the array based on the allowed types
return prompts_data.filter(prompt => allowedTypes.includes(prompt.type));
}

View file

@ -19,7 +19,7 @@
// Some original methods are derived from https://github.com/ali-raheem/Aify/blob/cfadf52f576b7be3720b5b73af7c8d3129c054da/plugin/html/actions.js // Some original methods are derived from https://github.com/ali-raheem/Aify/blob/cfadf52f576b7be3720b5b73af7c8d3129c054da/plugin/html/actions.js
import { getPrompts } from './mzta-prompts.js'; import { getPrompts } from './mzta-prompts.js';
import { getLanguageDisplayName, getMenuContextCompose, getMenuContextDisplay } from './mzta-utils.js' import { getLanguageDisplayName, getMenuContextCompose, getMenuContextDisplay, i18nConditionalGet } from './mzta-utils.js'
export class mzta_Menus { export class mzta_Menus {
@ -33,6 +33,10 @@ export class mzta_Menus {
//{ id: 'ItemC', act: (info, tab) => { console.log('ItemC', info, tab, info.menuItemId); alert('ItemC') } }, //{ id: 'ItemC', act: (info, tab) => { console.log('ItemC', info, tab, info.menuItemId); alert('ItemC') } },
]; ];
shortcutMenu = [
//{ id: 'ItemD', label: 'LabelD' },
];
constructor(openChatGPT) { constructor(openChatGPT) {
this.menu_context_compose = getMenuContextCompose(); this.menu_context_compose = getMenuContextCompose();
this.menu_context_display = getMenuContextDisplay(); this.menu_context_display = getMenuContextDisplay();
@ -45,6 +49,7 @@ export class mzta_Menus {
async initialize() { async initialize() {
this.allPrompts = []; this.allPrompts = [];
this.rootMenu = []; this.rootMenu = [];
this.shortcutMenu = [];
this.menu_listeners = {}; this.menu_listeners = {};
this.allPrompts = await getPrompts(true); this.allPrompts = await getPrompts(true);
this.allPrompts.sort((a, b) => a.name.localeCompare(b.name)); this.allPrompts.sort((a, b) => a.name.localeCompare(b.name));
@ -55,7 +60,7 @@ export class mzta_Menus {
async reload(){ async reload(){
await browser.menus.removeAll().catch(error => { await browser.menus.removeAll().catch(error => {
console.error("[ThunderAI] ERROR removing the menus: ", error); console.error("[ThunderAI] ERROR removing the menus: ", error);
}); });
this.removeClickListener(); this.removeClickListener();
this.loadMenus(); this.loadMenus();
@ -140,10 +145,23 @@ export class mzta_Menus {
} }
} }
loadShortcutMenu() {
this.shortcutMenu = [];
this.allPrompts.forEach((prompt) => {
this.addShortcutMenu(prompt);
});
}
addShortcutMenu(prompt) {
let curr_menu_entry = {id: prompt.id, label: i18nConditionalGet(prompt.name), type: prompt.type};
this.shortcutMenu.push(curr_menu_entry);
}
async loadMenus() { async loadMenus() {
await this.initialize(); await this.initialize();
await this.addMenu(this.rootMenu); await this.addMenu(this.rootMenu);
this.addClickListener(); this.addClickListener();
this.loadShortcutMenu();
} }
listener(info, tab) { listener(info, tab) {
@ -219,4 +237,23 @@ export class mzta_Menus {
} }
} }
async executeMenuAction(id) {
// Retrieve the action callback from the menu listeners using the provided ID
const action = this.menu_listeners[id];
if (action) {
try {
// Execute the action callback
await action();
} catch (error) {
// Log any errors that occur during execution
console.error(`Error executing action for menu item ${id}:`, error);
}
} else {
// Warn if no action is found for the provided ID
console.warn(`No action found for menu item ID: ${id}`);
}
}
} }

View file

@ -44,5 +44,10 @@
"default_locale": "en", "default_locale": "en",
"options_ui": { "options_ui": {
"page": "options/mzta-options.html" "page": "options/mzta-options.html"
} },
"commands": {
"_thunderai__do_action": {
"description": ""
}
}
} }

View file

@ -32,12 +32,14 @@ let prefs_debug = await browser.storage.sync.get({do_debug: false});
let taLog = new taLogger("mzta-background",prefs_debug.do_debug); let taLog = new taLogger("mzta-background",prefs_debug.do_debug);
browser.composeScripts.register({ browser.composeScripts.register({
js: [{file: "/js/mzta-compose-script.js"}] js: [{ file: "js/mzta-compose-script.js" }],
css: [{ file: "css/mzta-compose-styles.css" }],
}); });
// Register the message display script for all newly opened message tabs. // Register the message display script for all newly opened message tabs.
messenger.messageDisplayScripts.register({ messenger.messageDisplayScripts.register({
js: [{ file: "js/mzta-compose-script.js" }], js: [{ file: "js/mzta-compose-script.js" }],
css: [{ file: "css/mzta-compose-styles.css" }],
}); });
// Inject script and CSS in all already open message tabs. // Inject script and CSS in all already open message tabs.
@ -52,7 +54,10 @@ for (let messageTab of messageTabs) {
try { try {
await browser.tabs.executeScript(messageTab.id, { await browser.tabs.executeScript(messageTab.id, {
file: "js/mzta-compose-script.js" file: "js/mzta-compose-script.js"
}) });
await browser.tabs.insertCSS(messageTab.id, {
file: "css/mzta-compose-styles.css"
});
} catch (error) { } catch (error) {
console.error("[ThunderAI] Error injecting message display script:", error); console.error("[ThunderAI] Error injecting message display script:", error);
console.error("[ThunderAI] Message tab:", messageTab.url); console.error("[ThunderAI] Message tab:", messageTab.url);
@ -65,6 +70,34 @@ browser.contentScripts.register({
runAt: "document_idle" runAt: "document_idle"
}); });
let ThunderAI_Shortcut = "Ctrl+Alt+A";
// Shortcut
messenger.commands.update({
name: "_thunderai__do_action",
shortcut: ThunderAI_Shortcut
}).then(() => {
taLog.log('Shortcut [' + ThunderAI_Shortcut + '] registered successfully!');
}).catch((error) => {
taLog.error('Error registering shortcut [' + ThunderAI_Shortcut + ']: ' + error);
});
// Listen for shortcut command
messenger.commands.onCommand.addListener((command, tab) => {
if (command === "_thunderai__do_action") {
handleShortcut(tab);
}
});
async function handleShortcut(tab) {
taLog.log("Shortcut triggered!");
if(!["mail", "messageCompose","messageDisplay"].includes(tab.type)){
return;
}
browser.tabs.sendMessage(tab.id, { command: "searchPrompt", _prompts_data: menus.shortcutMenu, tabId: tab.id, _tab_type: tab.type });
}
messenger.runtime.onMessage.addListener(async (message, sender, sendResponse) => { messenger.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
// Check what type of message we have received and invoke the appropriate // Check what type of message we have received and invoke the appropriate
// handler function. // handler function.
@ -147,6 +180,10 @@ messenger.runtime.onMessage.addListener(async (message, sender, sendResponse) =>
await menus.reload(); await menus.reload();
taLog.log("[ThunderAI] Reloaded menus"); taLog.log("[ThunderAI] Reloaded menus");
break; break;
case 'shortcut_do_prompt':
taLog.log("Executing shortcut, promptId: " + message.promptId);
menus.executeMenuAction(message.promptId);
break;
default: default:
break; break;
} }
@ -319,7 +356,7 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_
}); });
const listener4 = async (message, sender, sendResponse) => { const listener4 = async (message, sender, sendResponse) => {
console.log(">>>>>>>>>>>>>> message: " + JSON.stringify(message)); //console.log(">>>>>>>>>>>>>> message: " + JSON.stringify(message));
if (message.command === "openai_comp_api_ready_"+rand_call_id4) { if (message.command === "openai_comp_api_ready_"+rand_call_id4) {
let newWindow4 = await browser.windows.get(message.window_id, {populate: true}); let newWindow4 = await browser.windows.get(message.window_id, {populate: true});