add prettify to project

This commit is contained in:
AnisHADJARAB 2024-10-29 12:49:13 +00:00
parent 9e327f6c08
commit 29f09e92b7
13 changed files with 1867 additions and 1754 deletions

5
.prettierignore Normal file
View File

@ -0,0 +1,5 @@
# Add files here to ignore them from prettier formatting
/dist
/coverage
/.nx/cache
.angular

14
.prettierrc Normal file
View File

@ -0,0 +1,14 @@
{
"printWidth": 300,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": true,
"quoteProps": "as-needed",
"trailingComma": "all",
"bracketSpacing": true,
"arrowParens": "always",
"requirePragma": false,
"insertPragma": false,
"endOfLine": "crlf"
}

135
package-lock.json generated
View File

@ -17,11 +17,13 @@
"vite": "^5.4.9", "vite": "^5.4.9",
"vite-plugin-copy": "^0.1.6", "vite-plugin-copy": "^0.1.6",
"vite-plugin-html": "^3.2.2", "vite-plugin-html": "^3.2.2",
"vite-plugin-terminal": "^1.2.0",
"vite-plugin-wasm": "^3.3.0" "vite-plugin-wasm": "^3.3.0"
}, },
"devDependencies": { "devDependencies": {
"copy-webpack-plugin": "^12.0.2", "copy-webpack-plugin": "^12.0.2",
"html-webpack-plugin": "^5.6.0", "html-webpack-plugin": "^5.6.0",
"prettier": "^3.3.3",
"ts-loader": "^9.5.1", "ts-loader": "^9.5.1",
"typescript": "^5.3.3", "typescript": "^5.3.3",
"vite-plugin-static-copy": "^1.0.6", "vite-plugin-static-copy": "^1.0.6",
@ -902,6 +904,56 @@
"node": ">=14" "node": ">=14"
} }
}, },
"node_modules/@polka/url": {
"version": "1.0.0-next.28",
"resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.28.tgz",
"integrity": "sha512-8LduaNlMZGwdZ6qWrKlfa+2M4gahzFkprZiAt2TF8uS0qQgBizKXpXURqvTJ4WtmupWxaLqjRb2UCTe72mu+Aw==",
"license": "MIT"
},
"node_modules/@rollup/plugin-strip": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@rollup/plugin-strip/-/plugin-strip-3.0.4.tgz",
"integrity": "sha512-LDRV49ZaavxUo2YoKKMQjCxzCxugu1rCPQa0lDYBOWLj6vtzBMr8DcoJjsmg+s450RbKbe3qI9ZLaSO+O1oNbg==",
"license": "MIT",
"dependencies": {
"@rollup/pluginutils": "^5.0.1",
"estree-walker": "^2.0.2",
"magic-string": "^0.30.3"
},
"engines": {
"node": ">=14.0.0"
},
"peerDependencies": {
"rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0"
},
"peerDependenciesMeta": {
"rollup": {
"optional": true
}
}
},
"node_modules/@rollup/plugin-strip/node_modules/@rollup/pluginutils": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.1.2.tgz",
"integrity": "sha512-/FIdS3PyZ39bjZlwqFnWqCOVnW7o963LtKMwQOD0NhQqw22gSr2YY1afu3FxRip4ZCZNsD5jq6Aaz6QV3D/Njw==",
"license": "MIT",
"dependencies": {
"@types/estree": "^1.0.0",
"estree-walker": "^2.0.2",
"picomatch": "^2.3.1"
},
"engines": {
"node": ">=14.0.0"
},
"peerDependencies": {
"rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0"
},
"peerDependenciesMeta": {
"rollup": {
"optional": true
}
}
},
"node_modules/@rollup/pluginutils": { "node_modules/@rollup/pluginutils": {
"version": "4.2.1", "version": "4.2.1",
"resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-4.2.1.tgz", "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-4.2.1.tgz",
@ -4136,6 +4188,12 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/kolorist": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/kolorist/-/kolorist-1.8.0.tgz",
"integrity": "sha512-Y+60/zizpJ3HRH8DCss+q95yr6145JXZo46OTpFvDZWLfRCE4qChOyk1b26nMaNpfHHgxagk9dXT5OP0Tfe+dQ==",
"license": "MIT"
},
"node_modules/launch-editor": { "node_modules/launch-editor": {
"version": "2.8.0", "version": "2.8.0",
"resolved": "https://registry.npmjs.org/launch-editor/-/launch-editor-2.8.0.tgz", "resolved": "https://registry.npmjs.org/launch-editor/-/launch-editor-2.8.0.tgz",
@ -4192,7 +4250,6 @@
"version": "0.30.10", "version": "0.30.10",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.10.tgz", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.10.tgz",
"integrity": "sha512-iIRwTIf0QKV3UAnYK4PU8uiEc4SRh5jX0mwpIwETPpHdhVM4f53RSwS/vXvN1JhGX+Cs7B8qIq3d6AH49O5fAQ==", "integrity": "sha512-iIRwTIf0QKV3UAnYK4PU8uiEc4SRh5jX0mwpIwETPpHdhVM4f53RSwS/vXvN1JhGX+Cs7B8qIq3d6AH49O5fAQ==",
"peer": true,
"dependencies": { "dependencies": {
"@jridgewell/sourcemap-codec": "^1.4.15" "@jridgewell/sourcemap-codec": "^1.4.15"
} }
@ -4334,6 +4391,15 @@
"node": ">=16 || 14 >=14.17" "node": ">=16 || 14 >=14.17"
} }
}, },
"node_modules/mrmime": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.0.tgz",
"integrity": "sha512-eu38+hdgojoyq63s+yTpN4XMBdt5l8HhMhc4VKLO9KM5caLIBvUm4thi7fFaxyTmCKeNnXZ5pAlBwCUnhA09uw==",
"license": "MIT",
"engines": {
"node": ">=10"
}
},
"node_modules/ms": { "node_modules/ms": {
"version": "2.1.2", "version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
@ -4739,6 +4805,22 @@
"node": "^10 || ^12 || >=14" "node": "^10 || ^12 || >=14"
} }
}, },
"node_modules/prettier": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.3.3.tgz",
"integrity": "sha512-i2tDNA0O5IrMO757lfrdQZCc2jPNDVntV0m/+4whiDfWaTKfMNgR7Qz0NAeGz/nRqF4m5/6CLzbP4/liHt12Ew==",
"dev": true,
"license": "MIT",
"bin": {
"prettier": "bin/prettier.cjs"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/prettier/prettier?sponsor=1"
}
},
"node_modules/pretty-error": { "node_modules/pretty-error": {
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/pretty-error/-/pretty-error-4.0.0.tgz", "resolved": "https://registry.npmjs.org/pretty-error/-/pretty-error-4.0.0.tgz",
@ -5430,6 +5512,20 @@
"integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",
"dev": true "dev": true
}, },
"node_modules/sirv": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/sirv/-/sirv-2.0.4.tgz",
"integrity": "sha512-94Bdh3cC2PKrbgSOUqTiGPWVZeSiXfKOVZNJniWoqrWrRkB1CJzBU3NEbiTsPcYy1lDsANA/THzS+9WBiy5nfQ==",
"license": "MIT",
"dependencies": {
"@polka/url": "^1.0.0-next.24",
"mrmime": "^2.0.0",
"totalist": "^3.0.0"
},
"engines": {
"node": ">= 10"
}
},
"node_modules/slash": { "node_modules/slash": {
"version": "5.1.0", "version": "5.1.0",
"resolved": "https://registry.npmjs.org/slash/-/slash-5.1.0.tgz", "resolved": "https://registry.npmjs.org/slash/-/slash-5.1.0.tgz",
@ -5808,6 +5904,15 @@
"node": ">=0.6" "node": ">=0.6"
} }
}, },
"node_modules/totalist": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/totalist/-/totalist-3.0.1.tgz",
"integrity": "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/tree-dump": { "node_modules/tree-dump": {
"version": "1.0.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/tree-dump/-/tree-dump-1.0.2.tgz", "resolved": "https://registry.npmjs.org/tree-dump/-/tree-dump-1.0.2.tgz",
@ -5966,6 +6071,12 @@
"node": ">=14.17" "node": ">=14.17"
} }
}, },
"node_modules/ufo": {
"version": "1.5.4",
"resolved": "https://registry.npmjs.org/ufo/-/ufo-1.5.4.tgz",
"integrity": "sha512-UsUk3byDzKd04EyoZ7U4DOlxQaD14JUKQl6/P7wiX4FNvUfm3XL246n9W5AmqwW5RSFJ27NAuM0iLscAOYUiGQ==",
"license": "MIT"
},
"node_modules/undici-types": { "node_modules/undici-types": {
"version": "5.26.5", "version": "5.26.5",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",
@ -6201,6 +6312,28 @@
"node": ">=14.14" "node": ">=14.14"
} }
}, },
"node_modules/vite-plugin-terminal": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/vite-plugin-terminal/-/vite-plugin-terminal-1.2.0.tgz",
"integrity": "sha512-IIw1V+IySth8xlrGmH4U7YmfTp681vTzYpa7b8A3KNCJ2oW1BGPPwW8tSz6BQTvSgbRmrP/9NsBLsfXkN4e8sA==",
"license": "MIT",
"dependencies": {
"@rollup/plugin-strip": "^3.0.2",
"debug": "^4.3.4",
"kolorist": "^1.7.0",
"sirv": "^2.0.2",
"ufo": "^1.1.1"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/sponsors/patak-dev"
},
"peerDependencies": {
"vite": "^2.0.0||^3.0.0||^4.0.0||^5.0.0"
}
},
"node_modules/vite-plugin-wasm": { "node_modules/vite-plugin-wasm": {
"version": "3.3.0", "version": "3.3.0",
"resolved": "https://registry.npmjs.org/vite-plugin-wasm/-/vite-plugin-wasm-3.3.0.tgz", "resolved": "https://registry.npmjs.org/vite-plugin-wasm/-/vite-plugin-wasm-3.3.0.tgz",

View File

@ -8,7 +8,8 @@
"build_wasm": "wasm-pack build --out-dir ../ihm_client/dist/pkg ../sdk_client --target bundler --dev", "build_wasm": "wasm-pack build --out-dir ../ihm_client/dist/pkg ../sdk_client --target bundler --dev",
"start": "vite --host 0.0.0.0", "start": "vite --host 0.0.0.0",
"build": "tsc && vite build", "build": "tsc && vite build",
"deploy": "sudo cp -r dist/* /var/www/html/" "deploy": "sudo cp -r dist/* /var/www/html/",
"prettify": "prettier --config ./.prettierrc --write \"src/**/*{.ts,.html.scss}\""
}, },
"keywords": [], "keywords": [],
"author": "", "author": "",
@ -16,6 +17,7 @@
"devDependencies": { "devDependencies": {
"copy-webpack-plugin": "^12.0.2", "copy-webpack-plugin": "^12.0.2",
"html-webpack-plugin": "^5.6.0", "html-webpack-plugin": "^5.6.0",
"prettier": "^3.3.3",
"ts-loader": "^9.5.1", "ts-loader": "^9.5.1",
"typescript": "^5.3.3", "typescript": "^5.3.3",
"vite-plugin-static-copy": "^1.0.6", "vite-plugin-static-copy": "^1.0.6",

View File

@ -37,4 +37,3 @@
// console.error(error); // console.error(error);
// } // }
// }); // });

View File

@ -4,19 +4,16 @@ export interface INotification {
description: string; description: string;
sendToNotificationPage?: boolean; sendToNotificationPage?: boolean;
path?: string; path?: string;
} }
// Quelles sont les données utiles pour le user ??? // Quelles sont les données utiles pour le user ???
export interface IUser { export interface IUser {
id: string; id: string;
information?: any information?: any;
} }
// Quelles sont les données utiles pour les messages ??? // Quelles sont les données utiles pour les messages ???
export interface IMessage { export interface IMessage {
id: string; id: string;
message: any message: any;
} }

View File

@ -3,7 +3,7 @@ export interface IProcess {
name: string; name: string;
description: string; description: string;
icon?: string; icon?: string;
zoneList: IZone[], zoneList: IZone[];
} }
export interface IZone { export interface IZone {
@ -12,9 +12,9 @@ export interface IZone {
path: string; path: string;
// Est-ce que la zone a besoin d'une icone ? // Est-ce que la zone a besoin d'une icone ?
icon?: string; icon?: string;
} }
export interface INotification { export interface INotification {
id: number; id: number;
title: string; title: string;
description: string; description: string;

View File

@ -1,40 +1,37 @@
import { Html5QrcodeScanner } from "html5-qrcode"; import { Html5QrcodeScanner } from 'html5-qrcode';
import Routing from "../../services/routing.service"; import Routing from '../../services/routing.service';
import Services from "../../services/service"; import Services from '../../services/service';
let resultContainer = document.getElementById('qr-reader-results'); let resultContainer = document.getElementById('qr-reader-results');
let lastResult: any, countResults = 0; let lastResult: any,
countResults = 0;
export function initHomePage(): void { export function initHomePage(): void {
console.log('INIT') console.log('INIT');
document.querySelectorAll('.tab').forEach(tab => { document.querySelectorAll('.tab').forEach((tab) => {
tab.addEventListener('click', () => { tab.addEventListener('click', () => {
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active')); document.querySelectorAll('.tab').forEach((t) => t.classList.remove('active'));
tab.classList.add('active'); tab.classList.add('active');
document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active')); document.querySelectorAll('.tab-content').forEach((content) => content.classList.remove('active'));
document.getElementById(tab.getAttribute('data-tab') as string)?.classList.add('active'); document.getElementById(tab.getAttribute('data-tab') as string)?.classList.add('active');
}); });
}); });
document.getElementById('notification-bell')?.addEventListener('click', openCloseNotifications); document.getElementById('notification-bell')?.addEventListener('click', openCloseNotifications);
var html5QrcodeScanner = new Html5QrcodeScanner( var html5QrcodeScanner = new Html5QrcodeScanner('qr-reader', { fps: 10, qrbox: 250 }, undefined);
"qr-reader", { fps: 10, qrbox: 250 }, undefined); html5QrcodeScanner.render(onScanSuccess, undefined);
html5QrcodeScanner.render(onScanSuccess, undefined);
docReady(() => { docReady(() => {
scanDevice(); scanDevice();
});
});
} }
async function onScanSuccess(decodedText: any, decodedResult: any) { async function onScanSuccess(decodedText: any, decodedResult: any) {
if (lastResult === decodedText) { return; } if (lastResult === decodedText) {
return;
}
lastResult = decodedText; lastResult = decodedText;
++countResults; ++countResults;
// Handle on success condition with the decoded message. // Handle on success condition with the decoded message.
@ -48,7 +45,7 @@ async function onScanSuccess(decodedText: any, decodedResult: any) {
if (spAddress) { if (spAddress) {
html5QrcodeScanner.clear(); html5QrcodeScanner.clear();
const service = await Services.getInstance() const service = await Services.getInstance();
// Call the sendPairingTx function with the extracted sp_address // Call the sendPairingTx function with the extracted sp_address
await service.sendPairingTx(spAddress); await service.sendPairingTx(spAddress);
} else { } else {
@ -63,7 +60,7 @@ async function onScanSuccess(decodedText: any, decodedResult: any) {
} }
export function toggleMenu() { export function toggleMenu() {
let menu = document.getElementById('menu'); let menu = document.getElementById('menu');
if(menu) { if (menu) {
if (menu.style.display === 'block') { if (menu.style.display === 'block') {
menu.style.display = 'none'; menu.style.display = 'none';
} else { } else {
@ -72,17 +69,16 @@ export function toggleMenu() {
} }
} }
//// Modal //// Modal
export async function openModal(myAddress: string, receiverAddress: string) { export async function openModal(myAddress: string, receiverAddress: string) {
const router = await Routing.getInstance(); const router = await Routing.getInstance();
router.openLoginModal(myAddress, receiverAddress) router.openLoginModal(myAddress, receiverAddress);
} }
function openCloseNotifications() {
function openCloseNotifications() { const notifications = document.querySelector('.notification-board') as HTMLDivElement;
const notifications = document.querySelector('.notification-board') as HTMLDivElement notifications.style.display = notifications?.style.display === 'none' ? 'block' : 'none';
notifications.style.display = notifications?.style.display === 'none' ? 'block' : 'none' }
}
// const service = await Services.getInstance() // const service = await Services.getInstance()
// service.setNotification() // service.setNotification()
@ -93,22 +89,19 @@ export function toggleMenu() {
/// Scan QR Code /// Scan QR Code
function docReady(fn: any) { function docReady(fn: any) {
// see if DOM is already available // see if DOM is already available
if (document.readyState === "complete" if (document.readyState === 'complete' || document.readyState === 'interactive') {
|| document.readyState === "interactive") {
// call on next available tick // call on next available tick
setTimeout(fn, 1); setTimeout(fn, 1);
} else { } else {
document.addEventListener("DOMContentLoaded", fn); document.addEventListener('DOMContentLoaded', fn);
} }
} }
function scanDevice() { function scanDevice() {
const scannerImg = document.querySelector('#scanner') as HTMLElement const scannerImg = document.querySelector('#scanner') as HTMLElement;
if(scannerImg) scannerImg.style.display = 'none' if (scannerImg) scannerImg.style.display = 'none';
const scannerQrCode = document.querySelector('.qr-code-scanner') as HTMLElement const scannerQrCode = document.querySelector('.qr-code-scanner') as HTMLElement;
if(scannerQrCode) scannerQrCode.style.display = 'block' if (scannerQrCode) scannerQrCode.style.display = 'block';
} }
(window as any).scanDevice = scanDevice (window as any).scanDevice = scanDevice;

View File

@ -1,40 +1,39 @@
import Services from "../../services/service"; import Services from '../../services/service';
import {IProcess } from "~/models/process.model"; import { IProcess } from '~/models/process.model';
function toggleMenu() { function toggleMenu() {
const menu = document.getElementById("menu") as HTMLDivElement; const menu = document.getElementById('menu') as HTMLDivElement;
if (menu.style.display === "block") { if (menu.style.display === 'block') {
menu.style.display = "none"; menu.style.display = 'none';
} else { } else {
menu.style.display = "block"; menu.style.display = 'block';
} }
} }
// Initialize function, create initial tokens with itens that are already selected by the user // Initialize function, create initial tokens with itens that are already selected by the user
function init(element: HTMLElement) { function init(element: HTMLElement) {
// Create div that wroaps all the elements inside (select, elements selected, search div) to put select inside // Create div that wroaps all the elements inside (select, elements selected, search div) to put select inside
const wrapper = document.createElement("div"); const wrapper = document.createElement('div');
wrapper.addEventListener("click", clickOnWrapper); wrapper.addEventListener('click', clickOnWrapper);
wrapper.classList.add("multi-select-component"); wrapper.classList.add('multi-select-component');
wrapper.classList.add("input-field"); wrapper.classList.add('input-field');
// Create elements of search // Create elements of search
const search_div = document.createElement("div"); const search_div = document.createElement('div');
search_div.classList.add("search-container"); search_div.classList.add('search-container');
const input = document.createElement("input"); const input = document.createElement('input');
input.classList.add("selected-input"); input.classList.add('selected-input');
input.setAttribute("autocomplete", "off"); input.setAttribute('autocomplete', 'off');
input.setAttribute("tabindex", "0"); input.setAttribute('tabindex', '0');
input.addEventListener("keyup", inputChange); input.addEventListener('keyup', inputChange);
input.addEventListener("keydown", deletePressed); input.addEventListener('keydown', deletePressed);
input.addEventListener("click", openOptions); input.addEventListener('click', openOptions);
const dropdown_icon = document.createElement("a"); const dropdown_icon = document.createElement('a');
dropdown_icon.classList.add("dropdown-icon"); dropdown_icon.classList.add('dropdown-icon');
dropdown_icon.addEventListener("click", clickDropdown); dropdown_icon.addEventListener('click', clickDropdown);
const autocomplete_list = document.createElement("ul"); const autocomplete_list = document.createElement('ul');
autocomplete_list.classList.add("autocomplete-list"); autocomplete_list.classList.add('autocomplete-list');
search_div.appendChild(input); search_div.appendChild(input);
search_div.appendChild(autocomplete_list); search_div.appendChild(autocomplete_list);
search_div.appendChild(dropdown_icon); search_div.appendChild(dropdown_icon);
@ -47,43 +46,42 @@ function init(element: HTMLElement) {
addPlaceholder(wrapper); addPlaceholder(wrapper);
// const select = document.querySelector(".select-field"); // const select = document.querySelector(".select-field");
// for (const process of processeList) { // for (const process of processeList) {
// const option = document.createElement("option"); // const option = document.createElement("option");
// option.setAttribute("value", process.name); // option.setAttribute("value", process.name);
// option.innerText = process.name; // option.innerText = process.name;
// select.appendChild(option); // select.appendChild(option);
// } // }
} }
function removePlaceholder(wrapper: HTMLElement) { function removePlaceholder(wrapper: HTMLElement) {
const input_search = wrapper.querySelector(".selected-input"); const input_search = wrapper.querySelector('.selected-input');
input_search?.removeAttribute("placeholder"); input_search?.removeAttribute('placeholder');
} }
function addPlaceholder(wrapper: HTMLElement) { function addPlaceholder(wrapper: HTMLElement) {
const input_search = wrapper.querySelector(".selected-input"); const input_search = wrapper.querySelector('.selected-input');
const tokens = wrapper.querySelectorAll(".selected-wrapper"); const tokens = wrapper.querySelectorAll('.selected-wrapper');
if (!tokens.length && !(document.activeElement === input_search)) if (!tokens.length && !(document.activeElement === input_search)) input_search?.setAttribute('placeholder', '---------');
input_search?.setAttribute("placeholder", "---------");
} }
// Listener of user search // Listener of user search
function inputChange(e: Event) { function inputChange(e: Event) {
const target = e.target as HTMLInputElement const target = e.target as HTMLInputElement;
const wrapper = target?.parentNode?.parentNode; const wrapper = target?.parentNode?.parentNode;
const select = wrapper?.querySelector("select") as HTMLSelectElement; const select = wrapper?.querySelector('select') as HTMLSelectElement;
const dropdown = wrapper?.querySelector(".dropdown-icon"); const dropdown = wrapper?.querySelector('.dropdown-icon');
const input_val = target?.value; const input_val = target?.value;
if (input_val) { if (input_val) {
dropdown?.classList.add("active"); dropdown?.classList.add('active');
populateAutocompleteList(select, input_val.trim()); populateAutocompleteList(select, input_val.trim());
} else { } else {
dropdown?.classList.remove("active"); dropdown?.classList.remove('active');
const event = new Event("click"); const event = new Event('click');
dropdown?.dispatchEvent(event); dropdown?.dispatchEvent(event);
} }
} }
@ -91,11 +89,11 @@ function inputChange(e: Event) {
// Listen for clicks on the wrapper, if click happens focus on the input // Listen for clicks on the wrapper, if click happens focus on the input
function clickOnWrapper(e: Event) { function clickOnWrapper(e: Event) {
const wrapper = e.target as HTMLElement; const wrapper = e.target as HTMLElement;
if (wrapper.tagName == "DIV") { if (wrapper.tagName == 'DIV') {
const input_search = wrapper.querySelector(".selected-input"); const input_search = wrapper.querySelector('.selected-input');
const dropdown = wrapper.querySelector(".dropdown-icon"); const dropdown = wrapper.querySelector('.dropdown-icon');
if (!dropdown?.classList.contains("active")) { if (!dropdown?.classList.contains('active')) {
const event = new Event("click"); const event = new Event('click');
dropdown?.dispatchEvent(event); dropdown?.dispatchEvent(event);
} }
(input_search as HTMLInputElement)?.focus(); (input_search as HTMLInputElement)?.focus();
@ -106,9 +104,9 @@ function clickOnWrapper(e: Event) {
function openOptions(e: Event) { function openOptions(e: Event) {
const input_search = e.target as HTMLElement; const input_search = e.target as HTMLElement;
const wrapper = input_search?.parentElement?.parentElement; const wrapper = input_search?.parentElement?.parentElement;
const dropdown = wrapper?.querySelector(".dropdown-icon"); const dropdown = wrapper?.querySelector('.dropdown-icon');
if (!dropdown?.classList.contains("active")) { if (!dropdown?.classList.contains('active')) {
const event = new Event("click"); const event = new Event('click');
dropdown?.dispatchEvent(event); dropdown?.dispatchEvent(event);
} }
e.stopPropagation(); e.stopPropagation();
@ -116,22 +114,22 @@ function openOptions(e: Event) {
// Function that create a token inside of a wrapper with the given value // Function that create a token inside of a wrapper with the given value
function createToken(wrapper: HTMLElement, value: any) { function createToken(wrapper: HTMLElement, value: any) {
const search = wrapper.querySelector(".search-container"); const search = wrapper.querySelector('.search-container');
const inputInderline = document.querySelector(".selected-processes"); const inputInderline = document.querySelector('.selected-processes');
// Create token wrapper // Create token wrapper
const token = document.createElement("div"); const token = document.createElement('div');
token.classList.add("selected-wrapper"); token.classList.add('selected-wrapper');
const token_span = document.createElement("span"); const token_span = document.createElement('span');
token_span.classList.add("selected-label"); token_span.classList.add('selected-label');
token_span.innerText = value; token_span.innerText = value;
const close = document.createElement("a"); const close = document.createElement('a');
close.classList.add("selected-close"); close.classList.add('selected-close');
close.setAttribute("tabindex", "-1"); close.setAttribute('tabindex', '-1');
close.setAttribute("data-option", value); close.setAttribute('data-option', value);
close.setAttribute("data-hits", '0'); close.setAttribute('data-hits', '0');
close.setAttribute("href", "#"); close.setAttribute('href', '#');
close.innerText = "x"; close.innerText = 'x';
close.addEventListener("click", removeToken); close.addEventListener('click', removeToken);
token.appendChild(token_span); token.appendChild(token_span);
token.appendChild(close); token.appendChild(close);
inputInderline?.appendChild(token); inputInderline?.appendChild(token);
@ -141,16 +139,16 @@ function createToken(wrapper: HTMLElement, value: any) {
function clickDropdown(e: Event) { function clickDropdown(e: Event) {
const dropdown = e.target as HTMLElement; const dropdown = e.target as HTMLElement;
const wrapper = dropdown?.parentNode?.parentNode; const wrapper = dropdown?.parentNode?.parentNode;
const input_search = wrapper?.querySelector(".selected-input") as HTMLInputElement; const input_search = wrapper?.querySelector('.selected-input') as HTMLInputElement;
const select = wrapper?.querySelector("select") as HTMLSelectElement; const select = wrapper?.querySelector('select') as HTMLSelectElement;
dropdown.classList.toggle("active"); dropdown.classList.toggle('active');
if (dropdown.classList.contains("active")) { if (dropdown.classList.contains('active')) {
removePlaceholder(wrapper as HTMLElement); removePlaceholder(wrapper as HTMLElement);
input_search?.focus(); input_search?.focus();
if (!input_search?.value) { if (!input_search?.value) {
populateAutocompleteList(select, "", true); populateAutocompleteList(select, '', true);
} else { } else {
populateAutocompleteList(select, input_search.value); populateAutocompleteList(select, input_search.value);
} }
@ -164,8 +162,8 @@ function clickDropdown(e: Event) {
function clearAutocompleteList(select: HTMLSelectElement) { function clearAutocompleteList(select: HTMLSelectElement) {
const wrapper = select.parentNode; const wrapper = select.parentNode;
const autocomplete_list = wrapper?.querySelector(".autocomplete-list"); const autocomplete_list = wrapper?.querySelector('.autocomplete-list');
if(autocomplete_list) autocomplete_list.innerHTML = ""; if (autocomplete_list) autocomplete_list.innerHTML = '';
} }
// Populate the autocomplete list following a given query from the user // Populate the autocomplete list following a given query from the user
@ -178,33 +176,33 @@ function populateAutocompleteList(select: HTMLSelectElement, query: string, drop
else options_to_show = autocomplete(query, autocomplete_options); else options_to_show = autocomplete(query, autocomplete_options);
const wrapper = select.parentNode; const wrapper = select.parentNode;
const input_search = wrapper?.querySelector(".search-container"); const input_search = wrapper?.querySelector('.search-container');
const autocomplete_list = wrapper?.querySelector(".autocomplete-list"); const autocomplete_list = wrapper?.querySelector('.autocomplete-list');
if(autocomplete_list) autocomplete_list.innerHTML = ""; if (autocomplete_list) autocomplete_list.innerHTML = '';
const result_size = options_to_show.length; const result_size = options_to_show.length;
if (result_size == 1) { if (result_size == 1) {
const li = document.createElement("li"); const li = document.createElement('li');
li.innerText = options_to_show[0]; li.innerText = options_to_show[0];
li.setAttribute("data-value", options_to_show[0]); li.setAttribute('data-value', options_to_show[0]);
li.addEventListener("click", selectOption); li.addEventListener('click', selectOption);
autocomplete_list?.appendChild(li); autocomplete_list?.appendChild(li);
if (query.length == options_to_show[0].length) { if (query.length == options_to_show[0].length) {
const event = new Event("click"); const event = new Event('click');
li.dispatchEvent(event); li.dispatchEvent(event);
} }
} else if (result_size > 1) { } else if (result_size > 1) {
for (let i = 0; i < result_size; i++) { for (let i = 0; i < result_size; i++) {
const li = document.createElement("li"); const li = document.createElement('li');
li.innerText = options_to_show[i]; li.innerText = options_to_show[i];
li.setAttribute("data-value", options_to_show[i]); li.setAttribute('data-value', options_to_show[i]);
li.addEventListener("click", selectOption); li.addEventListener('click', selectOption);
autocomplete_list?.appendChild(li); autocomplete_list?.appendChild(li);
} }
} else { } else {
const li = document.createElement("li"); const li = document.createElement('li');
li.classList.add("not-cursor"); li.classList.add('not-cursor');
li.innerText = "No options found"; li.innerText = 'No options found';
autocomplete_list?.appendChild(li); autocomplete_list?.appendChild(li);
} }
} }
@ -212,15 +210,13 @@ function populateAutocompleteList(select: HTMLSelectElement, query: string, drop
// Listener to autocomplete results when clicked set the selected property in the select option // Listener to autocomplete results when clicked set the selected property in the select option
function selectOption(e: any) { function selectOption(e: any) {
const wrapper = e.target.parentNode.parentNode.parentNode; const wrapper = e.target.parentNode.parentNode.parentNode;
const input_search = wrapper.querySelector(".selected-input"); const input_search = wrapper.querySelector('.selected-input');
const option = wrapper.querySelector( const option = wrapper.querySelector(`select option[value="${e.target.dataset.value}"]`);
`select option[value="${e.target.dataset.value}"]`
);
option.setAttribute("selected", ""); option.setAttribute('selected', '');
createToken(wrapper, e.target.dataset.value); createToken(wrapper, e.target.dataset.value);
if (input_search.value) { if (input_search.value) {
input_search.value = ""; input_search.value = '';
} }
// showSelectedProcess(e.target.dataset.value); // showSelectedProcess(e.target.dataset.value);
@ -228,16 +224,16 @@ function selectOption(e: any) {
input_search.focus(); input_search.focus();
e.target.remove(); e.target.remove();
const autocomplete_list = wrapper.querySelector(".autocomplete-list"); const autocomplete_list = wrapper.querySelector('.autocomplete-list');
if (!autocomplete_list.children.length) { if (!autocomplete_list.children.length) {
const li = document.createElement("li"); const li = document.createElement('li');
li.classList.add("not-cursor"); li.classList.add('not-cursor');
li.innerText = "No options found"; li.innerText = 'No options found';
autocomplete_list.appendChild(li); autocomplete_list.appendChild(li);
} }
const event = new Event("keyup"); const event = new Event('keyup');
input_search.dispatchEvent(event); input_search.dispatchEvent(event);
e.stopPropagation(); e.stopPropagation();
} }
@ -251,9 +247,7 @@ function autocomplete(query: string, options: any) {
let options_return = []; let options_return = [];
for (let i = 0; i < options.length; i++) { for (let i = 0; i < options.length; i++) {
if ( if (query.toLowerCase() === options[i].slice(0, query.length).toLowerCase()) {
query.toLowerCase() === options[i].slice(0, query.length).toLowerCase()
) {
options_return.push(options[i]); options_return.push(options[i]);
} }
} }
@ -263,14 +257,10 @@ function autocomplete(query: string, options: any) {
// Returns the options that are selected by the user and the ones that are not // Returns the options that are selected by the user and the ones that are not
function getOptions(select: HTMLSelectElement) { function getOptions(select: HTMLSelectElement) {
// Select all the options available // Select all the options available
const all_options = Array.from(select.querySelectorAll("option")).map( const all_options = Array.from(select.querySelectorAll('option')).map((el) => el.value);
(el) => el.value
);
// Get the options that are selected from the user // Get the options that are selected from the user
const options_selected = Array.from( const options_selected = Array.from(select.querySelectorAll('option:checked')).map((el: any) => el.value);
select.querySelectorAll("option:checked")
).map((el: any) => el.value);
// Create an autocomplete options array with the options that are not selected by the user // Create an autocomplete options array with the options that are not selected by the user
const autocomplete_options: any[] = []; const autocomplete_options: any[] = [];
@ -291,20 +281,18 @@ function getOptions(select: HTMLSelectElement) {
// Listener for when the user wants to remove a given token. // Listener for when the user wants to remove a given token.
function removeToken(e: Event) { function removeToken(e: Event) {
// Get the value to remove // Get the value to remove
const target = e.target as HTMLSelectElement const target = e.target as HTMLSelectElement;
const value_to_remove = target.dataset.option; const value_to_remove = target.dataset.option;
const wrapper = target.parentNode?.parentNode?.parentNode; const wrapper = target.parentNode?.parentNode?.parentNode;
const input_search = wrapper?.querySelector(".selected-input"); const input_search = wrapper?.querySelector('.selected-input');
const dropdown = wrapper?.querySelector(".dropdown-icon"); const dropdown = wrapper?.querySelector('.dropdown-icon');
// Get the options in the select to be unselected // Get the options in the select to be unselected
const option_to_unselect = wrapper?.querySelector( const option_to_unselect = wrapper?.querySelector(`select option[value="${value_to_remove}"]`);
`select option[value="${value_to_remove}"]` option_to_unselect?.removeAttribute('selected');
);
option_to_unselect?.removeAttribute("selected");
// Remove token attribute // Remove token attribute
(target.parentNode as any)?.remove(); (target.parentNode as any)?.remove();
dropdown?.classList.remove("active"); dropdown?.classList.remove('active');
const process = document.querySelector("#" + target.dataset.option); const process = document.querySelector('#' + target.dataset.option);
process?.remove(); process?.remove();
} }
@ -313,24 +301,24 @@ function deletePressed(e: KeyboardEvent) {
const input_search = e.target as HTMLInputElement; const input_search = e.target as HTMLInputElement;
const wrapper = input_search?.parentNode?.parentNode; const wrapper = input_search?.parentNode?.parentNode;
const key = e.keyCode || e.charCode; const key = e.keyCode || e.charCode;
const tokens = wrapper?.querySelectorAll(".selected-wrapper"); const tokens = wrapper?.querySelectorAll('.selected-wrapper');
if (tokens?.length) { if (tokens?.length) {
const last_token_x = tokens[tokens.length - 1].querySelector("a"); const last_token_x = tokens[tokens.length - 1].querySelector('a');
let hits = +(last_token_x?.dataset?.hits || 0); let hits = +(last_token_x?.dataset?.hits || 0);
if (key == 8 || key == 46) { if (key == 8 || key == 46) {
if (!input_search.value) { if (!input_search.value) {
if (hits > 1) { if (hits > 1) {
// Trigger delete event // Trigger delete event
const event = new Event("click"); const event = new Event('click');
last_token_x?.dispatchEvent(event); last_token_x?.dispatchEvent(event);
} else { } else {
if(last_token_x?.dataset.hits) last_token_x.dataset.hits = '2'; if (last_token_x?.dataset.hits) last_token_x.dataset.hits = '2';
} }
} }
} else { } else {
if(last_token_x?.dataset.hits) last_token_x.dataset.hits = '0'; if (last_token_x?.dataset.hits) last_token_x.dataset.hits = '0';
} }
} }
return true; return true;
@ -345,71 +333,66 @@ function deletePressed(e: KeyboardEvent) {
// } // }
// get select that has the options available // get select that has the options available
const select = document.querySelectorAll("[data-multi-select-plugin]") as NodeListOf<HTMLElement>; const select = document.querySelectorAll('[data-multi-select-plugin]') as NodeListOf<HTMLElement>;
select.forEach((select) => { select.forEach((select) => {
console.log(select); console.log(select);
init(select); init(select);
}); });
// Dismiss on outside click // Dismiss on outside click
document.addEventListener("click", () => { document.addEventListener('click', () => {
// get select that has the options available // get select that has the options available
const select = document.querySelectorAll("[data-multi-select-plugin]"); const select = document.querySelectorAll('[data-multi-select-plugin]');
for (let i = 0; i < select.length; i++) { for (let i = 0; i < select.length; i++) {
if (event) { if (event) {
var isClickInside = select[i].parentElement?.parentElement?.contains( var isClickInside = select[i].parentElement?.parentElement?.contains(event.target as Node);
event.target as Node
);
if (!isClickInside) { if (!isClickInside) {
const wrapper = select[i].parentElement?.parentElement; const wrapper = select[i].parentElement?.parentElement;
const dropdown = wrapper?.querySelector(".dropdown-icon"); const dropdown = wrapper?.querySelector('.dropdown-icon');
const autocomplete_list = wrapper?.querySelector(".autocomplete-list"); const autocomplete_list = wrapper?.querySelector('.autocomplete-list');
//the click was outside the specifiedElement, do something //the click was outside the specifiedElement, do something
dropdown?.classList.remove("active"); dropdown?.classList.remove('active');
if(autocomplete_list) autocomplete_list.innerHTML = ""; if (autocomplete_list) autocomplete_list.innerHTML = '';
addPlaceholder(wrapper as HTMLElement); addPlaceholder(wrapper as HTMLElement);
} }
} }
} }
}); });
export async function unpair() { export async function unpair() {
const service = await Services.getInstance() const service = await Services.getInstance();
await service.unpairDevice() await service.unpairDevice();
} }
(window as any).unpair = unpair; (window as any).unpair = unpair;
async function showSelectedProcess(event: MouseEvent) { async function showSelectedProcess(event: MouseEvent) {
const elem = event.target; const elem = event.target;
if(elem) { if (elem) {
const cardContent = document.querySelector('.card-content');
const cardContent = document.querySelector(".card-content");
const processes = await getProcesses(); const processes = await getProcesses();
console.log("🚀 ~ Services ~ showSelectedProcess ~ processes:", processes) console.log('🚀 ~ Services ~ showSelectedProcess ~ processes:', processes);
const process = processes.find((process: any) => process.name === (elem as any).dataset.value); const process = processes.find((process: any) => process.name === (elem as any).dataset.value);
if (process) { if (process) {
const processDiv = document.createElement("div"); const processDiv = document.createElement('div');
processDiv.className = "process"; processDiv.className = 'process';
processDiv.id = process.name; processDiv.id = process.name;
const titleDiv = document.createElement("div"); const titleDiv = document.createElement('div');
titleDiv.className = "process-title"; titleDiv.className = 'process-title';
titleDiv.innerHTML = `${process.name} : ${process.description}`; titleDiv.innerHTML = `${process.name} : ${process.description}`;
processDiv.appendChild(titleDiv); processDiv.appendChild(titleDiv);
for (const zone of process.zoneList) { for (const zone of process.zoneList) {
const zoneElement = document.createElement("div"); const zoneElement = document.createElement('div');
zoneElement.className = "process-element"; zoneElement.className = 'process-element';
zoneElement.setAttribute('zone-id', zone.id.toString()) zoneElement.setAttribute('zone-id', zone.id.toString());
zoneElement.innerHTML = `Zone ${zone.id} : ${zone.name}`; zoneElement.innerHTML = `Zone ${zone.id} : ${zone.name}`;
const service = await Services.getInstance() const service = await Services.getInstance();
service.addSubscription(zoneElement, 'click', 'goToProcessPage') service.addSubscription(zoneElement, 'click', 'goToProcessPage');
processDiv.appendChild(zoneElement); processDiv.appendChild(zoneElement);
} }
if(cardContent) cardContent.appendChild(processDiv); if (cardContent) cardContent.appendChild(processDiv);
} }
} }
} }
@ -418,59 +401,61 @@ function goToProcessPage(event: MouseEvent) {
const target = event.target as HTMLDivElement; const target = event.target as HTMLDivElement;
const zoneId = target?.getAttribute('zone-id'); const zoneId = target?.getAttribute('zone-id');
const processList = document.querySelectorAll('.process-element'); const processList = document.querySelectorAll('.process-element');
if(processList) { if (processList) {
for(const process of processList) { for (const process of processList) {
process.classList.remove('selected') process.classList.remove('selected');
} }
} }
target.classList.add('selected') target.classList.add('selected');
console.log('=======================> going to process page', zoneId) console.log('=======================> going to process page', zoneId);
} }
async function getProcesses(): Promise<IProcess[]> { async function getProcesses(): Promise<any[]> {
const service = await Services.getInstance() const service = await Services.getInstance();
// const processes = service.getProcesses() // const processes = service.getProcesses()
// console.log("🚀 ~ Services ~ getProcesses ~ processes:", processes) // console.log("🚀 ~ Services ~ getProcesses ~ processes:", processes)
return [ const process = [
{ {
id: 1, title: 'Messaging',
name: "Messaging", description: 'Messagerie chiffrée',
description: "Encrypted messages", html: '<div><input /></div>',
zoneList: [ css: '',
script: '',
zones: ['zone 1', 'zone 2'],
roles: {
owner: {
members: ['dfdsfdfdsf', 'dfdfdfdsfsfdfdsf'],
validation_rules: [
{ {
id: 1, quorum: 1.0,
name: "General", fields: ['description', 'roles', 'session_privkey', 'session_pubkey', 'key_parity'],
path: '/test' min_sig_member: 1.0,
}, },
], ],
}, },
{ },
id: 2,
name: "Storage",
description: "Distributed storage",
zoneList: [
{
id: 1,
name: "Paris",
path: '/test'
}, },
{ {
id: 2, title: 'Database',
name: "Normandy", description: 'Database chiffrée',
path: '/test' html: '<div><input /></div>',
}, css: '',
script: '',
zones: ['zone 1', 'zone 2'],
roles: {
owner: {
members: ['dfdsfdfdsf', 'dfdfdfdsfsfdfdsf'],
validation_rules: [
{ {
id: 3, quorum: 1.0,
name: "New York", fields: ['description', 'roles', 'session_privkey', 'session_pubkey', 'key_parity'],
path: '/test' min_sig_member: 1.0,
},
{
id: 4,
name: "Moscow",
path: '/test'
}, },
], ],
}, },
},
},
]; ];
return process
} }

View File

@ -3,8 +3,8 @@ import { initHomePage } from './pages/home/home';
import Services from './services/service'; import Services from './services/service';
const routes: { [key: string]: string } = { const routes: { [key: string]: string } = {
'home': '/src/pages/home/home.html', home: '/src/pages/home/home.html',
'process': '/src/pages/process/process.html', process: '/src/pages/process/process.html',
}; };
export async function navigate(path: string) { export async function navigate(path: string) {
@ -21,16 +21,15 @@ async function handleLocation(path: string) {
const content = document.getElementById('containerId'); const content = document.getElementById('containerId');
if (content) { if (content) {
const html = await fetch(routeHtml).then(data => data.text()); const html = await fetch(routeHtml).then((data) => data.text());
content.innerHTML = html; content.innerHTML = html;
await new Promise(requestAnimationFrame); await new Promise(requestAnimationFrame);
if(path === "home") { if (path === 'home') {
const { initHomePage } = await import('./pages/home/home'); const { initHomePage } = await import('./pages/home/home');
initHomePage() initHomePage();
} } else if (path === 'process') {
else if (path === "process") {
await import('./pages/process/process'); await import('./pages/process/process');
} }
} }
@ -41,45 +40,43 @@ window.onpopstate = () => handleLocation('home');
async function init(): Promise<boolean> { async function init(): Promise<boolean> {
let isPaired = false; let isPaired = false;
try { try {
const services = await Services.getInstance(); const services = await Services.getInstance();
setTimeout( async () => { setTimeout(async () => {
let device = await services.getDevice() let device = await services.getDevice();
console.log("🚀 ~ setTimeout ~ device:", device) console.log('🚀 ~ setTimeout ~ device:', device);
if(!device) { if (!device) {
device = await services.createNewDevice(); device = await services.createNewDevice();
} else { } else {
await services.restoreDevice(device) await services.restoreDevice(device);
} }
await services.restoreProcesses(); await services.restoreProcesses();
await services.restoreMessages(); await services.restoreMessages();
if (services.isPaired()) { if (services.isPaired()) {
isPaired = true; isPaired = true;
console.log("🚀 ~ setTimeout ~ isPaired:", isPaired) console.log('🚀 ~ setTimeout ~ isPaired:', isPaired);
await navigate('process'); await navigate('process');
return isPaired return isPaired;
} else { } else {
const queryString = window.location.search; const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString) const urlParams = new URLSearchParams(queryString);
const pairingAddress = urlParams.get('sp_address') const pairingAddress = urlParams.get('sp_address');
if(pairingAddress) { if (pairingAddress) {
setTimeout(async () => await services.sendPairingTx(pairingAddress), 2000) setTimeout(async () => await services.sendPairingTx(pairingAddress), 2000);
} }
return isPaired return isPaired;
} }
}, 200); }, 200);
} catch (error) { } catch (error) {
console.error(error); console.error(error);
return isPaired return isPaired;
} }
return isPaired return isPaired;
} }
(async () => { (async () => {
const isPaired = await init() const isPaired = await init();
console.log("🚀 ~ handleLocation ~ isPaired:", isPaired) console.log('🚀 ~ handleLocation ~ isPaired:', isPaired);
await navigate('home'); await navigate('home');
})(); })();

View File

@ -6,7 +6,6 @@ import Services from './service';
import { U32_MAX } from './service'; import { U32_MAX } from './service';
import { navigate } from '../router'; import { navigate } from '../router';
export default class Routing { export default class Routing {
private static instance: Routing; private static instance: Routing;
private sdkClient: any; private sdkClient: any;
@ -25,36 +24,37 @@ export default class Routing {
} }
public async init(): Promise<void> { public async init(): Promise<void> {
this.sdkClient = await import("../../dist/pkg/sdk_client"); this.sdkClient = await import('../../dist/pkg/sdk_client');
} }
public openLoginModal(myAddress: string, receiverAddress: string) { public openLoginModal(myAddress: string, receiverAddress: string) {
const container = document.querySelector('.page-container'); const container = document.querySelector('.page-container');
let html = modalHtml let html = modalHtml;
html = html.replace('{{device1}}', myAddress) html = html.replace('{{device1}}', myAddress);
html = html.replace('{{device2}}', receiverAddress) html = html.replace('{{device2}}', receiverAddress);
if (container) container.innerHTML += html; if (container) container.innerHTML += html;
const modal = document.getElementById('login-modal') const modal = document.getElementById('login-modal');
if (modal) modal.style.display = 'flex'; if (modal) modal.style.display = 'flex';
const newScript = document.createElement('script'); const newScript = document.createElement('script');
newScript.setAttribute('type', 'module');
newScript.setAttribute('type', 'module')
newScript.textContent = modalScript; newScript.textContent = modalScript;
document.head.appendChild(newScript).parentNode?.removeChild(newScript); document.head.appendChild(newScript).parentNode?.removeChild(newScript);
} }
public async openConfirmationModal(pcd: any, outpointCommitment: string) { public async openConfirmationModal(pcd: any, outpointCommitment: string) {
console.log("") console.log('');
let roles = JSON.parse(pcd['roles']);// ['members'][0]; let roles = JSON.parse(pcd['roles']); // ['members'][0];
console.log(roles); console.log(roles);
let members = roles['owner']['members']; let members = roles['owner']['members'];
console.log(members); console.log(members);
// We take all the addresses except our own // We take all the addresses except our own
const local_address = this.sdkClient.get_address(); const local_address = this.sdkClient.get_address();
console.log("🚀 ~ Routing ~ openConfirmationModal ~ pcd:", pcd) console.log('🚀 ~ Routing ~ openConfirmationModal ~ pcd:', pcd);
for (const address of members[0]['sp_addresses']) { for (const address of members[0]['sp_addresses']) {
if (address !== local_address) { this.paired_addresses.push(address) } if (address !== local_address) {
this.paired_addresses.push(address);
}
} }
let html = confirmationModalHtml; let html = confirmationModalHtml;
let services = await Services.getInstance(); let services = await Services.getInstance();
@ -64,10 +64,10 @@ export default class Routing {
const container = document.querySelector('.page-container'); const container = document.querySelector('.page-container');
if (container) container.innerHTML += html; if (container) container.innerHTML += html;
const modal = document.getElementById('modal') const modal = document.getElementById('modal');
if (modal) modal.style.display = 'flex'; if (modal) modal.style.display = 'flex';
const newScript = document.createElement('script'); const newScript = document.createElement('script');
newScript.setAttribute('type', 'module') newScript.setAttribute('type', 'module');
newScript.textContent = confirmationModalScript; newScript.textContent = confirmationModalScript;
document.head.appendChild(newScript).parentNode?.removeChild(newScript); document.head.appendChild(newScript).parentNode?.removeChild(newScript);
@ -79,39 +79,39 @@ export default class Routing {
if (event.target === modal) { if (event.target === modal) {
this.closeConfirmationModal(); this.closeConfirmationModal();
} }
} };
} }
confirmLogin() { confirmLogin() {
console.log('=============> Confirm Login') console.log('=============> Confirm Login');
const loginTx = this.sdkClient.create_login_transaction(1) const loginTx = this.sdkClient.create_login_transaction(1);
this.sdkClient.login('LOGIN', loginTx) this.sdkClient.login('LOGIN', loginTx);
} }
async closeLoginModal() { async closeLoginModal() {
const modal = document.getElementById('login-modal') const modal = document.getElementById('login-modal');
if (modal) modal.style.display = 'none'; if (modal) modal.style.display = 'none';
} }
async confirmPairing() { async confirmPairing() {
const service = await Services.getInstance() const service = await Services.getInstance();
const modal = document.getElementById('modal') const modal = document.getElementById('modal');
// console.log("🚀 ~ Routing ~ confirm ~ prd:", prd) // console.log("🚀 ~ Routing ~ confirm ~ prd:", prd)
if (modal) modal.style.display = 'none'; if (modal) modal.style.display = 'none';
// Just make an empty commitment for now // Just make an empty commitment for now
const emptyTxid = '0'.repeat(64) const emptyTxid = '0'.repeat(64);
const commitmentOutpoint = `${emptyTxid}:${U32_MAX}`; const commitmentOutpoint = `${emptyTxid}:${U32_MAX}`;
// We take the paired device(s) from the contract // We take the paired device(s) from the contract
await this.sdkClient.pair_device(commitmentOutpoint, this.paired_addresses) await this.sdkClient.pair_device(commitmentOutpoint, this.paired_addresses);
this.paired_addresses = [] this.paired_addresses = [];
const newDevice = await service.dumpDevice(); const newDevice = await service.dumpDevice();
await service.saveDevice(newDevice); await service.saveDevice(newDevice);
navigate('process'); navigate('process');
} }
async closeConfirmationModal() { async closeConfirmationModal() {
const service = await Services.getInstance() const service = await Services.getInstance();
await service.unpairDevice() await service.unpairDevice();
const modal = document.getElementById('modal') const modal = document.getElementById('modal');
if (modal) modal.style.display = 'none'; if (modal) modal.style.display = 'none';
} }
} }

View File

@ -7,7 +7,7 @@ import processScript from '../pages/process/process.js?raw';
import { IProcess } from '~/models/process.model'; 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 } from '../../dist/pkg/sdk_client';
import Routing from './routing.service'; import Routing from './routing.service';
@ -26,8 +26,8 @@ export default class Services {
private websocketConnection: WebSocketClient | null = null; private websocketConnection: WebSocketClient | null = null;
private processes: IProcess[] | null = null; private processes: IProcess[] | null = null;
private notifications: INotification[] | null = null; private notifications: INotification[] | null = null;
private subscriptions: {element: Element; event: string; eventHandler: string;}[] = [] ; private subscriptions: { element: Element; event: string; eventHandler: string }[] = [];
private database: any private database: any;
// Private constructor to prevent direct instantiation from outside // Private constructor to prevent direct instantiation from outside
private constructor() {} private constructor() {}
@ -53,7 +53,7 @@ export default class Services {
public async init(): Promise<void> { public async init(): Promise<void> {
this.notifications = this.getNotifications(); this.notifications = this.getNotifications();
this.sdkClient = await import("../../dist/pkg/sdk_client"); this.sdkClient = await import('../../dist/pkg/sdk_client');
this.sdkClient.setup(); this.sdkClient.setup();
await this.addWebsocketConnection(wsurl); await this.addWebsocketConnection(wsurl);
} }
@ -71,41 +71,41 @@ export default class Services {
try { try {
const container = document.getElementById('containerId'); const container = document.getElementById('containerId');
const currentUrl = 'https://' + window.location.host; const currentUrl = 'https://' + window.location.host;
const url = await QRCode.toDataURL(currentUrl + "?sp_address=" + text); const url = await QRCode.toDataURL(currentUrl + '?sp_address=' + text);
const qrCode = container?.querySelector('.qr-code img'); const qrCode = container?.querySelector('.qr-code img');
qrCode?.setAttribute('src', url) qrCode?.setAttribute('src', url);
//Generate Address CopyBtn //Generate Address CopyBtn
const address = container?.querySelector('.sp-address-btn') const address = container?.querySelector('.sp-address-btn');
if (address) { if (address) {
address.textContent = "Copy address"; address.textContent = 'Copy address';
} }
const copyBtn = document.getElementById('copyBtn'); const copyBtn = document.getElementById('copyBtn');
if (copyBtn) { if (copyBtn) {
copyBtn.addEventListener('click', () => this.copyToClipboard(currentUrl + "?sp_address=" + text)); copyBtn.addEventListener('click', () => this.copyToClipboard(currentUrl + '?sp_address=' + text));
} }
} catch (err) { } catch (err) {
console.error(err); console.error(err);
} }
} };
//Copy Address //Copy Address
public async copyToClipboard(fullAddress: string) { public async copyToClipboard(fullAddress: string) {
try { try {
await navigator.clipboard.writeText(fullAddress); await navigator.clipboard.writeText(fullAddress);
alert("Adresse copiée dans le presse-papiers !"); alert('Adresse copiée dans le presse-papiers !');
} catch (err) { } catch (err) {
console.error("Failed to copy the address: ", err); console.error('Failed to copy the address: ', err);
} }
} }
//Generate emojis list //Generate emojis list
public generateEmojiList(): string[] { public generateEmojiList(): string[] {
const emojiRanges = [ const emojiRanges = [
[0x1F600, 0x1F64F], [0x1f600, 0x1f64f],
[0x1F300, 0x1F5FF], [0x1f300, 0x1f5ff],
[0x1F680, 0x1F6FF], [0x1f680, 0x1f6ff],
[0x1F700, 0x1F77F] [0x1f700, 0x1f77f],
]; ];
const emojiList: string[] = []; const emojiList: string[] = [];
@ -134,12 +134,14 @@ export default class Services {
//Hash slice to emojis //Hash slice to emojis
const emojiList = this.generateEmojiList(); const emojiList = this.generateEmojiList();
const emojis = Array.from(bytes).map(byte => emojiList[byte]).join(''); const emojis = Array.from(bytes)
.map((byte) => emojiList[byte])
.join('');
return emojis; return emojis;
} };
//Get emojis from other device //Get emojis from other device
public async emojisPairingRequest () { public async emojisPairingRequest() {
try { try {
const container = document.getElementById('containerId'); const container = document.getElementById('containerId');
@ -155,7 +157,7 @@ export default class Services {
const emojiDisplay = container?.querySelector('.pairing-request'); const emojiDisplay = container?.querySelector('.pairing-request');
if (emojiDisplay) { if (emojiDisplay) {
emojiDisplay.textContent = "(Request from: " +emojis+")"; emojiDisplay.textContent = '(Request from: ' + emojis + ')';
} }
} catch (err) { } catch (err) {
console.error(err); console.error(err);
@ -164,7 +166,7 @@ export default class Services {
// Display address emojis and other device emojis // Display address emojis and other device emojis
private displayEmojis = async (text: string) => { private displayEmojis = async (text: string) => {
console.log("🚀 ~ Services ~ adressToEmoji") console.log('🚀 ~ Services ~ adressToEmoji');
try { try {
const container = document.getElementById('containerId'); const container = document.getElementById('containerId');
const emojis = await this.addressToEmoji(text); const emojis = await this.addressToEmoji(text);
@ -177,11 +179,10 @@ export default class Services {
this.emojisPairingRequest(); this.emojisPairingRequest();
this.initAddressInput(); this.initAddressInput();
} catch (err) { } catch (err) {
console.error(err); console.error(err);
} }
} };
// Verify Other address // Verify Other address
public initAddressInput() { public initAddressInput() {
@ -241,13 +242,13 @@ export default class Services {
try { try {
return this.sdkClient.is_linking(); return this.sdkClient.is_linking();
} catch (e) { } catch (e) {
console.error("isPaired ~ Error:", e); console.error('isPaired ~ Error:', e);
} }
} }
public async unpairDevice(): Promise<void> { public async unpairDevice(): Promise<void> {
const service = await Services.getInstance() const service = await Services.getInstance();
await service.sdkClient.unpair_device() await service.sdkClient.unpair_device();
const newDevice = await this.dumpDevice(); const newDevice = await this.dumpDevice();
await this.saveDevice(newDevice); await this.saveDevice(newDevice);
} }
@ -256,60 +257,50 @@ export default class Services {
const initial_session_privkey = new Uint8Array(32); const initial_session_privkey = new Uint8Array(32);
const initial_session_pubkey = new Uint8Array(32); const initial_session_pubkey = new Uint8Array(32);
const pairingTemplate = { const pairingTemplate = {
"description": "AliceBob", description: 'AliceBob',
"roles": { roles: {
"owner": { owner: {
"members": members: [{ sp_addresses: [myAddress, recipientAddress] }],
[{sp_addresses: [myAddress, recipientAddress]}], validation_rules: [
"validation_rules":
[
{ {
"quorum": 1.0, quorum: 1.0,
"fields": [ fields: ['description', 'roles', 'session_privkey', 'session_pubkey', 'key_parity'],
"description", min_sig_member: 1.0,
"roles",
"session_privkey",
"session_pubkey",
"key_parity"
],
"min_sig_member": 1.0
}
]
}
}, },
"session_privkey": initial_session_privkey, ],
"session_pubkey": initial_session_pubkey, },
"key_parity": true, },
} session_privkey: initial_session_privkey,
session_pubkey: initial_session_pubkey,
key_parity: true,
};
const apiReturn = this.sdkClient.create_update_transaction(undefined, JSON.stringify(pairingTemplate), 1);
const apiReturn = this.sdkClient.create_update_transaction(undefined, JSON.stringify(pairingTemplate), 1) return apiReturn;
return apiReturn
} }
public async sendPairingTx(spAddress: string): Promise<void> { public async sendPairingTx(spAddress: string): Promise<void> {
const localAddress = this.sdkClient.get_address(); const localAddress = this.sdkClient.get_address();
const emptyTxid = '0'.repeat(64) const emptyTxid = '0'.repeat(64);
try { try {
let commitmentOutpoint = `${emptyTxid}:${U32_MAX}`; let commitmentOutpoint = `${emptyTxid}:${U32_MAX}`;
this.sdkClient.pair_device(commitmentOutpoint, [spAddress]) this.sdkClient.pair_device(commitmentOutpoint, [spAddress]);
} catch (e) { } catch (e) {
console.error("Services ~ Error:", e); console.error('Services ~ Error:', e);
return return;
} }
setTimeout( async () => { setTimeout(async () => {
const apiReturn = this.prepareProcessTx(localAddress, spAddress) const apiReturn = this.prepareProcessTx(localAddress, spAddress);
await this.handleApiReturn(apiReturn); await this.handleApiReturn(apiReturn);
}, 1500) }, 1500);
return return;
} }
async resetDevice() { async resetDevice() {
await this.sdkClient.reset_device() await this.sdkClient.reset_device();
} }
async sendNewTxMessage(message: string) { async sendNewTxMessage(message: string) {
@ -317,12 +308,12 @@ export default class Services {
throw new Error('No websocket connection'); throw new Error('No websocket connection');
} }
// console.log("🚀 ~ WebSocketClient ~ this.ws.onopen= ~ newTxMessage:", message) // console.log("🚀 ~ WebSocketClient ~ this.ws.onopen= ~ newTxMessage:", message)
await this.websocketConnection.sendMessage('NewTx', message) await this.websocketConnection.sendMessage('NewTx', message);
} }
async sendCommitMessage(message: string) { async sendCommitMessage(message: string) {
// console.log("🚀 ~ WebSocketClient ~ this.ws.onopen= ~ CommitMessage:", message) // console.log("🚀 ~ WebSocketClient ~ this.ws.onopen= ~ CommitMessage:", message)
await this.websocketConnection?.sendMessage('Commit', message) await this.websocketConnection?.sendMessage('Commit', message);
} }
async sendCipherMessages(ciphers: string[]) { async sendCipherMessages(ciphers: string[]) {
@ -348,8 +339,8 @@ export default class Services {
try { try {
console.log('parsing new cipher'); console.log('parsing new cipher');
const apiReturn = await this.sdkClient.parse_cipher(message, 0.00001); const apiReturn = await this.sdkClient.parse_cipher(message, 0.00001);
console.log("🚀 ~ Services ~ parseCipher ~ apiReturn:", apiReturn); console.log('🚀 ~ Services ~ parseCipher ~ apiReturn:', apiReturn);
await this.handleApiReturn(apiReturn) await this.handleApiReturn(apiReturn);
} catch (e) { } catch (e) {
console.log("Cipher isn't for us"); console.log("Cipher isn't for us");
} }
@ -359,25 +350,25 @@ export default class Services {
async parseNewTx(tx: string) { async parseNewTx(tx: string) {
try { try {
// console.log('==============> sending txxxxxxx parser', tx) // console.log('==============> sending txxxxxxx parser', tx)
const parsedTx = await this.sdkClient.parse_new_tx(tx, 0, 0.0001) const parsedTx = await this.sdkClient.parse_new_tx(tx, 0, 0.0001);
if(parsedTx) { if (parsedTx) {
console.log("🚀 ~ Services ~ parseNewTx ~ parsedTx:", parsedTx) console.log('🚀 ~ Services ~ parseNewTx ~ parsedTx:', parsedTx);
try { try {
await this.handleApiReturn(parsedTx); await this.handleApiReturn(parsedTx);
const newDevice = await this.dumpDevice(); const newDevice = await this.dumpDevice();
await this.saveDevice(newDevice); await this.saveDevice(newDevice);
} catch (e) { } catch (e) {
console.error("Failed to update device with new tx"); console.error('Failed to update device with new tx');
} }
} }
} catch(e) { } catch (e) {
console.trace(e); console.trace(e);
} }
} }
private async handleApiReturn(apiReturn: ApiReturn) { private async handleApiReturn(apiReturn: ApiReturn) {
if (apiReturn.ciphers_to_send && apiReturn.ciphers_to_send.length) { if (apiReturn.ciphers_to_send && apiReturn.ciphers_to_send.length) {
await this.sendCipherMessages(apiReturn.ciphers_to_send) await this.sendCipherMessages(apiReturn.ciphers_to_send);
} }
setTimeout(async () => { setTimeout(async () => {
@ -402,7 +393,7 @@ export default class Services {
} }
} }
if(apiReturn.updated_cached_msg && apiReturn.updated_cached_msg.length) { if (apiReturn.updated_cached_msg && apiReturn.updated_cached_msg.length) {
apiReturn.updated_cached_msg.forEach((msg, index) => { apiReturn.updated_cached_msg.forEach((msg, index) => {
// console.debug(`CachedMessage ${index}:`, msg); // console.debug(`CachedMessage ${index}:`, msg);
// Save the message to local storage // Save the message to local storage
@ -416,13 +407,13 @@ export default class Services {
} }
if (apiReturn.new_tx_to_send && apiReturn.new_tx_to_send.transaction.length != 0) { if (apiReturn.new_tx_to_send && apiReturn.new_tx_to_send.transaction.length != 0) {
await this.sendNewTxMessage(JSON.stringify(apiReturn.new_tx_to_send)) await this.sendNewTxMessage(JSON.stringify(apiReturn.new_tx_to_send));
} }
}, 0) }, 0);
} }
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)
@ -483,8 +474,8 @@ export default class Services {
// } // }
async getAmount(): Promise<BigInt> { async getAmount(): Promise<BigInt> {
const amount = await this.sdkClient.get_available_amount() const amount = await this.sdkClient.get_available_amount();
return amount return amount;
} }
async getDeviceAddress() { async getDeviceAddress() {
@ -492,9 +483,9 @@ export default class Services {
} }
async dumpDevice() { async dumpDevice() {
const device = await this.sdkClient.dump_device() const device = await this.sdkClient.dump_device();
// console.log("🚀 ~ Services ~ dumpDevice ~ device:", device) // console.log("🚀 ~ Services ~ dumpDevice ~ device:", device)
return device return device;
} }
async saveDevice(device: any): Promise<any> { async saveDevice(device: any): Promise<any> {
@ -503,18 +494,18 @@ export default class Services {
} }
async getDevice(): Promise<string | null> { async getDevice(): Promise<string | null> {
return localStorage.getItem('wallet') return localStorage.getItem('wallet');
} }
async dumpWallet() { async dumpWallet() {
const wallet = await this.sdkClient.dump_wallet() const wallet = await this.sdkClient.dump_wallet();
console.log("🚀 ~ Services ~ dumpWallet ~ wallet:", wallet) console.log('🚀 ~ Services ~ dumpWallet ~ wallet:', wallet);
return wallet return wallet;
} }
async createFaucetMessage() { async createFaucetMessage() {
const message = await this.sdkClient.create_faucet_msg() const message = await this.sdkClient.create_faucet_msg();
console.log("🚀 ~ Services ~ createFaucetMessage ~ message:", message) console.log('🚀 ~ Services ~ createFaucetMessage ~ message:', message);
return message; return message;
} }
@ -526,28 +517,28 @@ export default class Services {
async createNewDevice() { async createNewDevice() {
let spAddress = ''; let spAddress = '';
try { try {
spAddress = await this.sdkClient.create_new_device(0, 'regtest') spAddress = await this.sdkClient.create_new_device(0, 'regtest');
const device = await this.dumpDevice() const device = await this.dumpDevice();
console.log("🚀 ~ Services ~ device:", device) console.log('🚀 ~ Services ~ device:', device);
await this.saveDevice(device) await this.saveDevice(device);
} catch (e) { } catch (e) {
console.error("Services ~ Error:", e); console.error('Services ~ Error:', e);
} }
this.generateQRCode(spAddress || '') this.generateQRCode(spAddress || '');
//Adress to Emoji integration //Adress to Emoji integration
this.displayEmojis(spAddress) this.displayEmojis(spAddress);
//Adress to Emoji integration //Adress to Emoji integration
return spAddress; return spAddress;
} }
async restoreDevice(device: string) { async restoreDevice(device: string) {
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();
this.generateQRCode(spAddress || '') this.generateQRCode(spAddress || '');
//Adress to Emoji integration //Adress to Emoji integration
this.displayEmojis(spAddress) this.displayEmojis(spAddress);
//Adress to Emoji integration //Adress to Emoji integration
} catch (e) { } catch (e) {
console.error(e); console.error(e);
@ -557,7 +548,7 @@ export default class Services {
private getProcessesCache(): ProcessesCache { private getProcessesCache(): ProcessesCache {
// Regular expression to match 64-character hexadecimal strings // Regular expression to match 64-character hexadecimal strings
const hexU32KeyRegex: RegExp = /^[0-9a-fA-F]{64}:\d+$/; const hexU32KeyRegex: RegExp = /^[0-9a-fA-F]{64}:\d+$/;
const hexObjects: ProcessesCache = {} const hexObjects: ProcessesCache = {};
// Iterate over all keys in localStorage // Iterate over all keys in localStorage
for (let i = 0; i < localStorage.length; i++) { for (let i = 0; i < localStorage.length; i++) {
@ -615,10 +606,10 @@ export default class Services {
public async restoreProcesses() { public async restoreProcesses() {
const processesCache = this.getProcessesCache(); const processesCache = this.getProcessesCache();
console.log("🚀 ~ Services ~ restoreProcesses ~ processesCache:", processesCache); console.log('🚀 ~ Services ~ restoreProcesses ~ processesCache:', processesCache);
if (processesCache.length == 0) { if (processesCache.length == 0) {
console.debug("🚀 ~ Services ~ restoreProcesses ~ no processes in local storage"); console.debug('🚀 ~ Services ~ restoreProcesses ~ no processes in local storage');
return; return;
} }
@ -631,7 +622,7 @@ export default class Services {
public async restoreMessages() { public async restoreMessages() {
const cachedMessages = this.getCachedMessages(); const cachedMessages = this.getCachedMessages();
console.log("🚀 ~ Services ~ restoreMessages ~ chachedMessages:", cachedMessages); console.log('🚀 ~ Services ~ restoreMessages ~ chachedMessages:', cachedMessages);
if (cachedMessages && cachedMessages.length != 0) { if (cachedMessages && cachedMessages.length != 0) {
try { try {
@ -640,7 +631,6 @@ export default class Services {
console.error('Services ~ restoreMessages ~ Error:', e); console.error('Services ~ restoreMessages ~ Error:', e);
} }
} }
} }
private cleanSubscriptions(): void { private cleanSubscriptions(): void {
@ -653,22 +643,22 @@ export default class Services {
} }
public async setProcessesInSelectElement(processList: any[]) { public async setProcessesInSelectElement(processList: any[]) {
const select = document.querySelector(".select-field"); const select = document.querySelector('.select-field');
if(select) { if (select) {
for (const process of processList) { for (const process of processList) {
const option = document.createElement("option"); const option = document.createElement('option');
option.setAttribute("value", process.name); option.setAttribute('value', process.name);
option.innerText = process.name; option.innerText = process.name;
select.appendChild(option); select.appendChild(option);
} }
} }
const optionList = document.querySelector('.autocomplete-list'); const optionList = document.querySelector('.autocomplete-list');
if(optionList) { if (optionList) {
const observer = new MutationObserver((mutations, observer) => { const observer = new MutationObserver((mutations, observer) => {
const options = optionList.querySelectorAll('li') const options = optionList.querySelectorAll('li');
if(options) { if (options) {
for(const option of options) { for (const option of options) {
this.addSubscription(option, 'click', 'showSelectedProcess') this.addSubscription(option, 'click', 'showSelectedProcess');
} }
} }
}); });
@ -681,11 +671,9 @@ export default class Services {
public async listenToOptionListPopulating(event: Event) { public async listenToOptionListPopulating(event: Event) {
const target = event.target as HTMLUListElement; const target = event.target as HTMLUListElement;
const options = target?.querySelectorAll('li') const options = target?.querySelectorAll('li');
} }
getNotifications(): INotification[] { getNotifications(): INotification[] {
return [ return [
{ {
@ -693,37 +681,37 @@ export default class Services {
title: 'Notif 1', title: 'Notif 1',
description: 'A normal notification', description: 'A normal notification',
sendToNotificationPage: false, sendToNotificationPage: false,
path: '/notif1' path: '/notif1',
}, },
{ {
id: 2, id: 2,
title: 'Notif 2', title: 'Notif 2',
description: 'A normal notification', description: 'A normal notification',
sendToNotificationPage: false, sendToNotificationPage: false,
path: '/notif2' path: '/notif2',
}, },
{ {
id: 3, id: 3,
title: 'Notif 3', title: 'Notif 3',
description: 'A normal notification', description: 'A normal notification',
sendToNotificationPage: false, sendToNotificationPage: false,
path: '/notif3' path: '/notif3',
} },
] ];
} }
async setNotification(): Promise<void> { async setNotification(): Promise<void> {
const badge = document.querySelector('.notification-badge') as HTMLDivElement const badge = document.querySelector('.notification-badge') as HTMLDivElement;
const notifications = this.notifications const notifications = this.notifications;
const noNotifications = document.querySelector('.no-notification') as HTMLDivElement const noNotifications = document.querySelector('.no-notification') as HTMLDivElement;
if(notifications?.length) { if (notifications?.length) {
badge.innerText = notifications.length.toString() badge.innerText = notifications.length.toString();
const notificationBoard = document.querySelector('.notification-board') as HTMLDivElement const notificationBoard = document.querySelector('.notification-board') as HTMLDivElement;
noNotifications.style.display = 'none' noNotifications.style.display = 'none';
for(const notif of notifications) { for (const notif of notifications) {
const notifElement = document.createElement("div"); const notifElement = document.createElement('div');
notifElement.className = "notification-element"; notifElement.className = 'notification-element';
notifElement.setAttribute('notif-id', notif.id.toString()) notifElement.setAttribute('notif-id', notif.id.toString());
notifElement.innerHTML = ` notifElement.innerHTML = `
<div>${notif.title}</div> <div>${notif.title}</div>
<div>${notif.description}</div> <div>${notif.description}</div>
@ -732,8 +720,7 @@ export default class Services {
notificationBoard.appendChild(notifElement); notificationBoard.appendChild(notifElement);
} }
} else { } else {
noNotifications.style.display = 'block' noNotifications.style.display = 'block';
} }
} }
} }

View File

@ -1,15 +1,18 @@
import { AnkFlag, CachedMessage } from "dist/pkg/sdk_client"; import { AnkFlag, CachedMessage } from 'dist/pkg/sdk_client';
import Services from "./services/service"; import Services from './services/service';
// import { AnkFlag, AnkNetworkMsg, CachedMessage } from "../dist/pkg/sdk_client"; // import { AnkFlag, AnkNetworkMsg, CachedMessage } from "../dist/pkg/sdk_client";
class WebSocketClient { class WebSocketClient {
private ws: WebSocket; private ws: WebSocket;
private messageQueue: string[] = []; private messageQueue: string[] = [];
constructor(url: string, private services: Services) { constructor(
url: string,
private services: Services,
) {
this.ws = new WebSocket(url); this.ws = new WebSocket(url);
if(this.ws !== null) { if (this.ws !== null) {
this.ws.onopen = async (event) => { this.ws.onopen = async (event) => {
console.log('WebSocket connection established'); console.log('WebSocket connection established');
@ -36,15 +39,15 @@ class WebSocketClient {
if (typeof msgData === 'string') { if (typeof msgData === 'string') {
try { try {
const feeRate = 0.0001; const feeRate = 0.0001;
const parsedMessage = JSON.parse(msgData) const parsedMessage = JSON.parse(msgData);
// console.log("🚀 ~ WebSocketClient ~ parsedMessage:", parsedMessage) // console.log("🚀 ~ WebSocketClient ~ parsedMessage:", parsedMessage)
const services = await Services.getInstance() const services = await Services.getInstance();
switch(parsedMessage.flag) { switch (parsedMessage.flag) {
case 'NewTx': case 'NewTx':
await services.parseNewTx(parsedMessage.content) await services.parseNewTx(parsedMessage.content);
break; break;
case 'Cipher': case 'Cipher':
await services.parseCipher(parsedMessage.content) await services.parseCipher(parsedMessage.content);
// device = await services.dumpWallet() // device = await services.dumpWallet()
// console.log("🚀 ~ WebSocketClient ~ device:", device) // console.log("🚀 ~ WebSocketClient ~ device:", device)
// await services.saveDevice(device) // await services.saveDevice(device)
@ -93,23 +96,22 @@ class WebSocketClient {
// Listen for when the connection is closed // Listen for when the connection is closed
this.ws.onclose = (event) => { this.ws.onclose = (event) => {
console.log('WebSocket is closed now.'); console.log('WebSocket is closed now.');
};
} }
} }
}
// Method to send messages // Method to send messages
public async sendMessage(flag: AnkFlag, message: string): Promise<void> { public async sendMessage(flag: AnkFlag, message: string): Promise<void> {
if (this.ws.readyState === WebSocket.OPEN) { if (this.ws.readyState === WebSocket.OPEN) {
const networkMessage = { const networkMessage = {
'flag': flag, flag: flag,
'content': message content: message,
} };
// if(flag === 'Cipher') { // if(flag === 'Cipher') {
// const services = await Services.getInstance(); // const services = await Services.getInstance();
// services.parseCipher(JSON.stringify(networkMessage)) // services.parseCipher(JSON.stringify(networkMessage))
// } // }
console.log("Sending message:", JSON.stringify(networkMessage)); console.log('Sending message:', JSON.stringify(networkMessage));
this.ws.send(JSON.stringify(networkMessage)); this.ws.send(JSON.stringify(networkMessage));
} else { } else {
console.error('WebSocket is not open. ReadyState:', this.ws.readyState); console.error('WebSocket is not open. ReadyState:', this.ws.readyState);
@ -123,8 +125,7 @@ class WebSocketClient {
public sendNormalMessage(message: string) { public sendNormalMessage(message: string) {
this.ws.send(message); this.ws.send(message);
console.log("Sending message:", JSON.stringify(message)); console.log('Sending message:', JSON.stringify(message));
} }
// Method to close the WebSocket connection // Method to close the WebSocket connection