Skip to content

Commit

Permalink
⚡ Add manage key option
Browse files Browse the repository at this point in the history
  • Loading branch information
nilooy committed Jul 2, 2022
1 parent e1f9144 commit 19f4dc3
Show file tree
Hide file tree
Showing 9 changed files with 103 additions and 91 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"firefox:web": "vite build --watch",
"firefox:preview": "vite preview",
"firefox:build": "tsup src/background src/content --format iife --out-dir extension/dist --no-splitting",
"firefox:open": "npm run wait && web-ext run --start-url \"about:debugging#/runtime/this-firefox\" --source-dir ./extension/ --no-reload --browser-console",
"firefox:open": "npm run wait && web-ext run --start-url \"about:debugging#/runtime/this-firefox\" --source-dir ./extension/ --browser-console",
"build:chrome": "run-s clear build:web build:prepare build:js",
"build:firefox": "run-s clear build:web 'build:prepare -- --firefox' build:js",
"build:prepare": "esno scripts/prepare.ts build",
Expand Down
61 changes: 0 additions & 61 deletions packageOld.json

This file was deleted.

40 changes: 40 additions & 0 deletions src/background/events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import browser from "webextension-polyfill";
import { KEY_PREFIX } from "../constants";
import { StorageChange } from "../types";



export const handleStorageChange = async (changes: {
[index: string]: StorageChange
}) => {
{
const changedArray: StorageChange[] = Object.values(changes)

if(!changedArray?.length) return null;

changedArray.forEach(({oldValue, newValue}: StorageChange) => {
// ADD KEY
if(!oldValue && newValue) {
console.log({'create': true, oldValue, newValue});
browser.contextMenus.create({
title: `Search on ${newValue.url}`,
contexts: ["selection"],
id: `${KEY_PREFIX}-${newValue.id}`,
});
}
// REMOVE KEY
else if (oldValue && !newValue){
console.log({'REMOVE': true, oldValue, newValue});
browser.contextMenus.remove(oldValue.id);
}
// EDIT KEY
else if (oldValue && newValue){
console.log({'EDIT': true, oldValue, newValue});
browser.contextMenus.update(oldValue.id, {
title: `Search on ${newValue.url}`,
contexts: ["selection"],
});
}
})
}
}
68 changes: 44 additions & 24 deletions src/background/index.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,70 @@
import browser from "webextension-polyfill";
import browser, { Menus } from "webextension-polyfill";
import { keyLists } from "./superkey.db.json";
import { handleStorageChange } from "./events";
import { KEY_PREFIX } from "../constants";

const KEY_PREFIX = "superkey";
interface IDefaultMenu extends Menus.CreateCreatePropertiesType{
// for future
}

const DEFAULT_CONTEXT_MENUS: IDefaultMenu[] = [
{
title: `Manage Keys`,
contexts: ["all"],
id: `addNew`,
}
]

const handleDefaultMenuClick = async (id: string) => {
const defaultKey = DEFAULT_CONTEXT_MENUS.find(each => each.id === id)
let urlToGo:string = '';
if(defaultKey?.id === 'addNew')
urlToGo = browser.runtime.getURL('dist/options/index.html')

return urlToGo && browser.tabs.create({
url: urlToGo,
});
}

function handleSearch(info: any, tab: any) {
async function handleSearch(info: any, tab: any) {
const [keyPrefix, indexKey] = info.menuItemId.split("-");

if (keyPrefix !== KEY_PREFIX || !info.selectionText) return;
if (keyPrefix !== KEY_PREFIX) return;

await handleDefaultMenuClick(indexKey)

if(!info.index) return;

browser.storage.sync.get(indexKey).then((item) => {
const keyItem = item[indexKey];

browser.tabs.create({
return keyItem && browser.tabs.create({
url: `${keyItem.queryUrl}=${encodeURI(info.selectionText)}`,
});
});
}

browser.runtime.onInstalled.addListener(async () => {
// CLEAN ALL CONTEXT MENU BEFORE ADDING/RESETTING ALL KEYS
await browser.contextMenus.removeAll()

// Add Default Menus
DEFAULT_CONTEXT_MENUS.forEach(({title,contexts,id }:Menus.CreateCreatePropertiesType) =>
browser.contextMenus.create({
title,contexts,id: `${KEY_PREFIX}-${id}`
}))

// Add User Keys
keyLists.forEach((keyItem, index) => {
const indexKey = index + 1;
browser.storage.sync
// @ts-ignore
.set({ [indexKey]: { id: indexKey, ...keyItem } }) // TODO: Test carefully.
.then(() => browser.runtime.openOptionsPage());

// context menu
if (keyItem.queryUrl) {
browser.contextMenus.create({
title: `Search on ${keyItem.url}`,
contexts: ["selection"],
id: `${KEY_PREFIX}-${indexKey}`,
});
}
// This will trigger handleStorageChange
});
});

browser.contextMenus.onClicked.addListener(handleSearch);

browser.storage.onChanged.addListener(function (changes) {
const { newValue } = Object.values(changes)?.[0] || {};

if (newValue.queryUrl)
browser.contextMenus.create({
title: `Search on ${newValue.url}`,
contexts: ["selection"],
id: `${KEY_PREFIX}-${newValue.id}`,
});
});
browser.storage.onChanged.addListener(handleStorageChange);
4 changes: 1 addition & 3 deletions src/components/autocomplete/suggestions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,7 @@ const Suggestions: FunctionComponent<ISuggestionsProps> = ({
className="ml-2 badge badge-accent badge-outline text-xs cursor-pointer hover:bg-accent hover:text-gray-100 hover:border-none"
onClick={() =>
window.open(
browser.runtime.getURL(
"features/options/index.html#add-key-modal"
)
browser.runtime.getURL('dist/options/index.html#add-key-modal')
)
}
>
Expand Down
2 changes: 1 addition & 1 deletion src/components/autocomplete/use-autocomplete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export const useAutocomplete = () => {
const handleChange = useCallback(
async (e: Event) => {
const target = e.currentTarget as HTMLInputElement;
const userInput = target.value;
const userInput = target.value?.toLowerCase();
let newFilteredSuggestions: ISuperKeyOptional[] = [];

if (isSearchingBookmarks(userInput)) {
Expand Down
1 change: 1 addition & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const KEY_PREFIX = "superkey";
2 changes: 1 addition & 1 deletion src/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export async function getManifest(isFirefoxInArg: boolean = false) {
const shortCut = {
[`_execute${isFirefoxInArg ? "_browser" : ""}_action`]: {
suggested_key: {
windows: "Alt+Space",
windows: "Ctrl+Space",
mac: "Alt+Space",
},
},
Expand Down
14 changes: 14 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,17 @@ export interface ISearchHandler {
keyItem: ISuperKeyOptional | null;
value?: string;
}

export interface StorageChange {
/**
* The old value of the item, if there was an old value.
* Optional.
*/
oldValue?: any;

/**
* The new value of the item, if there is a new value.
* Optional.
*/
newValue?: any;
}

0 comments on commit 19f4dc3

Please sign in to comment.