pretiffy code

This commit is contained in:
AnisHADJARAB 2024-11-07 09:46:16 +00:00
parent c2ac42ae54
commit 896de5aca4
12 changed files with 315 additions and 351 deletions

View File

@ -7,7 +7,7 @@ let notifications = [];
export async function unpair() {
const service = await Services.getInstance();
await service.unpairDevice();
navigate('home')
navigate('home');
}
(window as any).unpair = unpair;
@ -27,7 +27,7 @@ function toggleMenu() {
async function getNotifications() {
const service = await Services.getInstance();
notifications = service.getNotifications();
return notifications
return notifications;
}
function openCloseNotifications() {
const notifications = document.querySelector('.notification-board') as HTMLDivElement;
@ -40,7 +40,7 @@ export async function initHeader() {
if (currentRoute === 'home') {
hideSomeFunctionnalities();
} else {
fetchNotifications()
fetchNotifications();
setInterval(fetchNotifications, 2 * 60 * 1000);
}
}
@ -82,8 +82,7 @@ async function setNotification(notifications: INotification[]): Promise<void> {
}
async function fetchNotifications() {
const service = await Services.getInstance()
const service = await Services.getInstance();
const data = service.getNotifications();
setNotification(data)
setNotification(data);
}

View File

@ -1,12 +1,12 @@
import ModalService from "../../services/modal.service";
import ModalService from '../../services/modal.service';
const modalService = await ModalService.getInstance();
export async function confirm() {
modalService.confirmPairing()
modalService.confirmPairing();
}
export async function closeConfirmationModal() {
modalService.closeConfirmationModal()
modalService.closeConfirmationModal();
}
(window as any).confirm = confirm;

View File

@ -17,16 +17,16 @@ export async function initHomePage(): Promise<void> {
document.querySelectorAll('.tab-content').forEach((content) => content.classList.remove('active'));
document.getElementById(tab.getAttribute('data-tab') as string)?.classList.add('active');
})
});
});
const service = await Services.getInstance();
const spAddress = await service.getDeviceAddress()
generateQRCode(spAddress)
displayEmojis(spAddress)
const spAddress = await service.getDeviceAddress();
generateQRCode(spAddress);
displayEmojis(spAddress);
const notifBell = document.getElementById('notification-bell')
if(notifBell) addSubscription(notifBell, 'click', openCloseNotifications)
const notifBell = document.getElementById('notification-bell');
if (notifBell) addSubscription(notifBell, 'click', openCloseNotifications);
var html5QrcodeScanner = new Html5QrcodeScanner('qr-reader', { fps: 10, qrbox: 250 }, undefined);
html5QrcodeScanner.render(onScanSuccess, undefined);

View File

@ -1,3 +1,4 @@
import { interpolate } from '../../utils/html.utils';
import Services from '../../services/service';
let currentPageStyle: HTMLStyleElement | null = null;
@ -13,10 +14,6 @@ export async function initProcessElement(id: string, zone: string) {
}
}
function interpolate(template: string, data: { [key: string]: string }) {
return template.replace(/{{(.*?)}}/g, (_, key) => data[key.trim()]);
}
async function loadPage(data?: any) {
const content = document.getElementById('containerId');
if (content && data) {

View File

@ -7,7 +7,7 @@ export async function init() {
const element = document.querySelector('select') as HTMLSelectElement;
// Create div that wroaps all the elements inside (select, elements selected, search div) to put select inside
const wrapper = document.createElement('div');
if(wrapper) addSubscription(wrapper, 'click', clickOnWrapper)
if (wrapper) addSubscription(wrapper, 'click', clickOnWrapper);
wrapper.classList.add('multi-select-component');
wrapper.classList.add('input-field');
@ -19,15 +19,15 @@ export async function init() {
input.setAttribute('autocomplete', 'off');
input.setAttribute('tabindex', '0');
if (input) {
addSubscription(input, 'keyup', inputChange)
addSubscription(input, 'keydown', deletePressed)
addSubscription(input, 'click', openOptions)
addSubscription(input, 'keyup', inputChange);
addSubscription(input, 'keydown', deletePressed);
addSubscription(input, 'click', openOptions);
}
const dropdown_icon = document.createElement('a');
dropdown_icon.classList.add('dropdown-icon');
if(dropdown_icon) addSubscription(dropdown_icon, 'click', clickDropdown)
if (dropdown_icon) addSubscription(dropdown_icon, 'click', clickDropdown);
const autocomplete_list = document.createElement('ul');
autocomplete_list.classList.add('autocomplete-list');
search_div.appendChild(input);
@ -131,7 +131,7 @@ function createToken(wrapper: HTMLElement, value: any) {
close.setAttribute('data-option', value);
close.setAttribute('data-hits', '0');
close.innerText = 'x';
if(close) addSubscription(close, 'click', removeToken)
if (close) addSubscription(close, 'click', removeToken);
token.appendChild(token_span);
token.appendChild(close);
inputInderline?.appendChild(token);
@ -188,7 +188,7 @@ function populateAutocompleteList(select: HTMLSelectElement, query: string, drop
const li = document.createElement('li');
li.innerText = options_to_show[0];
li.setAttribute('data-value', options_to_show[0]);
if(li) addSubscription(li, 'click', selectOption)
if (li) addSubscription(li, 'click', selectOption);
autocomplete_list?.appendChild(li);
if (query.length == options_to_show[0].length) {
const event = new Event('click');
@ -199,7 +199,7 @@ function populateAutocompleteList(select: HTMLSelectElement, query: string, drop
const li = document.createElement('li');
li.innerText = options_to_show[i];
li.setAttribute('data-value', options_to_show[i]);
if(li) addSubscription(li, 'click', selectOption)
if (li) addSubscription(li, 'click', selectOption);
autocomplete_list?.appendChild(li);
}
} else {
@ -348,7 +348,7 @@ addSubscription(document, 'click', () => {
}
}
}
})
});
async function showSelectedProcess(elem: MouseEvent) {
if (elem) {

View File

@ -12,7 +12,7 @@ const routes: { [key: string]: string } = {
export let currentRoute = '';
export async function navigate(path: string) {
cleanSubscriptions()
cleanSubscriptions();
path = path.replace(/^\//, '');
if (path.includes('/')) {
const parsedPath = path.split('/')[0];
@ -29,7 +29,7 @@ async function handleLocation(path: string) {
if (path.includes('/')) {
path = parsedPath[0];
}
currentRoute = path
currentRoute = path;
const routeHtml = routes[path] || routes['home'];
const content = document.getElementById('containerId');
@ -58,9 +58,9 @@ async function handleLocation(path: string) {
window.onpopstate = async () => {
const services = await Services.getInstance();
if (!services.isPaired()) {
handleLocation('home')
handleLocation('home');
} else {
handleLocation('process')
handleLocation('process');
}
};
@ -108,7 +108,7 @@ async function injectHeader() {
script.src = '/src/components/header/header.ts';
script.type = 'module';
document.head.appendChild(script);
initHeader()
initHeader();
}
}

View File

@ -57,7 +57,7 @@ export default class ModalService {
let members = roles['owner']['members'];
console.log(members);
// We take all the addresses except our own
const service = await Services.getInstance()
const service = await Services.getInstance();
const localAddress = await service.getDeviceAddress();
console.log('🚀 ~ Routing ~ openConfirmationModal ~ pcd:', pcd);
for (const address of members[0]['sp_addresses']) {
@ -65,7 +65,7 @@ export default class ModalService {
this.paired_addresses.push(address);
}
}
await this.injectModal(members)
await this.injectModal(members);
const modal = document.getElementById('modal');
if (modal) modal.style.display = 'flex';
// const newScript = document.createElement('script');

View File

@ -37,7 +37,7 @@ export default class Services {
Services.initializing = (async () => {
const instance = new Services();
await instance.init();
instance.routingInstance = await ModalService.getInstance()
instance.routingInstance = await ModalService.getInstance();
return instance;
})();
}

3
src/utils/html.utils.ts Normal file
View File

@ -0,0 +1,3 @@
export function interpolate(template: string, data: { [key: string]: string }) {
return template.replace(/{{(.*?)}}/g, (_, key) => data[key.trim()]);
}

View File

@ -1,5 +1,5 @@
import Services from "../services/service";
import { addSubscription } from "./subscription.utils";
import Services from '../services/service';
import { addSubscription } from './subscription.utils';
import QRCode from 'qrcode';
//Copy Address
@ -51,8 +51,7 @@ export async function addressToEmoji(text: string): Promise<string> {
.map((byte) => emojiList[byte])
.join('');
return emojis;
};
}
//Get emojis from other device
async function emojisPairingRequest() {
@ -96,7 +95,7 @@ async function emojisPairingRequest() {
} catch (err) {
console.error(err);
}
};
}
// Verify Other address
export function initAddressInput() {
@ -137,7 +136,7 @@ async function emojisPairingRequest() {
okButton.style.display = 'none';
}
}
})
});
if (okButton) {
addSubscription(okButton, 'click', () => {
@ -147,7 +146,7 @@ async function emojisPairingRequest() {
}
async function onOkButtonClick() {
const service = await Services.getInstance()
const service = await Services.getInstance();
const addressInput = (document.getElementById('addressInput') as HTMLInputElement).value;
await service.sendPairingTx(addressInput);
}
@ -167,9 +166,9 @@ export async function generateQRCode(spAddress: string) {
}
const copyBtn = document.getElementById('copyBtn');
if (copyBtn) {
addSubscription(copyBtn, 'click', () => copyToClipboard(currentUrl + '?sp_address=' + spAddress))
addSubscription(copyBtn, 'click', () => copyToClipboard(currentUrl + '?sp_address=' + spAddress));
}
} catch (err) {
console.error(err);
}
};
}

View File

@ -1,7 +1,7 @@
let subscriptions: { element: Element | Document, event: any, eventHandler: EventListenerOrEventListenerObject }[] = [];
let subscriptions: { element: Element | Document; event: any; eventHandler: EventListenerOrEventListenerObject }[] = [];
export function cleanSubscriptions(): void {
console.log("🚀 ~ cleanSubscriptions ~ sub:", subscriptions)
console.log('🚀 ~ cleanSubscriptions ~ sub:', subscriptions);
for (const sub of subscriptions) {
const el = sub.element;
const eventHandler = sub.eventHandler;

View File

@ -3,10 +3,10 @@ import Services from './services/service';
let ws: WebSocket;
let messageQueue: string[] = [];
let services: Services
let services: Services;
export async function initWebsocket(url: string) {
ws = new WebSocket(url);
services = await Services.getInstance()
services = await Services.getInstance();
if (ws !== null) {
ws.onopen = async (event) => {
@ -36,44 +36,14 @@ export async function initWebsocket(url: string) {
try {
const feeRate = 0.0001;
const parsedMessage = JSON.parse(msgData);
// console.log("🚀 ~ WebSocketClient ~ parsedMessage:", parsedMessage)
switch (parsedMessage.flag) {
case 'NewTx':
await services.parseNewTx(parsedMessage.content);
break;
case 'Cipher':
await services.parseCipher(parsedMessage.content);
// device = await services.dumpWallet()
// console.log("🚀 ~ WebSocketClient ~ device:", device)
// await services.saveDevice(device)
break;
}
// By parsing the message, we can link it with existing cached message and return the updated version of the message
// if (res.status === 'FaucetComplete') {
// // we received a faucet tx, there's nothing else to do
// window.alert(`New faucet output\n${res.commited_in}`);
// } else if (res.status === 'TxWaitingCipher') {
// // we received a tx but we don't have the cipher
// console.debug(`received notification in output ${res.commited_in}, waiting for cipher message`);
// } else if (res.status === 'CipherWaitingTx') {
// // we received a cipher but we don't have the key
// console.debug(`received a cipher`);
// } else if (res.status === 'SentWaitingConfirmation') {
// // We are sender and we're waiting for the challenge that will confirm recipient got the transaction and the message
// } else if (res.status === 'MustSpendConfirmation') {
// // we received a challenge for a notification we made
// // that means we can stop rebroadcasting the tx and we must spend the challenge to confirm
// window.alert(`Spending ${res.confirmed_by} to prove our identity`);
// console.debug(`sending confirm message to ${res.recipient}`);
// } else if (res.status === 'ReceivedMustConfirm') {
// // we found a notification and decrypted the cipher
// window.alert(`Received message from ${res.sender}\n${res.plaintext}`);
// // we must spend the commited_in output to sender
// } else if (res.status === 'Complete') {
// window.alert(`Received confirmation that ${res.sender} is the author of message ${res.plaintext}`)
// } else {
// console.debug('Received an unimplemented valid message');
// }
} catch (error) {
console.error('Received an invalid message:', error);
}
@ -102,10 +72,6 @@ export async function initWebsocket(url: string) {
flag: flag,
content: message,
};
// if(flag === 'Cipher') {
// const services = await Services.getInstance();
// services.parseCipher(JSON.stringify(networkMessage))
// }
console.log('Sending message:', JSON.stringify(networkMessage));
ws.send(JSON.stringify(networkMessage));
} else {