change header to ts and fix qr generation to only happen in home page

This commit is contained in:
AnisHADJARAB 2024-10-31 12:57:24 +00:00
parent 8767b5c5c4
commit 46622e2a7a
6 changed files with 122 additions and 131 deletions

View File

@ -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';
}
}
}

View File

@ -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<HTMLAnchorElement>;
for (const action of actions) {
if (action.innerHTML !== 'Import') {
action.style.display = 'none';
}
}
}

View File

@ -6,7 +6,7 @@ let resultContainer = document.getElementById('qr-reader-results');
let lastResult: any, let lastResult: any,
countResults = 0; countResults = 0;
export function initHomePage(): void { export async function initHomePage(): Promise<void> {
console.log('INIT'); console.log('INIT');
document.querySelectorAll('.tab').forEach((tab) => { document.querySelectorAll('.tab').forEach((tab) => {
tab.addEventListener('click', () => { 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); document.getElementById('notification-bell')?.addEventListener('click', openCloseNotifications);
var html5QrcodeScanner = new Html5QrcodeScanner('qr-reader', { fps: 10, qrbox: 250 }, undefined); var html5QrcodeScanner = new Html5QrcodeScanner('qr-reader', { fps: 10, qrbox: 250 }, undefined);

View File

@ -1,4 +1,5 @@
import '../public/style/4nk.css'; import '../public/style/4nk.css';
import { initHeader } from './components/header/header';
import Services from './services/service'; import Services from './services/service';
const routes: { [key: string]: string } = { const routes: { [key: string]: string } = {
@ -26,6 +27,7 @@ async function handleLocation(path: string) {
if (path.includes('/')) { if (path.includes('/')) {
path = parsedPath[0]; path = parsedPath[0];
} }
currentRoute = path
const routeHtml = routes[path] || routes['home']; const routeHtml = routes[path] || routes['home'];
const content = document.getElementById('containerId'); const content = document.getElementById('containerId');
@ -48,14 +50,19 @@ async function handleLocation(path: string) {
initProcessElement(parseProcess[0], parseProcess[1]); 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<boolean> { async function init(): Promise<void> {
let isPaired = false;
try { try {
const services = await Services.getInstance(); const services = await Services.getInstance();
setTimeout(async () => { setTimeout(async () => {
@ -71,10 +78,7 @@ async function init(): Promise<boolean> {
await services.restoreMessages(); await services.restoreMessages();
if (services.isPaired()) { if (services.isPaired()) {
isPaired = true;
console.log('🚀 ~ setTimeout ~ isPaired:', isPaired);
await navigate('process'); await navigate('process');
return isPaired;
} else { } else {
const queryString = window.location.search; const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString); const urlParams = new URLSearchParams(queryString);
@ -82,14 +86,13 @@ async function init(): Promise<boolean> {
if (pairingAddress) { if (pairingAddress) {
setTimeout(async () => await services.sendPairingTx(pairingAddress), 2000); setTimeout(async () => await services.sendPairingTx(pairingAddress), 2000);
} }
return isPaired; await navigate('home');
} }
}, 200); }, 200);
} catch (error) { } catch (error) {
console.error(error); console.error(error);
return isPaired; await navigate('home');
} }
return isPaired;
} }
async function injectHeader() { async function injectHeader() {
@ -100,13 +103,13 @@ async function injectHeader() {
// Dynamically load the header JS // Dynamically load the header JS
const script = document.createElement('script'); const script = document.createElement('script');
script.src = '/src/components/header/header.js'; script.src = '/src/components/header/header.ts';
script.type = 'module'; script.type = 'module';
document.head.appendChild(script); document.head.appendChild(script);
initHeader()
} }
} }
(async () => { (async () => {
const isPaired = await init(); await init();
await navigate('home');
})(); })();

View File

@ -83,8 +83,6 @@ export default class Routing {
} }
confirmLogin() { confirmLogin() {
console.log('=============> Confirm Login'); console.log('=============> Confirm Login');
const loginTx = this.sdkClient.create_login_transaction(1);
this.sdkClient.login('LOGIN', loginTx);
} }
async closeLoginModal() { async closeLoginModal() {
const modal = document.getElementById('login-modal'); const modal = document.getElementById('login-modal');

View File

@ -4,9 +4,9 @@ import { IProcess } from '~/models/process.model';
// import Database from './database'; // import Database from './database';
import { WebSocketClient } from '../websockets'; import { WebSocketClient } from '../websockets';
import QRCode from 'qrcode'; 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 Routing from './routing.service';
import { currentRoute } from '../router'; import { currentRoute, navigate } from '../router';
type ProcessesCache = { type ProcessesCache = {
[key: string]: any; [key: string]: any;
@ -64,7 +64,7 @@ export default class Services {
} }
} }
private generateQRCode = async (text: string) => { generateQRCode = async (text: string) => {
try { try {
const container = document.getElementById('containerId'); const container = document.getElementById('containerId');
const currentUrl = 'https://' + window.location.host; const currentUrl = 'https://' + window.location.host;
@ -162,7 +162,7 @@ export default class Services {
} }
// Display address emojis and other device emojis // Display address emojis and other device emojis
private displayEmojis = async (text: string) => { displayEmojis = async (text: string) => {
console.log('🚀 ~ Services ~ adressToEmoji'); console.log('🚀 ~ Services ~ adressToEmoji');
try { try {
const container = document.getElementById('containerId'); const container = document.getElementById('containerId');
@ -411,48 +411,48 @@ export default class Services {
async pairDevice(prd: any, outpointCommitment: string) { async pairDevice(prd: any, outpointCommitment: string) {
console.log('🚀 ~ Services ~ pairDevice ~ prd:', prd); console.log('🚀 ~ Services ~ pairDevice ~ prd:', prd);
// const service = await Services.getInstance(); const service = await Services.getInstance();
// const spAddress = await this.getDeviceAddress() as any; const spAddress = (await this.getDeviceAddress()) as any;
// const sender = JSON.parse(prd?.sender) const sender = JSON.parse(prd?.sender);
// const senderAddress = sender?.sp_addresses?.find((address: string) => address !== spAddress) const senderAddress = sender?.sp_addresses?.find((address: string) => address !== spAddress);
// console.log("🚀 ~ Services ~ pairDevice ~ senderAddress:", senderAddress) console.log('🚀 ~ Services ~ pairDevice ~ senderAddress:', senderAddress);
// if(senderAddress) { if (senderAddress) {
// const proposal = service.sdkClient.get_update_proposals(outpointCommitment); const proposal = service.sdkClient.get_update_proposals(outpointCommitment);
// console.log("🚀 ~ Services ~ pairDevice ~ proposal:", proposal) console.log('🚀 ~ Services ~ pairDevice ~ proposal:', proposal);
// // const pairingTx = proposal.pairing_tx.replace(/^\"+|\"+$/g, '') // const pairingTx = proposal.pairing_tx.replace(/^\"+|\"+$/g, '')
// const parsedProposal = JSON.parse(proposal[0]) const parsedProposal = JSON.parse(proposal[0]);
// console.log("🚀 ~ Services ~ pairDevice ~ parsedProposal:", parsedProposal) console.log('🚀 ~ Services ~ pairDevice ~ parsedProposal:', parsedProposal);
// const roles = JSON.parse(parsedProposal.roles) const roles = JSON.parse(parsedProposal.roles);
// console.log("🚀 ~ Services ~ pairDevice ~ roles:", roles, Array.isArray(roles), !roles.owner) console.log('🚀 ~ Services ~ pairDevice ~ roles:', roles, Array.isArray(roles), !roles.owner);
// if(Array.isArray(roles) || !roles.owner) return if (Array.isArray(roles) || !roles.owner) return;
// const proposalMembers = roles?.owner?.members const proposalMembers = roles?.owner?.members;
// const isFirstDevice = proposalMembers.some((member: Member) => member.sp_addresses.some(address => address === spAddress)) 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)) const isSecondDevice = proposalMembers.some((member: Member) => member.sp_addresses.some((address) => address === senderAddress));
// console.log("🚀 ~ Services ~ pairDevice ~ proposalMembers:", proposalMembers) console.log('🚀 ~ Services ~ pairDevice ~ proposalMembers:', proposalMembers);
// if(proposalMembers?.length !== 2 || !isFirstDevice || !isSecondDevice) return if (proposalMembers?.length !== 2 || !isFirstDevice || !isSecondDevice) return;
// const pairingTx = parsedProposal?.pairing_tx?.replace(/^\"+|\"+$/g, '') const pairingTx = parsedProposal?.pairing_tx?.replace(/^\"+|\"+$/g, '');
// let txid = '0'.repeat(64) let txid = '0'.repeat(64);
// console.log("🚀 ~ Services ~ pairDevice ~ pairingTx:", pairingTx, `${txid}:4294967295`) console.log('🚀 ~ Services ~ pairDevice ~ pairingTx:', pairingTx, `${txid}:4294967295`);
// const pairing = await service.sdkClient.pair_device(`${txid}:4294967295`, [senderAddress]) const pairing = await service.sdkClient.pair_device(`${txid}:4294967295`, [senderAddress]);
// const device = this.dumpDevice() const device = this.dumpDevice();
// console.log("🚀 ~ Services ~ pairDevice ~ device:", device) console.log('🚀 ~ Services ~ pairDevice ~ device:', device);
// this.saveDevice(device) this.saveDevice(device);
// // await service.sdkClient.pair_device(pairingTx, [senderAddress]) // await service.sdkClient.pair_device(pairingTx, [senderAddress])
// console.log("🚀 ~ Services ~ pairDevice ~ pairing:", pairing) console.log('🚀 ~ Services ~ pairDevice ~ pairing:', pairing);
// // const process = await this.prepareProcessTx(spAddress, senderAddress) // const process = await this.prepareProcessTx(spAddress, senderAddress)
// console.log("🚀 ~ Services ~ pairDevice ~ process:", outpointCommitment, prd, prd.payload) console.log('🚀 ~ Services ~ pairDevice ~ process:', outpointCommitment, prd, prd.payload);
// const prdString = JSON.stringify(prd).trim() const prdString = JSON.stringify(prd).trim();
// console.log("🚀 ~ Services ~ pairDevice ~ prdString:", prdString) console.log('🚀 ~ Services ~ pairDevice ~ prdString:', prdString);
// let tx = await service.sdkClient.response_prd(outpointCommitment, prdString, true) let tx = await service.sdkClient.response_prd(outpointCommitment, prdString, true);
// console.log("🚀 ~ Services ~ pairDevice ~ tx:", tx) console.log('🚀 ~ Services ~ pairDevice ~ tx:', tx);
// if(tx.ciphers_to_send) { if (tx.ciphers_to_send) {
// tx.ciphers_to_send.forEach((cipher: string) => service.websocketConnection?.sendMessage('Cipher', cipher)) tx.ciphers_to_send.forEach((cipher: string) => service.websocketConnection?.sendMessage('Cipher', cipher));
// } }
// this.injectProcessListPage() navigate('process');
// } }
} }
// async saveTxToDb(tx: CachedMessage) { // async saveTxToDb(tx: CachedMessage) {
@ -522,12 +522,6 @@ export default class Services {
console.error('Services ~ Error:', e); console.error('Services ~ Error:', e);
} }
if (currentRoute === 'home') {
this.generateQRCode(spAddress || '');
//Adress to Emoji integration
this.displayEmojis(spAddress);
//Adress to Emoji integration
}
return spAddress; return spAddress;
} }
@ -535,12 +529,6 @@ export default class Services {
try { try {
await this.sdkClient.restore_device(device); await this.sdkClient.restore_device(device);
const spAddress = this.sdkClient.get_address(); 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) { } catch (e) {
console.error(e); console.error(e);
} }