Skip to content

Commit

Permalink
Merge pull request #26 from toastr-space/account_switch
Browse files Browse the repository at this point in the history
account switch
  • Loading branch information
satoshisound authored Dec 26, 2023
2 parents 0bf6bd0 + 5d3d490 commit 42a6d36
Show file tree
Hide file tree
Showing 14 changed files with 149 additions and 50 deletions.
20 changes: 20 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
name: Node.js CI

on: [push]

jobs:
build:

runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4
- name: Use Node.js
uses: actions/setup-node@v3
with:
node-version: '20.x'
- run: npm install -g pnpm
- run: pnpm install
# - run: pnpm lint
- run: pnpm check
- run: pnpm run build
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"private": true,
"scripts": {
"dev": "vite dev",
"build": "vite build",
"build": "vite build && npx esbuild ./src/lib/services/background.ts --bundle --outdir=build/ && npx esbuild ./src/lib/services/content.ts --bundle --outdir=build/",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
Expand Down
64 changes: 36 additions & 28 deletions src/lib/components/AccountDropdownMenu.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,19 @@
import { profileController } from '$lib/controllers/profile.controller';
export let accountDropdownMenuOpen: boolean;
export let canEdit: boolean = true;
const load = (profile: Profile) => profileController.loadProfile(profile);
</script>

<div data-popup="accountDropdownMenu">
<div
class="menu-modal card w-72 shadow-xl backdrop-blur-xl bg-surface-200 dark:bg-zinc-800 pt-3 rounded-2xl border-[0.33px] border-solid border-white border-opacity-30"
class="menu-modal card w-72 shadow-xl backdrop-blur-xl bg-surface-200 dark:bg-zinc-800 pt-3 rounded-2xl border-[0.33px] border-solid border-white border-opacity-30 pl-1"
>
<nav class="list-nav">
<ul>
<nav class="list-nav w-full" class:pb-3={canEdit}>
<ul class="w-full">
{#each $profiles as profile}
<li class="flex w-full items-stretch justify-between">
<li class="flex w-full gap-2">
<div class="flex-grow">
<button class="btn px-0 py-0" on:click={() => load(profile)}>
<Avatar
Expand All @@ -40,34 +41,41 @@
</button>
</div>

<div class="flex-shrink-0">
<button
class="btn btn-sm text-gray-500 px-0 py-0 mt-2"
on:click={async () => {
await profileController.deleteProfile(profile);
await tick();
accountDropdownMenuOpen = true;
}}
>
<Icon icon="mdi:trash-can-outline" width={22} />
</button>
</div>
{#if canEdit}
<div class="flex-shrink-0">
<button
class="btn btn-sm text-gray-500 px-0 py-0 mt-2"
on:click={async () => {
await profileController.deleteProfile(profile);
await tick();
accountDropdownMenuOpen = true;
}}
>
<Icon icon="mdi:trash-can-outline" width={22} />
</button>
</div>
{/if}
</li>
{/each}
<li
class="justify-center items-stretch self-stretch flex w-full flex-col py-3 border-t-[0.33px] border-t-black dark:border-t-white border-solid"
>
<button
on:click={() => {
currentPage.set(Page.AddProfile);
}}
class="mx-2"
{#if canEdit}
<li
class="justify-center items-stretch self-stretch flex w-full mb-2 flex-col py-3 border-t-[0.33px] border-t-black dark:border-t-white border-solid"
>
<span class="badge text-black dark:text-white"><Icon icon="mdi:plus" width={22} /></span
<button
on:click={() => {
currentPage.set(Page.AddProfile);
}}
class="mx-2"
>
<span class="flex-auto text-black dark:text-white">Add Account</span>
</button>
</li>
<span class="badge text-black dark:text-white"
><Icon icon="mdi:plus" width={22} /></span
>
<span class="flex-auto text-black dark:text-white">Add Account</span>
</button>
</li>
{:else}
<li class="h-4 w-2" />
{/if}
</ul>
</nav>
</div>
Expand Down
2 changes: 2 additions & 0 deletions src/lib/controllers/browser.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,14 @@ const createBrowserController = (): Browser => {
};
const injectJsInTab = async (tab: chrome.tabs.Tab, jsFileName: string): Promise<void> => {
try {

await web.scripting.executeScript({
target: { tabId: tab.id as number },
files: [jsFileName]
});
return;
} catch (e) {
console.error(tab.id, tab.url)
console.error('Error injecting Nostr Provider', e);
return Promise.reject(e);
}
Expand Down
35 changes: 25 additions & 10 deletions src/lib/services/background.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Message, MessageSender, Responders } from '$lib/types';
import type { WebSite, Authorization } from '$lib/types/profile';
import type { WebSite, Authorization, Profile } from '$lib/types/profile';

import { finishEvent, getPublicKey, nip04 } from 'nostr-tools';
import { urlToDomain, web, BrowserUtil, ProfileUtil } from '../utility';
Expand All @@ -10,11 +10,33 @@ import { profileController } from '$lib/controllers/profile.controller';
import { sessionController } from '$lib/controllers/session.controller';
import { backgroundController } from '$lib/controllers/background.controller';

const session = sessionController();
const background = backgroundController();
const session = sessionController();

const switchIcon = async (activeInfo: { tabId: number }) => {
const tab = await web.tabs.get(activeInfo.tabId);

const user: Profile = await background.getUserProfile();
const domain = urlToDomain(tab.url || '');
const webSites = user.data?.webSites as { [key: string]: WebSite };
if (webSites !== undefined && domain in webSites) {
web.action.setIcon({
tabId: tab.id,
path: 'assets/logo-on.png'
});
} else {
web.action.setIcon({
tabId: tab.id,
path: 'assets/logo-off.png'
});
}
}


web.runtime.onInstalled.addListener(() => BrowserUtil.injectJsinAllTabs('content.js'));
web.runtime.onStartup.addListener(() => BrowserUtil.injectJsinAllTabs('content.js'));
web.tabs.onActivated.addListener(async (activeInfo) => switchIcon(activeInfo));
BrowserUtil.getCurrentTab().then((tab) => switchIcon({ tabId: tab.id as number }));

const responders: Responders = {};
const requestQueue: any[] = [];
Expand Down Expand Up @@ -172,16 +194,10 @@ async function manageRequest(message: Message, resolver: any = null, next: boole
const user = await background.getUserProfile();
const domain = urlToDomain(message.url || '');

// const popupWindow = (await web.windows.getAll()).find((win) => win.type === 'popup');

if (next === false) {
requestQueue.push({ message, resolver: resolve });
return
}
// if (popupWindow !== undefined || requestQueue.length > 0) {
//
// return;
// }

if (user.data?.privateKey === undefined)
return Promise.resolve(
Expand Down Expand Up @@ -260,7 +276,6 @@ const proceedNextRequest = async () => {
const popupWindow = (await web.windows.getAll()).find((win) => win.type === 'popup');
if (popupWindow === undefined && requestQueue.length > 0) {
const { message, resolver } = requestQueue.shift();
console.log('requestQueue', requestQueue.length, 'sending message', message, 'to popup');
manageRequest(message, resolver, true);
}
}
Expand All @@ -278,7 +293,7 @@ web.runtime.onMessage.addListener((message: Message, sender: MessageSender, send
sendResponse(data);
})
.catch((err) => {
console.error(err, 'happened');
console.error(err);
}).finally(() => {
proceedNextRequest();
})
Expand Down
1 change: 1 addition & 0 deletions src/routes/+layout.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
storePopup.set({ computePosition, autoUpdate, offset, shift, flip, arrow });
if (typeof document !== 'undefined') profileController.loadTheme();
onMount(() => {
profileController.loadDuration();
NostrUtil.prepareRelayPool();
Expand Down
3 changes: 1 addition & 2 deletions src/routes/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@
import { AppPage } from '$lib/components/App';
import { profileController } from '$lib/controllers/profile.controller';
import { PageSettings, PageHome, PageAddProfile } from '$lib/pages';
import { PageSettings, PageHome, PageAddProfile } from '$lib/Pages';
// Set theme based on local storage
if (typeof document !== 'undefined') profileController.loadTheme();
const promise = profileController.loadProfiles();
</script>
Expand Down
58 changes: 55 additions & 3 deletions src/routes/popup/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,34 @@
import { browserController } from '$lib/controllers';
import { urlToDomain } from '$lib/utility/utils';
import { onMount } from 'svelte';
import { sessionData } from '$lib/stores/data';
import type { PopupSettings } from '@skeletonlabs/skeleton';
import AccountDropdownMenu from '$lib/components/AccountDropdownMenu.svelte';
import { profileController } from '$lib/controllers/profile.controller';
import { sessionData, userProfile } from '$lib/stores/data';
import { popup, Avatar } from '@skeletonlabs/skeleton';
import { derived } from 'svelte/store';
import { onMount } from 'svelte';
import Icon from '@iconify/svelte';
let parameter: PopupParams;
let accountDropdownMenuOpen = false;
const accountDropdownMenu: PopupSettings = {
event: 'click',
target: 'accountDropdownMenu',
placement: 'bottom',
state: async () => {
accountDropdownMenuOpen = false;
}
};
const displayName = derived(userProfile, ($userProfile) => {
const name = $userProfile?.metadata?.name || $userProfile?.name || 'Click to select account';
return name.length > 12 ? name.slice(0, 12) + '...' : name;
});
async function handleData() {
profileController.loadProfiles();
const urlParams = new URLSearchParams(document.location.search);
Expand All @@ -26,8 +48,38 @@
});
</script>

<div class="w-full h-full flex flex-col p-4 mx-auto items-center bg-[#222222]">
<div class="w-full h-full flex flex-col p-4 mx-auto items-center dark:bg-[#222222] bg-white">
{#if parameter?.url}
<div class="w-full bg-surface-400 rounded-lg dark:bg-black bg-opacity-50 h-[72px]">
<div
class="text-gray-800 dark:text-gray-400 text-opacity-70 font-semibold leading-4 tracking-[3px] flex flex-row items-center gap-2 p-2"
>
<button
class="btn background-surface-700 pl-0 items-center"
use:popup={accountDropdownMenu}
on:click={() => (accountDropdownMenuOpen = !accountDropdownMenuOpen)}
>
<span class="flex flex-row gap-1 items-center justify-between w-[250px]">
<Avatar
src={$userProfile?.metadata?.picture || 'https://toastr.space/images/toastr.png'}
width="w-10"
rounded="rounded-full"
/>
<div
class="text-black dark:text-white text-xl font-semibold leading-7 text-ellipsis overflow-hidden flex-grow my-auto"
>
{$displayName}
</div>
<Icon
icon={accountDropdownMenuOpen ? 'mdi:chevron-up' : 'mdi:chevron-down'}
width={28}
class="text-gray-500 ml-2 mt-1"
/>
</span>
</button>
</div>
<AccountDropdownMenu {accountDropdownMenuOpen} canEdit={false} />
</div>
<Authorization
popupType={parameter.type}
isPopup={true}
Expand Down
Binary file added static/assets/logo-off-64.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/assets/logo-on-64.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions static/assets/nostr-provider.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ window.addEventListener("message", (message) => {
return;

if (message.data.response.error) {
if (message.data.response.error.code === 'invalid_public_key') {
alert('Invalid public key, please switch to the correct account and refresh the page');
}
let error = new Error("keys.band: " + message.data.response.error.message);
error.stack = message.data.response.error.stack;
window.nostr._requests[message.data.id].reject(error);
Expand Down
Binary file modified static/favicon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 3 additions & 3 deletions static/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@
"icons": {
"16": "assets/logo-on.png",
"32": "assets/logo-on.png",
"48": "assets/logo-on.png",
"128": "assets/logo-on.png"
"48": "assets/logo-on-64.png",
"128": "assets/logo-on-64.png"
},
"background": {
"service_worker": "background.js"
},
"permissions": ["storage", "scripting", "tabs"],
"host_permissions": ["https://*/*", "http://*/*"],
"host_permissions": ["https://*/*", "http://*/*", "<all_urls>"],
"content_scripts": [
{
"matches": ["<all_urls>"],
Expand Down
5 changes: 2 additions & 3 deletions tailwind.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,8 @@ export default {
darkMode: 'class',
plugins: [
require('@tailwindcss/typography'),
require("@tailwindcss/forms")({
strategy: 'base', // only generate global styles
strategy: 'class', // only generate classes
require('@tailwindcss/forms')({
strategy: 'base' // only generate global styles
}),
skeleton({
themes: {
Expand Down

0 comments on commit 42a6d36

Please sign in to comment.