From 46622e2a7a798cb9ac205896bb5ad9a7146d11d3 Mon Sep 17 00:00:00 2001 From: AnisHADJARAB Date: Thu, 31 Oct 2024 12:57:24 +0000 Subject: [PATCH] change header to ts and fix qr generation to only happen in home page --- src/components/header/header.js | 60 -------------------- src/components/header/header.ts | 57 +++++++++++++++++++ src/pages/home/home.ts | 7 ++- src/router.ts | 29 +++++----- src/services/routing.service.ts | 2 - src/services/service.ts | 98 +++++++++++++++------------------ 6 files changed, 122 insertions(+), 131 deletions(-) delete mode 100644 src/components/header/header.js create mode 100644 src/components/header/header.ts diff --git a/src/components/header/header.js b/src/components/header/header.js deleted file mode 100644 index eb8913c..0000000 --- a/src/components/header/header.js +++ /dev/null @@ -1,60 +0,0 @@ -import { currentRoute } from "../../router"; -import Services from "../../services/service"; - - -let notifications = [] - -export async function unpair() { - const service = await Services.getInstance(); - await service.unpairDevice(); - } - - window.unpair = unpair; - - function toggleMenu() { - const menu = document.getElementById('menu'); - if (menu.style.display === 'block') { - menu.style.display = 'none'; - } else { - menu.style.display = 'block'; - } - } - window.toggleMenu = toggleMenu - - async function getNotifications() { - const service = await Services.getInstance() - notifications = service.getNotifications() - console.log("🚀 ~ getNotifications ~ notifications:", notifications) - const badge = document.querySelector('.notification-badge') - if(badge) badge.innerHTML= notifications.length - } - function openCloseNotifications() { - const notifications = document.querySelector('.notification-board'); - console.log("🚀 ~ openCloseNotifications ~ notifications:", notifications) - notifications.style.display = notifications?.style.display === 'none' ? 'block' : 'none'; - } - - window.openCloseNotifications = openCloseNotifications - - - if(currentRoute === 'home') { - hideSomeFunctionnalities() - } else { - getNotifications() - } - - function hideSomeFunctionnalities() { - const bell = document.querySelector('.bell-icon') - if(bell) bell.style.display = 'none'; - const notifBadge = document.querySelector('.notification-badge') - if(notifBadge) notifBadge.style.display = 'none'; - const actions = document.querySelectorAll('.menu-content a') - console.log("🚀 ~ hideSomeFunctionnalities ~ actions:", actions) - for(const action of actions) { - console.log("🚀 ~ hideSomeFunctionnalities ~ action:", action) - if(action.innerHTML !== 'Import') { - action.style.display = 'none'; - } - } - - } \ No newline at end of file diff --git a/src/components/header/header.ts b/src/components/header/header.ts new file mode 100644 index 0000000..06cb1cc --- /dev/null +++ b/src/components/header/header.ts @@ -0,0 +1,57 @@ +import { currentRoute } from '../../router'; +import Services from '../../services/service'; + +let notifications = []; + +export async function unpair() { + const service = await Services.getInstance(); + await service.unpairDevice(); +} + +(window as any).unpair = unpair; + +function toggleMenu() { + const menu = document.getElementById('menu'); + if (menu) { + if (menu.style.display === 'block') { + menu.style.display = 'none'; + } else { + menu.style.display = 'block'; + } + } +} +(window as any).toggleMenu = toggleMenu; + +async function getNotifications() { + const service = await Services.getInstance(); + notifications = service.getNotifications(); + const badge = document.querySelector('.notification-badge') as HTMLDivElement; + if (badge) badge.innerHTML = notifications.length.toString(); +} +function openCloseNotifications() { + const notifications = document.querySelector('.notification-board') as HTMLDivElement; + notifications.style.display = notifications?.style.display === 'none' ? 'block' : 'none'; +} + +(window as any).openCloseNotifications = openCloseNotifications; + +export async function initHeader() { + if (currentRoute === 'home') { + hideSomeFunctionnalities(); + } else { + getNotifications(); + } +} + +function hideSomeFunctionnalities() { + const bell = document.querySelector('.bell-icon') as HTMLDivElement; + if (bell) bell.style.display = 'none'; + const notifBadge = document.querySelector('.notification-badge') as HTMLDivElement; + if (notifBadge) notifBadge.style.display = 'none'; + const actions = document.querySelectorAll('.menu-content a') as NodeListOf; + for (const action of actions) { + if (action.innerHTML !== 'Import') { + action.style.display = 'none'; + } + } +} diff --git a/src/pages/home/home.ts b/src/pages/home/home.ts index 462c1c4..5a5c508 100644 --- a/src/pages/home/home.ts +++ b/src/pages/home/home.ts @@ -6,7 +6,7 @@ let resultContainer = document.getElementById('qr-reader-results'); let lastResult: any, countResults = 0; -export function initHomePage(): void { +export async function initHomePage(): Promise { console.log('INIT'); document.querySelectorAll('.tab').forEach((tab) => { tab.addEventListener('click', () => { @@ -18,6 +18,11 @@ export function initHomePage(): void { }); }); + const service = await Services.getInstance(); + const spAddress = await service.getDeviceAddress() + service.generateQRCode(spAddress) + service.displayEmojis(spAddress) + document.getElementById('notification-bell')?.addEventListener('click', openCloseNotifications); var html5QrcodeScanner = new Html5QrcodeScanner('qr-reader', { fps: 10, qrbox: 250 }, undefined); diff --git a/src/router.ts b/src/router.ts index 2c2014b..a4d926b 100644 --- a/src/router.ts +++ b/src/router.ts @@ -1,4 +1,5 @@ import '../public/style/4nk.css'; +import { initHeader } from './components/header/header'; import Services from './services/service'; const routes: { [key: string]: string } = { @@ -26,6 +27,7 @@ async function handleLocation(path: string) { if (path.includes('/')) { path = parsedPath[0]; } + currentRoute = path const routeHtml = routes[path] || routes['home']; const content = document.getElementById('containerId'); @@ -48,14 +50,19 @@ async function handleLocation(path: string) { initProcessElement(parseProcess[0], parseProcess[1]); } } - currentRoute = path; } } -window.onpopstate = () => handleLocation('home'); +window.onpopstate = async () => { + const services = await Services.getInstance(); + if(!services.isPaired()) { + handleLocation('home') + } else { + handleLocation('process') + } +}; -async function init(): Promise { - let isPaired = false; +async function init(): Promise { try { const services = await Services.getInstance(); setTimeout(async () => { @@ -71,10 +78,7 @@ async function init(): Promise { await services.restoreMessages(); if (services.isPaired()) { - isPaired = true; - console.log('🚀 ~ setTimeout ~ isPaired:', isPaired); await navigate('process'); - return isPaired; } else { const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); @@ -82,14 +86,13 @@ async function init(): Promise { if (pairingAddress) { setTimeout(async () => await services.sendPairingTx(pairingAddress), 2000); } - return isPaired; + await navigate('home'); } }, 200); } catch (error) { console.error(error); - return isPaired; + await navigate('home'); } - return isPaired; } async function injectHeader() { @@ -100,13 +103,13 @@ async function injectHeader() { // Dynamically load the header JS const script = document.createElement('script'); - script.src = '/src/components/header/header.js'; + script.src = '/src/components/header/header.ts'; script.type = 'module'; document.head.appendChild(script); + initHeader() } } (async () => { - const isPaired = await init(); - await navigate('home'); + await init(); })(); diff --git a/src/services/routing.service.ts b/src/services/routing.service.ts index cf38442..5109013 100644 --- a/src/services/routing.service.ts +++ b/src/services/routing.service.ts @@ -83,8 +83,6 @@ export default class Routing { } confirmLogin() { console.log('=============> Confirm Login'); - const loginTx = this.sdkClient.create_login_transaction(1); - this.sdkClient.login('LOGIN', loginTx); } async closeLoginModal() { const modal = document.getElementById('login-modal'); diff --git a/src/services/service.ts b/src/services/service.ts index 65b67c4..7aa1286 100644 --- a/src/services/service.ts +++ b/src/services/service.ts @@ -4,9 +4,9 @@ import { IProcess } from '~/models/process.model'; // import Database from './database'; import { WebSocketClient } from '../websockets'; import QRCode from 'qrcode'; -import { ApiReturn } from '../../dist/pkg/sdk_client'; +import { ApiReturn, Member } from '../../dist/pkg/sdk_client'; import Routing from './routing.service'; -import { currentRoute } from '../router'; +import { currentRoute, navigate } from '../router'; type ProcessesCache = { [key: string]: any; @@ -64,7 +64,7 @@ export default class Services { } } - private generateQRCode = async (text: string) => { + generateQRCode = async (text: string) => { try { const container = document.getElementById('containerId'); const currentUrl = 'https://' + window.location.host; @@ -162,7 +162,7 @@ export default class Services { } // Display address emojis and other device emojis - private displayEmojis = async (text: string) => { + displayEmojis = async (text: string) => { console.log('🚀 ~ Services ~ adressToEmoji'); try { const container = document.getElementById('containerId'); @@ -411,48 +411,48 @@ export default class Services { async pairDevice(prd: any, outpointCommitment: string) { console.log('🚀 ~ Services ~ pairDevice ~ prd:', prd); - // const service = await Services.getInstance(); - // const spAddress = await this.getDeviceAddress() as any; - // const sender = JSON.parse(prd?.sender) - // const senderAddress = sender?.sp_addresses?.find((address: string) => address !== spAddress) - // console.log("🚀 ~ Services ~ pairDevice ~ senderAddress:", senderAddress) - // if(senderAddress) { - // const proposal = service.sdkClient.get_update_proposals(outpointCommitment); - // console.log("🚀 ~ Services ~ pairDevice ~ proposal:", proposal) - // // const pairingTx = proposal.pairing_tx.replace(/^\"+|\"+$/g, '') - // const parsedProposal = JSON.parse(proposal[0]) + const service = await Services.getInstance(); + const spAddress = (await this.getDeviceAddress()) as any; + const sender = JSON.parse(prd?.sender); + const senderAddress = sender?.sp_addresses?.find((address: string) => address !== spAddress); + console.log('🚀 ~ Services ~ pairDevice ~ senderAddress:', senderAddress); + if (senderAddress) { + const proposal = service.sdkClient.get_update_proposals(outpointCommitment); + console.log('🚀 ~ Services ~ pairDevice ~ proposal:', proposal); + // const pairingTx = proposal.pairing_tx.replace(/^\"+|\"+$/g, '') + const parsedProposal = JSON.parse(proposal[0]); - // console.log("🚀 ~ Services ~ pairDevice ~ parsedProposal:", parsedProposal) - // const roles = JSON.parse(parsedProposal.roles) - // console.log("🚀 ~ Services ~ pairDevice ~ roles:", roles, Array.isArray(roles), !roles.owner) - // if(Array.isArray(roles) || !roles.owner) return - // const proposalMembers = roles?.owner?.members - // const isFirstDevice = proposalMembers.some((member: Member) => member.sp_addresses.some(address => address === spAddress)) - // const isSecondDevice = proposalMembers.some((member: Member) => member.sp_addresses.some(address => address === senderAddress)) - // console.log("🚀 ~ Services ~ pairDevice ~ proposalMembers:", proposalMembers) - // if(proposalMembers?.length !== 2 || !isFirstDevice || !isSecondDevice) return - // const pairingTx = parsedProposal?.pairing_tx?.replace(/^\"+|\"+$/g, '') + console.log('🚀 ~ Services ~ pairDevice ~ parsedProposal:', parsedProposal); + const roles = JSON.parse(parsedProposal.roles); + console.log('🚀 ~ Services ~ pairDevice ~ roles:', roles, Array.isArray(roles), !roles.owner); + if (Array.isArray(roles) || !roles.owner) return; + const proposalMembers = roles?.owner?.members; + const isFirstDevice = proposalMembers.some((member: Member) => member.sp_addresses.some((address) => address === spAddress)); + const isSecondDevice = proposalMembers.some((member: Member) => member.sp_addresses.some((address) => address === senderAddress)); + console.log('🚀 ~ Services ~ pairDevice ~ proposalMembers:', proposalMembers); + if (proposalMembers?.length !== 2 || !isFirstDevice || !isSecondDevice) return; + const pairingTx = parsedProposal?.pairing_tx?.replace(/^\"+|\"+$/g, ''); - // let txid = '0'.repeat(64) - // console.log("🚀 ~ Services ~ pairDevice ~ pairingTx:", pairingTx, `${txid}:4294967295`) + let txid = '0'.repeat(64); + console.log('🚀 ~ Services ~ pairDevice ~ pairingTx:', pairingTx, `${txid}:4294967295`); - // const pairing = await service.sdkClient.pair_device(`${txid}:4294967295`, [senderAddress]) - // const device = this.dumpDevice() - // console.log("🚀 ~ Services ~ pairDevice ~ device:", device) - // this.saveDevice(device) - // // await service.sdkClient.pair_device(pairingTx, [senderAddress]) - // console.log("🚀 ~ Services ~ pairDevice ~ pairing:", pairing) - // // const process = await this.prepareProcessTx(spAddress, senderAddress) - // console.log("🚀 ~ Services ~ pairDevice ~ process:", outpointCommitment, prd, prd.payload) - // const prdString = JSON.stringify(prd).trim() - // console.log("🚀 ~ Services ~ pairDevice ~ prdString:", prdString) - // let tx = await service.sdkClient.response_prd(outpointCommitment, prdString, true) - // console.log("🚀 ~ Services ~ pairDevice ~ tx:", tx) - // if(tx.ciphers_to_send) { - // tx.ciphers_to_send.forEach((cipher: string) => service.websocketConnection?.sendMessage('Cipher', cipher)) - // } - // this.injectProcessListPage() - // } + const pairing = await service.sdkClient.pair_device(`${txid}:4294967295`, [senderAddress]); + const device = this.dumpDevice(); + console.log('🚀 ~ Services ~ pairDevice ~ device:', device); + this.saveDevice(device); + // await service.sdkClient.pair_device(pairingTx, [senderAddress]) + console.log('🚀 ~ Services ~ pairDevice ~ pairing:', pairing); + // const process = await this.prepareProcessTx(spAddress, senderAddress) + console.log('🚀 ~ Services ~ pairDevice ~ process:', outpointCommitment, prd, prd.payload); + const prdString = JSON.stringify(prd).trim(); + console.log('🚀 ~ Services ~ pairDevice ~ prdString:', prdString); + let tx = await service.sdkClient.response_prd(outpointCommitment, prdString, true); + console.log('🚀 ~ Services ~ pairDevice ~ tx:', tx); + if (tx.ciphers_to_send) { + tx.ciphers_to_send.forEach((cipher: string) => service.websocketConnection?.sendMessage('Cipher', cipher)); + } + navigate('process'); + } } // async saveTxToDb(tx: CachedMessage) { @@ -522,12 +522,6 @@ export default class Services { console.error('Services ~ Error:', e); } - if (currentRoute === 'home') { - this.generateQRCode(spAddress || ''); - //Adress to Emoji integration - this.displayEmojis(spAddress); - //Adress to Emoji integration - } return spAddress; } @@ -535,12 +529,6 @@ export default class Services { try { await this.sdkClient.restore_device(device); const spAddress = this.sdkClient.get_address(); - if (currentRoute === 'home') { - this.generateQRCode(spAddress || ''); - //Adress to Emoji integration - this.displayEmojis(spAddress); - //Adress to Emoji integration - } } catch (e) { console.error(e); }