diff --git a/src/main.ts b/src/main.ts index b0f47a4..ed8509b 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,20 +1,20 @@ import { SignatureComponent } from './pages/signature/signature-component'; import { SignatureElement } from './pages/signature/signature'; -/*import { ChatComponent } from './pages/chat/chat-component'; -import { ChatElement } from './pages/chat/chat';*/ -import { AccountComponent } from './pages/account/account-component'; -import { AccountElement } from './pages/account/account'; +// import { ChatComponent } from './pages/chat/chat-component'; +// import { ChatElement } from './pages/chat/chat'; +// import { AccountComponent } from './pages/account/account-component'; +// import { AccountElement } from './pages/account/account'; -export { SignatureComponent, SignatureElement, AccountComponent, AccountElement }; +export { SignatureComponent, SignatureElement }; declare global { interface HTMLElementTagNameMap { 'signature-component': SignatureComponent; 'signature-element': SignatureElement; - /*'chat-component': ChatComponent; - 'chat-element': ChatElement;*/ - 'account-component': AccountComponent; - 'account-element': AccountElement; + // 'chat-component': ChatComponent; + // 'chat-element': ChatElement; + // 'account-component': AccountComponent; + // 'account-element': AccountElement; } } @@ -25,6 +25,6 @@ if ((import.meta as any).env.VITE_IS_INDEPENDANT_LIB) { customElements.define('signature-element', SignatureElement); /*customElements.define('chat-component', ChatComponent); customElements.define('chat-element', ChatElement);*/ - customElements.define('account-component', AccountComponent); - customElements.define('account-element', AccountElement); + // customElements.define('account-component', AccountComponent); + // customElements.define('account-element', AccountElement); } diff --git a/src/pages/account/account-component.ts b/src/pages/account/account-component.ts index db8f193..bd235b0 100644 --- a/src/pages/account/account-component.ts +++ b/src/pages/account/account-component.ts @@ -1,62 +1,62 @@ -import { AccountElement } from './account'; -import accountCss from '../../../public/style/account.css?raw'; -import Services from '../../services/service.js'; +// import { AccountElement } from './account'; +// import accountCss from '../../../style/account.css?raw'; +// import Services from '../../services/service.js'; -class AccountComponent extends HTMLElement { - _callback: any; - accountElement: AccountElement | null = null; +// class AccountComponent extends HTMLElement { +// _callback: any; +// accountElement: AccountElement | null = null; - constructor() { - super(); - console.log('INIT'); - this.attachShadow({ mode: 'open' }); +// constructor() { +// super(); +// console.log('INIT'); +// this.attachShadow({ mode: 'open' }); - this.accountElement = this.shadowRoot?.querySelector('account-element') || null; - } +// this.accountElement = this.shadowRoot?.querySelector('account-element') || null; +// } - connectedCallback() { - console.log('CALLBACKs'); - this.render(); - this.fetchData(); +// connectedCallback() { +// console.log('CALLBACKs'); +// this.render(); +// this.fetchData(); - if (!customElements.get('account-element')) { - customElements.define('account-element', AccountElement); - } - } +// if (!customElements.get('account-element')) { +// customElements.define('account-element', AccountElement); +// } +// } - async fetchData() { - if ((import.meta as any).env.VITE_IS_INDEPENDANT_LIB === false) { - const data = await (window as any).myService?.getProcesses(); - } else { - const service = await Services.getInstance(); - const data = await service.getProcesses(); - } - } +// async fetchData() { +// if ((import.meta as any).env.VITE_IS_INDEPENDANT_LIB === false) { +// const data = await (window as any).myService?.getProcesses(); +// } else { +// const service = await Services.getInstance(); +// const data = await service.getProcesses(); +// } +// } - set callback(fn) { - if (typeof fn === 'function') { - this._callback = fn; - } else { - console.error('Callback is not a function'); - } - } +// set callback(fn) { +// if (typeof fn === 'function') { +// this._callback = fn; +// } else { +// console.error('Callback is not a function'); +// } +// } - get callback() { - return this._callback; - } +// get callback() { +// return this._callback; +// } - render() { - if (this.shadowRoot && !this.shadowRoot.querySelector('account-element')) { - const style = document.createElement('style'); - style.textContent = accountCss; +// render() { +// if (this.shadowRoot && !this.shadowRoot.querySelector('account-element')) { +// const style = document.createElement('style'); +// style.textContent = accountCss; - const accountElement = document.createElement('account-element'); +// const accountElement = document.createElement('account-element'); - this.shadowRoot.appendChild(style); - this.shadowRoot.appendChild(accountElement); - } - } -} +// this.shadowRoot.appendChild(style); +// this.shadowRoot.appendChild(accountElement); +// } +// } +// } -export { AccountComponent }; -customElements.define('account-component', AccountComponent); +// export { AccountComponent }; +// customElements.define('account-component', AccountComponent); diff --git a/src/pages/account/account.html b/src/pages/account/account.html index 654be9a..1b60224 100755 --- a/src/pages/account/account.html +++ b/src/pages/account/account.html @@ -1,4 +1,4 @@ - + diff --git a/src/pages/account/account.ts b/src/pages/account/account.ts index 3e05daa..687ab7a 100755 --- a/src/pages/account/account.ts +++ b/src/pages/account/account.ts @@ -1,1587 +1,1587 @@ -declare global { - interface Window { - initAccount: () => void; - showContractPopup: (contractId: string) => void; - showPairing: () => Promise; - showWallet: () => void; - showData: () => void; - addWalletRow: () => void; - confirmWalletRow: () => void; - cancelWalletRow: () => void; - openAvatarPopup: () => void; - closeAvatarPopup: () => void; - editDeviceName: (cell: HTMLTableCellElement) => void; - showNotifications: (processName: string) => void; - closeNotificationPopup: (event: Event) => void; - markAsRead: (processName: string, messageId: number, element: HTMLElement) => void; - exportRecovery: () => void; - confirmDeleteAccount: () => void; - deleteAccount: () => void; - updateNavbarBanner: (bannerUrl: string) => void; - saveBannerToLocalStorage: (bannerUrl: string) => void; - loadSavedBanner: () => void; - cancelAddRowPairing: () => void; - saveName: (cell: HTMLElement, input: HTMLInputElement) => void; - showProcessNotifications: (processName: string) => void; - handleLogout: () => void; - initializeEventListeners: () => void; - showProcess: () => void; - showProcessCreation: () => void; - showDocumentValidation: () => void; - updateNavbarName: (name: string) => void; - updateNavbarLastName: (lastName: string) => void; - showAlert: (title: string, text?: string, icon?: string) => void; - addRowPairing: () => void; - confirmRowPairing: () => void; - cancelRowPairing: () => void; - deleteRowPairing: (button: HTMLButtonElement) => void; - generateRecoveryWords: () => string[]; - exportUserData: () => void; - updateActionButtons: () => void; - showQRCodeModal: (pairingId: string) => void; - } -} +// declare global { +// interface Window { +// initAccount: () => void; +// showContractPopup: (contractId: string) => void; +// showPairing: () => Promise; +// showWallet: () => void; +// showData: () => void; +// addWalletRow: () => void; +// confirmWalletRow: () => void; +// cancelWalletRow: () => void; +// openAvatarPopup: () => void; +// closeAvatarPopup: () => void; +// editDeviceName: (cell: HTMLTableCellElement) => void; +// showNotifications: (processName: string) => void; +// closeNotificationPopup: (event: Event) => void; +// markAsRead: (processName: string, messageId: number, element: HTMLElement) => void; +// exportRecovery: () => void; +// confirmDeleteAccount: () => void; +// deleteAccount: () => void; +// updateNavbarBanner: (bannerUrl: string) => void; +// saveBannerToLocalStorage: (bannerUrl: string) => void; +// loadSavedBanner: () => void; +// cancelAddRowPairing: () => void; +// saveName: (cell: HTMLElement, input: HTMLInputElement) => void; +// showProcessNotifications: (processName: string) => void; +// handleLogout: () => void; +// initializeEventListeners: () => void; +// showProcess: () => void; +// showProcessCreation: () => void; +// showDocumentValidation: () => void; +// updateNavbarName: (name: string) => void; +// updateNavbarLastName: (lastName: string) => void; +// showAlert: (title: string, text?: string, icon?: string) => void; +// addRowPairing: () => void; +// confirmRowPairing: () => void; +// cancelRowPairing: () => void; +// deleteRowPairing: (button: HTMLButtonElement) => void; +// generateRecoveryWords: () => string[]; +// exportUserData: () => void; +// updateActionButtons: () => void; +// showQRCodeModal: (pairingId: string) => void; +// } +// } -import Swal from 'sweetalert2'; -import { STORAGE_KEYS, defaultRows, mockProcessRows, mockNotifications, notificationMessages, mockDataRows, mockContracts, ALLOWED_ROLES } from '../../mocks/mock-account/constAccountMock'; -import { Row, WalletRow, DataRow, Notification, Contract, NotificationMessage } from '../../mocks/mock-account/interfacesAccountMock'; -import { addressToEmoji } from '../../utils/sp-address.utils'; -import { getCorrectDOM } from '../../utils/document.utils'; -import accountStyle from '../../../public/style/account.css?inline'; -import Services from '../../services/service'; -import { getProcessCreation } from './process-creation'; -import { getDocumentValidation } from './document-validation'; -import { createProcessTab } from './process'; +// import Swal from 'sweetalert2'; +// import { STORAGE_KEYS, defaultRows, mockProcessRows, mockNotifications, notificationMessages, mockDataRows, mockContracts, ALLOWED_ROLES } from '../../mocks/mock-account/constAccountMock'; +// import { Row, WalletRow, DataRow, Notification, Contract, NotificationMessage } from '../../mocks/mock-account/interfacesAccountMock'; +// import { addressToEmoji } from '../../utils/sp-address.utils'; +// import { getCorrectDOM } from '../../utils/document.utils'; +// import accountStyle from '../../../public/style/account.css?inline'; +// import Services from '../../services/service'; +// import { getProcessCreation } from './process-creation'; +// import { getDocumentValidation } from './document-validation'; +// import { createProcessTab } from './process'; -let isAddingRow = false; -let currentRow: HTMLTableRowElement | null = null; -let currentMode: keyof typeof STORAGE_KEYS = 'pairing'; +// let isAddingRow = false; +// let currentRow: HTMLTableRowElement | null = null; +// let currentMode: keyof typeof STORAGE_KEYS = 'pairing'; -interface Process { - states: Array<{ - committed_in: string; - keys: {}; - pcd_commitment: { - counter: string; - }; - public_data: { - memberPublicName?: string; - }; - roles: { - pairing?: {}; - }; - state_id: string; - validation_tokens: Array; - }>; -} +// interface Process { +// states: Array<{ +// committed_in: string; +// keys: {}; +// pcd_commitment: { +// counter: string; +// }; +// public_data: { +// memberPublicName?: string; +// }; +// roles: { +// pairing?: {}; +// }; +// state_id: string; +// validation_tokens: Array; +// }>; +// } -class AccountElement extends HTMLElement { - private dom: Node; +// class AccountElement extends HTMLElement { +// private dom: Node; - constructor() { - super(); - this.attachShadow({ mode: 'open' }); - this.dom = getCorrectDOM('account-element'); +// constructor() { +// super(); +// this.attachShadow({ mode: 'open' }); +// this.dom = getCorrectDOM('account-element'); - // Ajouter Font Awesome - const fontAwesome = document.createElement('link'); - fontAwesome.rel = 'stylesheet'; - fontAwesome.href = 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css'; - this.shadowRoot!.appendChild(fontAwesome); +// // Ajouter Font Awesome +// const fontAwesome = document.createElement('link'); +// fontAwesome.rel = 'stylesheet'; +// fontAwesome.href = 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css'; +// this.shadowRoot!.appendChild(fontAwesome); - const style = document.createElement('style'); - style.textContent = accountStyle; - this.shadowRoot!.appendChild(style); +// const style = document.createElement('style'); +// style.textContent = accountStyle; +// this.shadowRoot!.appendChild(style); - this.shadowRoot!.innerHTML = ` +// this.shadowRoot!.innerHTML = ` - - - +// +// +// - -
- -
-
    - -
    -
    - Banner -
    -
    - Avatar - -
    -
    +// +//
    +// +//
    +//
      +// +//
      +//
      +// Banner +//
      +//
      +// Avatar +// +//
      +//
      - - -
    -
      Pairing 🔗
    - -
      Process ⚙️
    -
      Process Creation
    -
      Document Validation
    - -
    +//
+//
    Pairing 🔗
+// +//
    Process ⚙️
+//
    Process Creation
+//
    Document Validation
+// +//
- -
-
-
- -
-
-
- -
-
-
- `; +// +//
+//
+//
+// +//
+//
+//
+// +//
+//
+// +// `; - window.showPairing = () => this.showPairing(); - window.showWallet = () => this.showWallet(); - window.showProcess = () => this.showProcess(); - window.showProcessCreation = () => this.showProcessCreation(); - window.showDocumentValidation = () => this.showDocumentValidation(); - window.showData = () => this.showData(); - window.addWalletRow = () => this.addWalletRow(); - window.confirmWalletRow = () => this.confirmWalletRow(); - window.cancelWalletRow = () => this.cancelWalletRow(); - window.editDeviceName = (cell: HTMLTableCellElement) => this.editDeviceName(cell); - window.showProcessNotifications = (processName: string) => this.showProcessNotifications(processName); - window.handleLogout = () => this.handleLogout(); - window.confirmDeleteAccount = () => this.confirmDeleteAccount(); - window.showContractPopup = (contractId: string) => this.showContractPopup(contractId); - window.addRowPairing = () => this.addRowPairing(); - window.deleteRowPairing = (button: HTMLButtonElement) => this.deleteRowPairing(button); - window.confirmRowPairing = () => this.confirmRowPairing(); - window.cancelRowPairing = () => this.cancelRowPairing(); - window.updateNavbarBanner = (bannerUrl: string) => this.updateNavbarBanner(bannerUrl); - window.saveBannerToLocalStorage = (bannerUrl: string) => this.saveBannerToLocalStorage(bannerUrl); - window.loadSavedBanner = () => this.loadSavedBanner(); - window.closeNotificationPopup = (event: Event) => this.closeNotificationPopup(event); - window.markAsRead = (processName: string, messageId: number, element: HTMLElement) => this.markAsRead(processName, messageId, element); - window.exportRecovery = () => this.exportRecovery(); - window.generateRecoveryWords = () => this.generateRecoveryWords(); - window.exportUserData = () => this.exportUserData(); - window.updateActionButtons = () => this.updateActionButtons(); - window.openAvatarPopup = () => this.openAvatarPopup(); - window.closeAvatarPopup = () => this.closeAvatarPopup(); - window.showQRCodeModal = (pairingId: string) => this.showQRCodeModal(pairingId); +// window.showPairing = () => this.showPairing(); +// window.showWallet = () => this.showWallet(); +// window.showProcess = () => this.showProcess(); +// window.showProcessCreation = () => this.showProcessCreation(); +// window.showDocumentValidation = () => this.showDocumentValidation(); +// window.showData = () => this.showData(); +// window.addWalletRow = () => this.addWalletRow(); +// window.confirmWalletRow = () => this.confirmWalletRow(); +// window.cancelWalletRow = () => this.cancelWalletRow(); +// window.editDeviceName = (cell: HTMLTableCellElement) => this.editDeviceName(cell); +// window.showProcessNotifications = (processName: string) => this.showProcessNotifications(processName); +// window.handleLogout = () => this.handleLogout(); +// window.confirmDeleteAccount = () => this.confirmDeleteAccount(); +// window.showContractPopup = (contractId: string) => this.showContractPopup(contractId); +// window.addRowPairing = () => this.addRowPairing(); +// window.deleteRowPairing = (button: HTMLButtonElement) => this.deleteRowPairing(button); +// window.confirmRowPairing = () => this.confirmRowPairing(); +// window.cancelRowPairing = () => this.cancelRowPairing(); +// window.updateNavbarBanner = (bannerUrl: string) => this.updateNavbarBanner(bannerUrl); +// window.saveBannerToLocalStorage = (bannerUrl: string) => this.saveBannerToLocalStorage(bannerUrl); +// window.loadSavedBanner = () => this.loadSavedBanner(); +// window.closeNotificationPopup = (event: Event) => this.closeNotificationPopup(event); +// window.markAsRead = (processName: string, messageId: number, element: HTMLElement) => this.markAsRead(processName, messageId, element); +// window.exportRecovery = () => this.exportRecovery(); +// window.generateRecoveryWords = () => this.generateRecoveryWords(); +// window.exportUserData = () => this.exportUserData(); +// window.updateActionButtons = () => this.updateActionButtons(); +// window.openAvatarPopup = () => this.openAvatarPopup(); +// window.closeAvatarPopup = () => this.closeAvatarPopup(); +// window.showQRCodeModal = (pairingId: string) => this.showQRCodeModal(pairingId); - if (!localStorage.getItem('rows')) { - localStorage.setItem('rows', JSON.stringify(defaultRows)); - } - } +// if (!localStorage.getItem('rows')) { +// localStorage.setItem('rows', JSON.stringify(defaultRows)); +// } +// } - connectedCallback() { - this.initializeEventListeners(); - this.loadSavedBanner(); - this.loadUserInfo(); +// connectedCallback() { +// this.initializeEventListeners(); +// this.loadSavedBanner(); +// this.loadUserInfo(); - const savedAvatar = localStorage.getItem('userAvatar'); - const savedBanner = localStorage.getItem('userBanner'); - const savedName = localStorage.getItem('userName'); - const savedLastName = localStorage.getItem('userLastName'); +// const savedAvatar = localStorage.getItem('userAvatar'); +// const savedBanner = localStorage.getItem('userBanner'); +// const savedName = localStorage.getItem('userName'); +// const savedLastName = localStorage.getItem('userLastName'); - if (savedAvatar) { - const navAvatar = this.shadowRoot?.querySelector('.avatar') as HTMLImageElement; - if (navAvatar) navAvatar.src = savedAvatar; - } +// if (savedAvatar) { +// const navAvatar = this.shadowRoot?.querySelector('.avatar') as HTMLImageElement; +// if (navAvatar) navAvatar.src = savedAvatar; +// } - if (savedBanner) { - const navBanner = this.shadowRoot?.querySelector('.banner-image') as HTMLImageElement; - if (navBanner) navBanner.src = savedBanner; - } +// if (savedBanner) { +// const navBanner = this.shadowRoot?.querySelector('.banner-image') as HTMLImageElement; +// if (navBanner) navBanner.src = savedBanner; +// } - if (savedName) { - this.updateNavbarName(savedName); - } - if (savedLastName) { - this.updateNavbarLastName(savedLastName); - } - } +// if (savedName) { +// this.updateNavbarName(savedName); +// } +// if (savedLastName) { +// this.updateNavbarLastName(savedLastName); +// } +// } - private showAlert(message: string): void { - // Créer la popup si elle n'existe pas - let alertPopup = this.shadowRoot?.querySelector('.alert-popup'); - if (!alertPopup) { - alertPopup = document.createElement('div'); - alertPopup.className = 'alert-popup'; - this.shadowRoot?.appendChild(alertPopup); - } +// private showAlert(message: string): void { +// // Créer la popup si elle n'existe pas +// let alertPopup = this.shadowRoot?.querySelector('.alert-popup'); +// if (!alertPopup) { +// alertPopup = document.createElement('div'); +// alertPopup.className = 'alert-popup'; +// this.shadowRoot?.appendChild(alertPopup); +// } - // Définir le message et afficher la popup - alertPopup.textContent = message; - (alertPopup as HTMLElement).style.display = 'block'; +// // Définir le message et afficher la popup +// alertPopup.textContent = message; +// (alertPopup as HTMLElement).style.display = 'block'; - // Cacher la popup après 3 secondes - setTimeout(() => { - (alertPopup as HTMLElement).style.display = 'none'; - }, 3000); - } +// // Cacher la popup après 3 secondes +// setTimeout(() => { +// (alertPopup as HTMLElement).style.display = 'none'; +// }, 3000); +// } - // Fonctions de gestion des comptes et de l'interface utilisateur - private confirmDeleteAccount(): void { - const modal = document.createElement('div'); - modal.className = 'confirm-delete-modal'; - modal.innerHTML = ` -

Delete Account

-

Are you sure you want to delete your account? This action cannot be undone.

-
- - -
- `; +// // Fonctions de gestion des comptes et de l'interface utilisateur +// private confirmDeleteAccount(): void { +// const modal = document.createElement('div'); +// modal.className = 'confirm-delete-modal'; +// modal.innerHTML = ` +//

Delete Account

+//

Are you sure you want to delete your account? This action cannot be undone.

+//
+// +// +//
+// `; - this.shadowRoot?.appendChild(modal); - modal.style.display = 'block'; +// this.shadowRoot?.appendChild(modal); +// modal.style.display = 'block'; - const cancelBtn = modal.querySelector('.cancel-btn'); - const confirmBtn = modal.querySelector('.confirm-btn'); +// const cancelBtn = modal.querySelector('.cancel-btn'); +// const confirmBtn = modal.querySelector('.confirm-btn'); - cancelBtn?.addEventListener('click', () => { - modal.remove(); - }); +// cancelBtn?.addEventListener('click', () => { +// modal.remove(); +// }); - confirmBtn?.addEventListener('click', () => { - this.deleteAccount(); - modal.remove(); - }); -} +// confirmBtn?.addEventListener('click', () => { +// this.deleteAccount(); +// modal.remove(); +// }); +// } -private deleteAccount(): void { - localStorage.clear(); - window.location.href = '/login.html'; -} +// private deleteAccount(): void { +// localStorage.clear(); +// window.location.href = '/login.html'; +// } -private updateNavbarBanner(imageUrl: string): void { - const navbarSection = this.shadowRoot?.querySelector('.nav-wrapper .avatar-section'); - if (!navbarSection) return; +// private updateNavbarBanner(imageUrl: string): void { +// const navbarSection = this.shadowRoot?.querySelector('.nav-wrapper .avatar-section'); +// if (!navbarSection) return; - let bannerImg = navbarSection.querySelector('.banner-image'); +// let bannerImg = navbarSection.querySelector('.banner-image'); - if (!bannerImg) { - bannerImg = document.createElement('img'); - bannerImg.className = 'banner-image'; - navbarSection.insertBefore(bannerImg, navbarSection.firstChild); - } +// if (!bannerImg) { +// bannerImg = document.createElement('img'); +// bannerImg.className = 'banner-image'; +// navbarSection.insertBefore(bannerImg, navbarSection.firstChild); +// } - bannerImg.src = imageUrl; -} +// bannerImg.src = imageUrl; +// } -private saveBannerToLocalStorage(dataUrl: string): void { - localStorage.setItem('userBanner', dataUrl); -} +// private saveBannerToLocalStorage(dataUrl: string): void { +// localStorage.setItem('userBanner', dataUrl); +// } -private loadSavedBanner(): void { - const savedBanner = localStorage.getItem('userBanner'); - if (savedBanner) { - const bannerImg = this.shadowRoot?.getElementById('popup-banner-img') as HTMLImageElement; - if (bannerImg) { - bannerImg.src = savedBanner; - } - this.updateNavbarBanner(savedBanner); - } -} +// private loadSavedBanner(): void { +// const savedBanner = localStorage.getItem('userBanner'); +// if (savedBanner) { +// const bannerImg = this.shadowRoot?.getElementById('popup-banner-img') as HTMLImageElement; +// if (bannerImg) { +// bannerImg.src = savedBanner; +// } +// this.updateNavbarBanner(savedBanner); +// } +// } -private closeNotificationPopup(event: Event): void { - const target = event.target as HTMLElement; - const isOverlay = target.classList.contains('notification-popup-overlay'); - const isCloseButton = target.classList.contains('close-popup'); - if (!isOverlay && !isCloseButton) return; +// private closeNotificationPopup(event: Event): void { +// const target = event.target as HTMLElement; +// const isOverlay = target.classList.contains('notification-popup-overlay'); +// const isCloseButton = target.classList.contains('close-popup'); +// if (!isOverlay && !isCloseButton) return; - const popup = this.shadowRoot?.querySelector('.notification-popup-overlay'); - if (popup) popup.remove(); -} +// const popup = this.shadowRoot?.querySelector('.notification-popup-overlay'); +// if (popup) popup.remove(); +// } -private markAsRead(processName: string, messageId: number, element: HTMLElement): void { - const process = mockProcessRows.find(p => p.process === processName); - if (!process) return; +// private markAsRead(processName: string, messageId: number, element: HTMLElement): void { +// const process = mockProcessRows.find(p => p.process === processName); +// if (!process) return; - const message = process.notification.messages.find(m => m.id === messageId); - if (!message || message.read) return; +// const message = process.notification.messages.find(m => m.id === messageId); +// if (!message || message.read) return; - message.read = true; +// message.read = true; - element.classList.remove('unread'); - element.classList.add('read'); +// element.classList.remove('unread'); +// element.classList.add('read'); - const statusIcon = element.querySelector('.notification-status'); - if (statusIcon) { - statusIcon.innerHTML = ` - - - `; - } +// const statusIcon = element.querySelector('.notification-status'); +// if (statusIcon) { +// statusIcon.innerHTML = ` +// +// +// `; +// } - const notifCount = this.calculateNotifications(process.notification.messages); - const countElement = this.shadowRoot?.querySelector(`.notification-count[data-process="${processName}"]`); - if (countElement) { - countElement.textContent = `${notifCount.unread}/${notifCount.total}`; +// const notifCount = this.calculateNotifications(process.notification.messages); +// const countElement = this.shadowRoot?.querySelector(`.notification-count[data-process="${processName}"]`); +// if (countElement) { +// countElement.textContent = `${notifCount.unread}/${notifCount.total}`; - const bellContainer = countElement.closest('.notification-container'); - const bell = bellContainer?.querySelector('svg'); // Changé de .fa-bell à svg - if (bell && bellContainer && notifCount.unread === 0) { - bellContainer.classList.remove('has-unread'); - (bell as SVGElement).style.fill = '#666'; // Utiliser fill au lieu de color pour SVG - } - } -} +// const bellContainer = countElement.closest('.notification-container'); +// const bell = bellContainer?.querySelector('svg'); // Changé de .fa-bell à svg +// if (bell && bellContainer && notifCount.unread === 0) { +// bellContainer.classList.remove('has-unread'); +// (bell as SVGElement).style.fill = '#666'; // Utiliser fill au lieu de color pour SVG +// } +// } +// } -// Fonctions de gestion des données et de l'interface -private calculateNotifications(messages: NotificationMessage[]): { unread: number; total: number } { - const total = messages.length; - const unread = messages.filter(msg => !msg.read).length; - return { unread, total }; -} +// // Fonctions de gestion des données et de l'interface +// private calculateNotifications(messages: NotificationMessage[]): { unread: number; total: number } { +// const total = messages.length; +// const unread = messages.filter(msg => !msg.read).length; +// return { unread, total }; +// } -// Fonctions de récupération -private exportRecovery(): void { - Swal.fire({ - title: 'Recovery Words Export', - text: '4 words will be displayed. We strongly recommend writing them down on paper before exporting the account. Do you want to continue?', - icon: 'warning', - showCancelButton: true, - confirmButtonText: 'Confirm', - cancelButtonText: 'Cancel', - confirmButtonColor: '#C89666', - cancelButtonColor: '#6c757d', - // Ajouter des styles personnalisés - customClass: { - container: 'recovery-popup-container', - popup: 'recovery-popup' - } - }).then((result) => { - if (result.isConfirmed) { - const recoveryWords = this.generateRecoveryWords(); - localStorage.setItem('recoveryWords', JSON.stringify(recoveryWords)); +// // Fonctions de récupération +// private exportRecovery(): void { +// Swal.fire({ +// title: 'Recovery Words Export', +// text: '4 words will be displayed. We strongly recommend writing them down on paper before exporting the account. Do you want to continue?', +// icon: 'warning', +// showCancelButton: true, +// confirmButtonText: 'Confirm', +// cancelButtonText: 'Cancel', +// confirmButtonColor: '#C89666', +// cancelButtonColor: '#6c757d', +// // Ajouter des styles personnalisés +// customClass: { +// container: 'recovery-popup-container', +// popup: 'recovery-popup' +// } +// }).then((result) => { +// if (result.isConfirmed) { +// const recoveryWords = this.generateRecoveryWords(); +// localStorage.setItem('recoveryWords', JSON.stringify(recoveryWords)); - Swal.fire({ - title: 'Your Recovery Words', - html: ` -
- ${recoveryWords.map((word, index) => ` -
- ${index + 1}. - ${word} -
- `).join('')} -
-
- Please write these words down carefully. They will be needed to recover your account. -
- `, - showCancelButton: false, - confirmButtonText: 'I confirm the export', - confirmButtonColor: '#C89666', - allowOutsideClick: false, - allowEscapeKey: false, - customClass: { - container: 'recovery-popup-container', - popup: 'recovery-popup' - } - }).then((result) => { - if (result.isConfirmed) { - // Stocker l'état du bouton dans le localStorage - localStorage.setItem('recoveryExported', 'true'); +// Swal.fire({ +// title: 'Your Recovery Words', +// html: ` +//
+// ${recoveryWords.map((word, index) => ` +//
+// ${index + 1}. +// ${word} +//
+// `).join('')} +//
+//
+// Please write these words down carefully. They will be needed to recover your account. +//
+// `, +// showCancelButton: false, +// confirmButtonText: 'I confirm the export', +// confirmButtonColor: '#C89666', +// allowOutsideClick: false, +// allowEscapeKey: false, +// customClass: { +// container: 'recovery-popup-container', +// popup: 'recovery-popup' +// } +// }).then((result) => { +// if (result.isConfirmed) { +// // Stocker l'état du bouton dans le localStorage +// localStorage.setItem('recoveryExported', 'true'); - const exportRecoveryBtn = this.shadowRoot?.querySelector('.recovery-btn') as HTMLButtonElement; - if (exportRecoveryBtn) { - exportRecoveryBtn.disabled = true; - exportRecoveryBtn.style.opacity = '0.5'; - exportRecoveryBtn.style.cursor = 'not-allowed'; - } - } - }); - } - }); -} +// const exportRecoveryBtn = this.shadowRoot?.querySelector('.recovery-btn') as HTMLButtonElement; +// if (exportRecoveryBtn) { +// exportRecoveryBtn.disabled = true; +// exportRecoveryBtn.style.opacity = '0.5'; +// exportRecoveryBtn.style.cursor = 'not-allowed'; +// } +// } +// }); +// } +// }); +// } -private generateRecoveryWords(): string[] { - const wordsList = [ - 'apple', 'banana', 'orange', 'grape', 'kiwi', 'mango', 'peach', 'plum', - 'lemon', 'lime', 'cherry', 'melon', 'pear', 'fig', 'date', 'berry' - ]; - const recoveryWords: string[] = []; - while (recoveryWords.length < 4) { - const randomWord = wordsList[Math.floor(Math.random() * wordsList.length)]; - if (!recoveryWords.includes(randomWord)) { - recoveryWords.push(randomWord); - } - } - return recoveryWords; -} +// private generateRecoveryWords(): string[] { +// const wordsList = [ +// 'apple', 'banana', 'orange', 'grape', 'kiwi', 'mango', 'peach', 'plum', +// 'lemon', 'lime', 'cherry', 'melon', 'pear', 'fig', 'date', 'berry' +// ]; +// const recoveryWords: string[] = []; +// while (recoveryWords.length < 4) { +// const randomWord = wordsList[Math.floor(Math.random() * wordsList.length)]; +// if (!recoveryWords.includes(randomWord)) { +// recoveryWords.push(randomWord); +// } +// } +// return recoveryWords; +// } -private exportUserData(): void { - const data: { [key: string]: string | null } = {}; - for (let i = 0; i < localStorage.length; i++) { - const key = localStorage.key(i); - if (key) { - const value = localStorage.getItem(key); - data[key] = value; - } - } +// private exportUserData(): void { +// const data: { [key: string]: string | null } = {}; +// for (let i = 0; i < localStorage.length; i++) { +// const key = localStorage.key(i); +// if (key) { +// const value = localStorage.getItem(key); +// data[key] = value; +// } +// } - const jsonData = JSON.stringify(data, null, 2); - const blob = new Blob([jsonData], { type: 'application/json' }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = 'user_data.json'; - this.shadowRoot?.appendChild(a); - a.click(); - this.shadowRoot?.removeChild(a); - URL.revokeObjectURL(url); -} +// const jsonData = JSON.stringify(data, null, 2); +// const blob = new Blob([jsonData], { type: 'application/json' }); +// const url = URL.createObjectURL(blob); +// const a = document.createElement('a'); +// a.href = url; +// a.download = 'user_data.json'; +// this.shadowRoot?.appendChild(a); +// a.click(); +// this.shadowRoot?.removeChild(a); +// URL.revokeObjectURL(url); +// } -private updateActionButtons(): void { - const buttonContainer = this.shadowRoot?.querySelector('.button-container'); - if (!buttonContainer) return; +// private updateActionButtons(): void { +// const buttonContainer = this.shadowRoot?.querySelector('.button-container'); +// if (!buttonContainer) return; - buttonContainer.innerHTML = ` -
- - -
- `; -} +// buttonContainer.innerHTML = ` +//
+// +// +//
+// `; +// } -private getConfirmFunction(): string { - switch (currentMode) { - case 'wallet': - return 'window.confirmWalletRow()'; - case 'process': - return 'window.confirmProcessRow()'; - default: - return 'window.confirmRowPairing()'; - } -} +// private getConfirmFunction(): string { +// switch (currentMode) { +// case 'wallet': +// return 'window.confirmWalletRow()'; +// case 'process': +// return 'window.confirmProcessRow()'; +// default: +// return 'window.confirmRowPairing()'; +// } +// } -private getCancelFunction(): string { - switch (currentMode) { - case 'wallet': - return 'window.cancelWalletRow()'; - case 'process': - return 'window.cancelProcessRow()'; - default: - return 'window.cancelRowPairing()'; - } -} +// private getCancelFunction(): string { +// switch (currentMode) { +// case 'wallet': +// return 'window.cancelWalletRow()'; +// case 'process': +// return 'window.cancelProcessRow()'; +// default: +// return 'window.cancelRowPairing()'; +// } +// } -// Fonctions de gestion des tableaux -private async addRowPairing(): Promise { - if (isAddingRow) return; - isAddingRow = true; +// // Fonctions de gestion des tableaux +// private async addRowPairing(): Promise { +// if (isAddingRow) return; +// isAddingRow = true; - // Créer la popup - const modal = document.createElement('div'); - modal.className = 'pairing-modal'; - modal.innerHTML = ` -
-

Add New Device

-
-
- - -
-
- - -
-
- - -
-
- - -
-
-
- `; +// // Créer la popup +// const modal = document.createElement('div'); +// modal.className = 'pairing-modal'; +// modal.innerHTML = ` +//
+//

Add New Device

+//
+//
+// +// +//
+//
+// +// +//
+//
+// +// +//
+//
+// +// +//
+//
+//
+// `; - this.shadowRoot?.appendChild(modal); +// this.shadowRoot?.appendChild(modal); - // Ajouter les event listeners - const spAddressInput = modal.querySelector('#sp-address') as HTMLInputElement; - const spEmojisInput = modal.querySelector('#sp-emojis') as HTMLInputElement; - const deviceNameInput = modal.querySelector('#device-name') as HTMLInputElement; - const confirmButton = modal.querySelector('.confirm-button'); - const cancelButton = modal.querySelector('.cancel-button'); +// // Ajouter les event listeners +// const spAddressInput = modal.querySelector('#sp-address') as HTMLInputElement; +// const spEmojisInput = modal.querySelector('#sp-emojis') as HTMLInputElement; +// const deviceNameInput = modal.querySelector('#device-name') as HTMLInputElement; +// const confirmButton = modal.querySelector('.confirm-button'); +// const cancelButton = modal.querySelector('.cancel-button'); - // Mettre à jour les emojis automatiquement - spAddressInput?.addEventListener('input', async () => { - const emojis = await addressToEmoji(spAddressInput.value); - if (spEmojisInput) spEmojisInput.value = emojis; - }); +// // Mettre à jour les emojis automatiquement +// spAddressInput?.addEventListener('input', async () => { +// const emojis = await addressToEmoji(spAddressInput.value); +// if (spEmojisInput) spEmojisInput.value = emojis; +// }); - // Gérer la confirmation - confirmButton?.addEventListener('click', () => { - const spAddress = spAddressInput?.value.trim(); - const deviceName = deviceNameInput?.value.trim(); - const spEmojis = spEmojisInput?.value.trim(); +// // Gérer la confirmation +// confirmButton?.addEventListener('click', () => { +// const spAddress = spAddressInput?.value.trim(); +// const deviceName = deviceNameInput?.value.trim(); +// const spEmojis = spEmojisInput?.value.trim(); - if (!spAddress || !deviceName) { - this.showAlert('Please fill in all required fields'); - return; - } +// if (!spAddress || !deviceName) { +// this.showAlert('Please fill in all required fields'); +// return; +// } - //if (spAddress.length !== 118) { - // this.showAlert('SP Address must be exactly 118 characters long'); - // return; - //} +// //if (spAddress.length !== 118) { +// // this.showAlert('SP Address must be exactly 118 characters long'); +// // return; +// //} - const newRow: Row = { - column1: spAddress, - column2: deviceName, - column3: spEmojis || '' - }; +// const newRow: Row = { +// column1: spAddress, +// column2: deviceName, +// column3: spEmojis || '' +// }; - const storageKey = STORAGE_KEYS[currentMode]; - const rows: Row[] = JSON.parse(localStorage.getItem(storageKey) || '[]'); - rows.push(newRow); - localStorage.setItem(storageKey, JSON.stringify(rows)); +// const storageKey = STORAGE_KEYS[currentMode]; +// const rows: Row[] = JSON.parse(localStorage.getItem(storageKey) || '[]'); +// rows.push(newRow); +// localStorage.setItem(storageKey, JSON.stringify(rows)); - this.updateTableContent(rows); - modal.remove(); - isAddingRow = false; - }); +// this.updateTableContent(rows); +// modal.remove(); +// isAddingRow = false; +// }); - // Gérer l'annulation - cancelButton?.addEventListener('click', () => { - modal.remove(); - isAddingRow = false; - }); -} +// // Gérer l'annulation +// cancelButton?.addEventListener('click', () => { +// modal.remove(); +// isAddingRow = false; +// }); +// } -// Fonctions de mise à jour de l'interface -private updateTableContent(rows: Row[]): void { - const tbody = this.shadowRoot?.querySelector('#pairing-table tbody'); - if (!tbody) return; +// // Fonctions de mise à jour de l'interface +// private updateTableContent(rows: Row[]): void { +// const tbody = this.shadowRoot?.querySelector('#pairing-table tbody'); +// if (!tbody) return; - tbody.innerHTML = rows.map(row => ` - - ${row.column2} - ${row.column3} - - QR Code - - - - - - `).join(''); -} +// tbody.innerHTML = rows.map(row => ` +// +// ${row.column2} +// ${row.column3} +// +// QR Code +// +// +// +// +// +// `).join(''); +// } -private confirmRowPairing(): void { - if (!currentRow) return; +// private confirmRowPairing(): void { +// if (!currentRow) return; - const inputs = currentRow.getElementsByTagName('input'); - const values: string[] = Array.from(inputs).map(input => input.value.trim()); +// const inputs = currentRow.getElementsByTagName('input'); +// const values: string[] = Array.from(inputs).map(input => input.value.trim()); - // Vérification des champs vides - if (values.some(value => value === '')) { - this.showAlert('Please fill in all fields'); - return; - } +// // Vérification des champs vides +// if (values.some(value => value === '')) { +// this.showAlert('Please fill in all fields'); +// return; +// } - // Vérification de la longueur de l'adresse SP - if (values[0].length !== 118) { - this.showAlert('SP Address must be exactly 118 characters long'); - return; - } +// // Vérification de la longueur de l'adresse SP +// if (values[0].length !== 118) { +// this.showAlert('SP Address must be exactly 118 characters long'); +// return; +// } - const newRow: Row = { - column1: values[0], - column2: values[1], - column3: values[2] - }; +// const newRow: Row = { +// column1: values[0], +// column2: values[1], +// column3: values[2] +// }; - const storageKey = STORAGE_KEYS[currentMode]; - const rows: Row[] = JSON.parse(localStorage.getItem(storageKey) || '[]'); - rows.push(newRow); - localStorage.setItem(storageKey, JSON.stringify(rows)); +// const storageKey = STORAGE_KEYS[currentMode]; +// const rows: Row[] = JSON.parse(localStorage.getItem(storageKey) || '[]'); +// rows.push(newRow); +// localStorage.setItem(storageKey, JSON.stringify(rows)); - isAddingRow = false; - currentRow = null; +// isAddingRow = false; +// currentRow = null; - this.resetButtonContainer(); - this.updateTableContent(rows); -} +// this.resetButtonContainer(); +// this.updateTableContent(rows); +// } -private cancelRowPairing(): void { - if (!currentRow) return; +// private cancelRowPairing(): void { +// if (!currentRow) return; - currentRow.remove(); - isAddingRow = false; - currentRow = null; +// currentRow.remove(); +// isAddingRow = false; +// currentRow = null; - this.resetButtonContainer(); -} +// this.resetButtonContainer(); +// } -private resetButtonContainer(): void { - const buttonContainer = this.shadowRoot?.querySelector('.button-container'); - if (!buttonContainer) return; +// private resetButtonContainer(): void { +// const buttonContainer = this.shadowRoot?.querySelector('.button-container'); +// if (!buttonContainer) return; - buttonContainer.innerHTML = ` - - `; -} +// buttonContainer.innerHTML = ` +// +// `; +// } -private deleteRowPairing(button: HTMLButtonElement): void { - const row = button.closest('tr'); - if (!row) return; +// private deleteRowPairing(button: HTMLButtonElement): void { +// const row = button.closest('tr'); +// if (!row) return; - const table = row.closest('tbody'); - if (!table) return; +// const table = row.closest('tbody'); +// if (!table) return; - const remainingRows = table.getElementsByTagName('tr').length; - if (remainingRows <= 2) { - this.showAlert('You must keep at least 2 devices paired'); - return; - } +// const remainingRows = table.getElementsByTagName('tr').length; +// if (remainingRows <= 2) { +// this.showAlert('You must keep at least 2 devices paired'); +// return; +// } - // Créer la modal de confirmation - const modal = document.createElement('div'); - modal.className = 'confirm-delete-modal'; - modal.innerHTML = ` -
-

Confirm Deletion

-

Are you sure you want to delete this device?

-
- - -
-
- `; +// // Créer la modal de confirmation +// const modal = document.createElement('div'); +// modal.className = 'confirm-delete-modal'; +// modal.innerHTML = ` +//
+//

Confirm Deletion

+//

Are you sure you want to delete this device?

+//
+// +// +//
+//
+// `; - this.shadowRoot?.appendChild(modal); +// this.shadowRoot?.appendChild(modal); - // Gérer les boutons de la modal - const confirmBtn = modal.querySelector('.confirm-btn'); - const cancelBtn = modal.querySelector('.cancel-btn'); +// // Gérer les boutons de la modal +// const confirmBtn = modal.querySelector('.confirm-btn'); +// const cancelBtn = modal.querySelector('.cancel-btn'); - confirmBtn?.addEventListener('click', () => { - // Calculer l'index AVANT de supprimer la ligne du DOM - const index = Array.from(table.children).indexOf(row); - const storageKey = STORAGE_KEYS[currentMode]; - const rows = JSON.parse(localStorage.getItem(storageKey) || '[]'); +// confirmBtn?.addEventListener('click', () => { +// // Calculer l'index AVANT de supprimer la ligne du DOM +// const index = Array.from(table.children).indexOf(row); +// const storageKey = STORAGE_KEYS[currentMode]; +// const rows = JSON.parse(localStorage.getItem(storageKey) || '[]'); - // Supprimer du localStorage - if (index > -1) { - rows.splice(index, 1); - localStorage.setItem(storageKey, JSON.stringify(rows)); - } +// // Supprimer du localStorage +// if (index > -1) { +// rows.splice(index, 1); +// localStorage.setItem(storageKey, JSON.stringify(rows)); +// } - // Animation et suppression du DOM - row.style.transition = 'opacity 0.3s, transform 0.3s'; - row.style.opacity = '0'; - row.style.transform = 'translateX(-100%)'; +// // Animation et suppression du DOM +// row.style.transition = 'opacity 0.3s, transform 0.3s'; +// row.style.opacity = '0'; +// row.style.transform = 'translateX(-100%)'; - setTimeout(() => { - row.remove(); - }, 300); +// setTimeout(() => { +// row.remove(); +// }, 300); - modal.remove(); - }); +// modal.remove(); +// }); - cancelBtn?.addEventListener('click', () => { - modal.remove(); - }); -} +// cancelBtn?.addEventListener('click', () => { +// modal.remove(); +// }); +// } -private editDeviceName(cell: HTMLTableCellElement): void { - if (cell.classList.contains('editing')) return; +// private editDeviceName(cell: HTMLTableCellElement): void { +// if (cell.classList.contains('editing')) return; - const currentValue = cell.textContent || ''; - const input = document.createElement('input'); - input.type = 'text'; - input.value = currentValue; - input.className = 'edit-input'; +// const currentValue = cell.textContent || ''; +// const input = document.createElement('input'); +// input.type = 'text'; +// input.value = currentValue; +// input.className = 'edit-input'; - input.addEventListener('blur', () => this.finishEditing(cell, input)); - input.addEventListener('keypress', (e: KeyboardEvent) => { - if (e.key === 'Enter') { - this.finishEditing(cell, input); - } - }); +// input.addEventListener('blur', () => this.finishEditing(cell, input)); +// input.addEventListener('keypress', (e: KeyboardEvent) => { +// if (e.key === 'Enter') { +// this.finishEditing(cell, input); +// } +// }); - cell.textContent = ''; - cell.appendChild(input); - cell.classList.add('editing'); - input.focus(); -} +// cell.textContent = ''; +// cell.appendChild(input); +// cell.classList.add('editing'); +// input.focus(); +// } -private async finishEditing(cell: HTMLTableCellElement, input: HTMLInputElement): Promise { - const newValue = input.value.trim(); - if (newValue === '') { - cell.textContent = cell.getAttribute('data-original-value') || ''; - cell.classList.remove('editing'); - return; - } +// private async finishEditing(cell: HTMLTableCellElement, input: HTMLInputElement): Promise { +// const newValue = input.value.trim(); +// if (newValue === '') { +// cell.textContent = cell.getAttribute('data-original-value') || ''; +// cell.classList.remove('editing'); +// return; +// } - try { - const service = await Services.getInstance(); - const pairingProcessId = service.getPairingProcessId(); - const process = await service.getProcess(pairingProcessId); +// try { +// const service = await Services.getInstance(); +// const pairingProcessId = service.getPairingProcessId(); +// const process = await service.getProcess(pairingProcessId); - // Mettre à jour le nom via le service - await service.updateMemberPublicName(process, newValue); +// // Mettre à jour le nom via le service +// await service.updateMemberPublicName(process, newValue); - // Mettre à jour l'interface - cell.textContent = newValue; - cell.classList.remove('editing'); - } catch (error) { - console.error('Failed to update name:', error); - // Restaurer l'ancienne valeur en cas d'erreur - cell.textContent = cell.getAttribute('data-original-value') || ''; - cell.classList.remove('editing'); - } -} +// // Mettre à jour l'interface +// cell.textContent = newValue; +// cell.classList.remove('editing'); +// } catch (error) { +// console.error('Failed to update name:', error); +// // Restaurer l'ancienne valeur en cas d'erreur +// cell.textContent = cell.getAttribute('data-original-value') || ''; +// cell.classList.remove('editing'); +// } +// } -// Fonction pour gérer le téléchargement de l'avatar -private handleAvatarUpload(event: Event): void { - const input = event.target as HTMLInputElement; - const file = input.files?.[0]; +// // Fonction pour gérer le téléchargement de l'avatar +// private handleAvatarUpload(event: Event): void { +// const input = event.target as HTMLInputElement; +// const file = input.files?.[0]; - if (file) { - const reader = new FileReader(); - reader.onload = (e: ProgressEvent) => { - const result = e.target?.result as string; - const popupAvatar = this.shadowRoot?.getElementById('popup-avatar-img') as HTMLImageElement; - const navAvatar = this.shadowRoot?.querySelector('.nav-wrapper .avatar') as HTMLImageElement; +// if (file) { +// const reader = new FileReader(); +// reader.onload = (e: ProgressEvent) => { +// const result = e.target?.result as string; +// const popupAvatar = this.shadowRoot?.getElementById('popup-avatar-img') as HTMLImageElement; +// const navAvatar = this.shadowRoot?.querySelector('.nav-wrapper .avatar') as HTMLImageElement; - if (popupAvatar) popupAvatar.src = result; - if (navAvatar) navAvatar.src = result; +// if (popupAvatar) popupAvatar.src = result; +// if (navAvatar) navAvatar.src = result; - localStorage.setItem('userAvatar', result); - }; - reader.readAsDataURL(file); - } -} +// localStorage.setItem('userAvatar', result); +// }; +// reader.readAsDataURL(file); +// } +// } -private async showProcessCreation(): Promise { - this.hideAllContent(); - const container = this.shadowRoot?.getElementById('process-creation-content'); - if (container) { - getProcessCreation(container); - } -} +// private async showProcessCreation(): Promise { +// this.hideAllContent(); +// const container = this.shadowRoot?.getElementById('process-creation-content'); +// if (container) { +// getProcessCreation(container); +// } +// } -private async showDocumentValidation(): Promise { - this.hideAllContent(); - const container = this.shadowRoot?.getElementById('document-validation-content'); - if (container) { - getDocumentValidation(container); - } -} +// private async showDocumentValidation(): Promise { +// this.hideAllContent(); +// const container = this.shadowRoot?.getElementById('document-validation-content'); +// if (container) { +// getDocumentValidation(container); +// } +// } -private async showProcess(): Promise { - this.hideAllContent(); - const container = this.shadowRoot?.getElementById('process-content'); - if (container) { - const service = await Services.getInstance(); - const myProcesses = await service.getMyProcesses(); - if (myProcesses && myProcesses.length != 0) { - const myProcessesDataUnfiltered: { name: string, publicData: Record }[] = await Promise.all(myProcesses.map(async processId => { - const process = await service.getProcess(processId); - const lastState = service.getLastCommitedState(process); - if (!lastState) { - return { - name: '', - publicData: {} - }; - } - const description = await service.decryptAttribute(processId, lastState, 'description'); - const name = description ? description : 'N/A'; - const publicData = await service.getPublicData(process); - if (!publicData) { - return { - name: '', - publicData: {} - }; - } - return { - name: name, - publicData: publicData - }; - })); - const myProcessesData = myProcessesDataUnfiltered.filter( - (p) => p.name !== '' && Object.keys(p.publicData).length != 0 - ); +// private async showProcess(): Promise { +// this.hideAllContent(); +// const container = this.shadowRoot?.getElementById('process-content'); +// if (container) { +// const service = await Services.getInstance(); +// const myProcesses = await service.getMyProcesses(); +// if (myProcesses && myProcesses.length != 0) { +// const myProcessesDataUnfiltered: { name: string, publicData: Record }[] = await Promise.all(myProcesses.map(async processId => { +// const process = await service.getProcess(processId); +// const lastState = service.getLastCommitedState(process); +// if (!lastState) { +// return { +// name: '', +// publicData: {} +// }; +// } +// const description = await service.decryptAttribute(processId, lastState, 'description'); +// const name = description ? description : 'N/A'; +// const publicData = await service.getPublicData(process); +// if (!publicData) { +// return { +// name: '', +// publicData: {} +// }; +// } +// return { +// name: name, +// publicData: publicData +// }; +// })); +// const myProcessesData = myProcessesDataUnfiltered.filter( +// (p) => p.name !== '' && Object.keys(p.publicData).length != 0 +// ); - createProcessTab(container, myProcessesData); - } else { - createProcessTab(container, []); - } - } -} +// createProcessTab(container, myProcessesData); +// } else { +// createProcessTab(container, []); +// } +// } +// } -private showProcessNotifications(processName: string): void { - const process = mockProcessRows.find(p => p.process === processName); - if (!process) return; +// private showProcessNotifications(processName: string): void { +// const process = mockProcessRows.find(p => p.process === processName); +// if (!process) return; - const modal = document.createElement('div'); - modal.className = 'notifications-modal'; +// const modal = document.createElement('div'); +// modal.className = 'notifications-modal'; - let notificationsList = process.notification.messages.map(msg => ` -
-
- ${msg.read ? - ` - - ` : - ` - - ` - } -
-
- ${msg.message} - ${msg.date} -
-
- `).join(''); +// let notificationsList = process.notification.messages.map(msg => ` +//
+//
+// ${msg.read ? +// ` +// +// ` : +// ` +// +// ` +// } +//
+//
+// ${msg.message} +// ${msg.date} +//
+//
+// `).join(''); - if (process.notification.messages.length === 0) { - notificationsList = '

No notifications

'; - } +// if (process.notification.messages.length === 0) { +// notificationsList = '

No notifications

'; +// } - modal.innerHTML = ` -
-

${processName} Notifications

-
- ${notificationsList} -
- -
- `; +// modal.innerHTML = ` +//
+//

${processName} Notifications

+//
+// ${notificationsList} +//
+// +//
+// `; - this.shadowRoot?.appendChild(modal); +// this.shadowRoot?.appendChild(modal); - // Mettre à jour le compteur de notifications - const countElement = this.shadowRoot?.querySelector(`.notification-count[data-process="${processName}"]`); - if (countElement) { - const notifCount = this.calculateNotifications(process.notification.messages); - countElement.textContent = `${notifCount.unread}/${notifCount.total}`; - } +// // Mettre à jour le compteur de notifications +// const countElement = this.shadowRoot?.querySelector(`.notification-count[data-process="${processName}"]`); +// if (countElement) { +// const notifCount = this.calculateNotifications(process.notification.messages); +// countElement.textContent = `${notifCount.unread}/${notifCount.total}`; +// } - const closeButton = modal.querySelector('.close-notifications'); - closeButton?.addEventListener('click', () => { - modal.remove(); - this.showProcess(); // Rafraîchir l'affichage pour mettre à jour les compteurs - }); -} +// const closeButton = modal.querySelector('.close-notifications'); +// closeButton?.addEventListener('click', () => { +// modal.remove(); +// this.showProcess(); // Rafraîchir l'affichage pour mettre à jour les compteurs +// }); +// } -private handleLogout(): void { - localStorage.clear(); - window.location.href = '../login/login.html'; -} +// private handleLogout(): void { +// localStorage.clear(); +// window.location.href = '../login/login.html'; +// } -// Fonctions de gestion des contrats -private showContractPopup(contractId: string, event?: Event) { - if (event) { - event.preventDefault(); - } +// // Fonctions de gestion des contrats +// private showContractPopup(contractId: string, event?: Event) { +// if (event) { +// event.preventDefault(); +// } - // Check if the contract exists in mockContracts - const contract = mockContracts[contractId as keyof typeof mockContracts]; - if (!contract) { - console.error('Contract not found:', contractId); - return; - } +// // Check if the contract exists in mockContracts +// const contract = mockContracts[contractId as keyof typeof mockContracts]; +// if (!contract) { +// console.error('Contract not found:', contractId); +// return; +// } - const popup = document.createElement('div'); - popup.className = 'contract-popup-overlay'; - popup.innerHTML = ` -
- -

${contract.title}

-
-

Date: ${contract.date}

-

Parties: ${contract.parties.join(', ')}

-

Terms:

-
    - ${contract.terms.map(term => `
  • ${term}
  • `).join('')} -
-

Content: ${contract.content}

-
-
- `; +// const popup = document.createElement('div'); +// popup.className = 'contract-popup-overlay'; +// popup.innerHTML = ` +//
+// +//

${contract.title}

+//
+//

Date: ${contract.date}

+//

Parties: ${contract.parties.join(', ')}

+//

Terms:

+//
    +// ${contract.terms.map(term => `
  • ${term}
  • `).join('')} +//
+//

Content: ${contract.content}

+//
+//
+// `; - this.shadowRoot?.appendChild(popup); +// this.shadowRoot?.appendChild(popup); - const closeBtn = popup.querySelector('.close-contract-popup'); - const closePopup = () => popup.remove(); +// const closeBtn = popup.querySelector('.close-contract-popup'); +// const closePopup = () => popup.remove(); - closeBtn?.addEventListener('click', closePopup); - popup.addEventListener('click', (e) => { - if (e.target === popup) closePopup(); - }); -} +// closeBtn?.addEventListener('click', closePopup); +// popup.addEventListener('click', (e) => { +// if (e.target === popup) closePopup(); +// }); +// } -// Fonction utilitaire pour cacher tous les contenus -private hideAllContent(): void { - const contents = ['pairing-content', 'wallet-content', 'process-content', 'process-creation-content', 'data-content', 'document-validation-content']; - contents.forEach(id => { - const element = this.shadowRoot?.getElementById(id); - if (element) { - element.style.display = 'none'; - } - }); -} +// // Fonction utilitaire pour cacher tous les contenus +// private hideAllContent(): void { +// const contents = ['pairing-content', 'wallet-content', 'process-content', 'process-creation-content', 'data-content', 'document-validation-content']; +// contents.forEach(id => { +// const element = this.shadowRoot?.getElementById(id); +// if (element) { +// element.style.display = 'none'; +// } +// }); +// } -// Fonctions d'affichage des sections -private async showPairing(): Promise { - const service = await Services.getInstance(); - const spAddress = await service.getDeviceAddress(); +// // Fonctions d'affichage des sections +// private async showPairing(): Promise { +// const service = await Services.getInstance(); +// const spAddress = await service.getDeviceAddress(); - isAddingRow = false; - currentRow = null; - currentMode = 'pairing'; +// isAddingRow = false; +// currentRow = null; +// currentMode = 'pairing'; - this.hideAllContent(); +// this.hideAllContent(); - const headerElement = this.shadowRoot?.getElementById('parameter-header'); - if (headerElement) { - headerElement.textContent = 'Pairing'; - } +// const headerElement = this.shadowRoot?.getElementById('parameter-header'); +// if (headerElement) { +// headerElement.textContent = 'Pairing'; +// } - const pairingContent = this.shadowRoot?.getElementById('pairing-content'); - if (pairingContent) { - pairingContent.style.display = 'block'; - pairingContent.innerHTML = ` -
Pairing
-
- - - - - - - - - - -
Device NameSP EmojisQR CodeActions
-
- -
-
- `; +// const pairingContent = this.shadowRoot?.getElementById('pairing-content'); +// if (pairingContent) { +// pairingContent.style.display = 'block'; +// pairingContent.innerHTML = ` +//
Pairing
+//
+// +// +// +// +// +// +// +// +// +// +//
Device NameSP EmojisQR CodeActions
+//
+// +//
+//
+// `; - let rows = JSON.parse(localStorage.getItem(STORAGE_KEYS.pairing) || '[]'); +// let rows = JSON.parse(localStorage.getItem(STORAGE_KEYS.pairing) || '[]'); - const deviceExists = rows.some((row: Row) => row.column1 === spAddress); +// const deviceExists = rows.some((row: Row) => row.column1 === spAddress); - if (!deviceExists && spAddress) { - const emojis = await addressToEmoji(spAddress); +// if (!deviceExists && spAddress) { +// const emojis = await addressToEmoji(spAddress); - try { - // Déboguer le processus de pairing - const pairingProcessId = await service.getPairingProcessId(); - console.log('Pairing Process ID:', pairingProcessId); +// try { +// // Déboguer le processus de pairing +// const pairingProcessId = await service.getPairingProcessId(); +// console.log('Pairing Process ID:', pairingProcessId); - const pairingProcess = await service.getProcess(pairingProcessId); - console.log('Pairing Process:', pairingProcess); +// const pairingProcess = await service.getProcess(pairingProcessId); +// console.log('Pairing Process:', pairingProcess); - const userName = pairingProcess?.states?.[0]?.public_data?.memberPublicName - || localStorage.getItem('userName') +// const userName = pairingProcess?.states?.[0]?.public_data?.memberPublicName +// || localStorage.getItem('userName') - console.log('Username found:', userName); +// console.log('Username found:', userName); - const newRow = { - column1: spAddress, - column2: userName, - column3: emojis - }; - rows = [newRow, ...rows]; - localStorage.setItem(STORAGE_KEYS.pairing, JSON.stringify(rows)); - } catch (error) { - console.error('Error getting pairing process:', error); - const newRow = { - column1: spAddress, - column2: 'This Device', - column3: emojis - }; - rows = [newRow, ...rows]; - localStorage.setItem(STORAGE_KEYS.pairing, JSON.stringify(rows)); - } - } +// const newRow = { +// column1: spAddress, +// column2: userName, +// column3: emojis +// }; +// rows = [newRow, ...rows]; +// localStorage.setItem(STORAGE_KEYS.pairing, JSON.stringify(rows)); +// } catch (error) { +// console.error('Error getting pairing process:', error); +// const newRow = { +// column1: spAddress, +// column2: 'This Device', +// column3: emojis +// }; +// rows = [newRow, ...rows]; +// localStorage.setItem(STORAGE_KEYS.pairing, JSON.stringify(rows)); +// } +// } - this.updateTableContent(rows); - } -} +// this.updateTableContent(rows); +// } +// } -private showWallet(): void { - isAddingRow = false; - currentRow = null; +// private showWallet(): void { +// isAddingRow = false; +// currentRow = null; - currentMode = 'wallet'; - this.hideAllContent(); +// currentMode = 'wallet'; +// this.hideAllContent(); - // Mettre à jour le titre - const headerTitle = this.shadowRoot?.getElementById('header-title'); - if (headerTitle) headerTitle.textContent = 'Wallet'; +// // Mettre à jour le titre +// const headerTitle = this.shadowRoot?.getElementById('header-title'); +// if (headerTitle) headerTitle.textContent = 'Wallet'; - const walletContent = this.shadowRoot?.getElementById('wallet-content'); - if (!walletContent) return; - walletContent.style.display = 'block'; - walletContent.innerHTML = ` -
Wallet
-
- - - - - - - - - -
LabelWalletType
-
- -
-
- `; +// const walletContent = this.shadowRoot?.getElementById('wallet-content'); +// if (!walletContent) return; +// walletContent.style.display = 'block'; +// walletContent.innerHTML = ` +//
Wallet
+//
+// +// +// +// +// +// +// +// +// +//
LabelWalletType
+//
+// +//
+//
+// `; - const rows = JSON.parse(localStorage.getItem(STORAGE_KEYS.wallet) || '[]'); - this.updateWalletTableContent(rows); -} +// const rows = JSON.parse(localStorage.getItem(STORAGE_KEYS.wallet) || '[]'); +// this.updateWalletTableContent(rows); +// } -private updateWalletTableContent(rows: WalletRow[]): void { - const tbody = this.shadowRoot?.querySelector('#wallet-table tbody'); - if (!tbody) return; +// private updateWalletTableContent(rows: WalletRow[]): void { +// const tbody = this.shadowRoot?.querySelector('#wallet-table tbody'); +// if (!tbody) return; - tbody.innerHTML = rows.map(row => ` - - ${row.column1} - ${row.column2} - ${row.column3} - - `).join(''); -} +// tbody.innerHTML = rows.map(row => ` +// +// ${row.column1} +// ${row.column2} +// ${row.column3} +// +// `).join(''); +// } -private showData(): void { - //console.log("showData called"); - currentMode = 'data'; - this.hideAllContent(); +// private showData(): void { +// //console.log("showData called"); +// currentMode = 'data'; +// this.hideAllContent(); - const headerTitle = this.shadowRoot?.getElementById('header-title'); - if (headerTitle) headerTitle.textContent = 'Data'; +// const headerTitle = this.shadowRoot?.getElementById('header-title'); +// if (headerTitle) headerTitle.textContent = 'Data'; - const dataContent = this.shadowRoot?.getElementById('data-content'); - if (dataContent) { - dataContent.style.display = 'block'; - dataContent.innerHTML = ` -
Data
-
- - - - - - - - - - - - -
NameVisibilityRoleDurationLegalContract
-
- `; +// const dataContent = this.shadowRoot?.getElementById('data-content'); +// if (dataContent) { +// dataContent.style.display = 'block'; +// dataContent.innerHTML = ` +//
Data
+//
+// +// +// +// +// +// +// +// +// +// +// +// +//
NameVisibilityRoleDurationLegalContract
+//
+// `; - const rows = mockDataRows || JSON.parse(localStorage.getItem(STORAGE_KEYS.data) || '[]'); - this.updateDataTableContent(rows); - } -} +// const rows = mockDataRows || JSON.parse(localStorage.getItem(STORAGE_KEYS.data) || '[]'); +// this.updateDataTableContent(rows); +// } +// } -// Fonctions de gestion du wallet -private addWalletRow(): void { - if (isAddingRow) return; - isAddingRow = true; +// // Fonctions de gestion du wallet +// private addWalletRow(): void { +// if (isAddingRow) return; +// isAddingRow = true; - const table = this.shadowRoot?.getElementById('wallet-table')?.getElementsByTagName('tbody')[0]; - if (!table) return; +// const table = this.shadowRoot?.getElementById('wallet-table')?.getElementsByTagName('tbody')[0]; +// if (!table) return; - currentRow = table.insertRow(); - const placeholders = ['Label', 'Wallet', 'Type']; +// currentRow = table.insertRow(); +// const placeholders = ['Label', 'Wallet', 'Type']; - placeholders.forEach(placeholder => { - const cell = currentRow!.insertCell(); - const input = document.createElement('input'); - input.type = 'text'; - input.placeholder = placeholder; - input.className = 'edit-input'; - cell.appendChild(input); - }); +// placeholders.forEach(placeholder => { +// const cell = currentRow!.insertCell(); +// const input = document.createElement('input'); +// input.type = 'text'; +// input.placeholder = placeholder; +// input.className = 'edit-input'; +// cell.appendChild(input); +// }); - // Remplacer le bouton "Add a line" par les boutons de confirmation/annulation - const buttonContainer = this.shadowRoot?.querySelector('#wallet-content .button-container'); - if (!buttonContainer) return; +// // Remplacer le bouton "Add a line" par les boutons de confirmation/annulation +// const buttonContainer = this.shadowRoot?.querySelector('#wallet-content .button-container'); +// if (!buttonContainer) return; - buttonContainer.innerHTML = ` -
- - -
- `; +// buttonContainer.innerHTML = ` +//
+// +// +//
+// `; - this.updateActionButtons(); -} +// this.updateActionButtons(); +// } -private confirmWalletRow(): void { - if (!currentRow) return; +// private confirmWalletRow(): void { +// if (!currentRow) return; - const inputs = Array.from(currentRow.getElementsByTagName('input')); - const allFieldsFilled = inputs.every(input => input.value.trim() !== ''); +// const inputs = Array.from(currentRow.getElementsByTagName('input')); +// const allFieldsFilled = inputs.every(input => input.value.trim() !== ''); - if (allFieldsFilled) { - const newRow: WalletRow = { - column1: inputs[0].value.trim(), - column2: inputs[1].value.trim(), - column3: inputs[2].value.trim() - }; +// if (allFieldsFilled) { +// const newRow: WalletRow = { +// column1: inputs[0].value.trim(), +// column2: inputs[1].value.trim(), +// column3: inputs[2].value.trim() +// }; - const rows = JSON.parse(localStorage.getItem(STORAGE_KEYS.wallet) || '[]'); - rows.push(newRow); - localStorage.setItem(STORAGE_KEYS.wallet, JSON.stringify(rows)); +// const rows = JSON.parse(localStorage.getItem(STORAGE_KEYS.wallet) || '[]'); +// rows.push(newRow); +// localStorage.setItem(STORAGE_KEYS.wallet, JSON.stringify(rows)); - isAddingRow = false; - currentRow = null; - this.showWallet(); - } else { - this.showAlert('Please complete all fields before confirming.'); - } -} +// isAddingRow = false; +// currentRow = null; +// this.showWallet(); +// } else { +// this.showAlert('Please complete all fields before confirming.'); +// } +// } -private cancelWalletRow(): void { - if (!currentRow) return; +// private cancelWalletRow(): void { +// if (!currentRow) return; - currentRow.remove(); - isAddingRow = false; - currentRow = null; +// currentRow.remove(); +// isAddingRow = false; +// currentRow = null; - // Réinitialiser le conteneur de boutons avec le bouton "Add a line" - const buttonContainer = this.shadowRoot?.querySelector('#wallet-content .button-container'); - if (!buttonContainer) return; +// // Réinitialiser le conteneur de boutons avec le bouton "Add a line" +// const buttonContainer = this.shadowRoot?.querySelector('#wallet-content .button-container'); +// if (!buttonContainer) return; - buttonContainer.innerHTML = ` - - `; +// buttonContainer.innerHTML = ` +// +// `; -} +// } -private updateDataTableContent(rows: DataRow[]): void { - const tbody = this.shadowRoot?.querySelector('#data-table tbody'); - if (!tbody) return; +// private updateDataTableContent(rows: DataRow[]): void { +// const tbody = this.shadowRoot?.querySelector('#data-table tbody'); +// if (!tbody) return; - tbody.innerHTML = rows.map(row => ` - - ${row.column1} - ${row.column2} - ${row.column3} - ${row.column4} - ${row.column5} - - ${row.column6} - - - `).join(''); -} +// tbody.innerHTML = rows.map(row => ` +// +// ${row.column1} +// ${row.column2} +// ${row.column3} +// ${row.column4} +// ${row.column5} +// +// ${row.column6} +// +// +// `).join(''); +// } -// Fonctions de gestion de l'avatar et de la bannière -private openAvatarPopup(): void { - const popup = this.shadowRoot?.getElementById('avatar-popup'); - if (!popup) return; +// // Fonctions de gestion de l'avatar et de la bannière +// private openAvatarPopup(): void { +// const popup = this.shadowRoot?.getElementById('avatar-popup'); +// if (!popup) return; - // Récuprer les valeurs stockées - const savedName = localStorage.getItem('userName'); - const savedLastName = localStorage.getItem('userLastName'); - const savedAvatar = localStorage.getItem('userAvatar') || 'https://via.placeholder.com/150'; - const savedBanner = localStorage.getItem('userBanner') || 'https://via.placeholder.com/800x200'; - const savedAddress = localStorage.getItem('userAddress') || '🏠 🌍 🗽🎊😩-🎊😑😩'; +// // Récuprer les valeurs stockées +// const savedName = localStorage.getItem('userName'); +// const savedLastName = localStorage.getItem('userLastName'); +// const savedAvatar = localStorage.getItem('userAvatar') || 'https://via.placeholder.com/150'; +// const savedBanner = localStorage.getItem('userBanner') || 'https://via.placeholder.com/800x200'; +// const savedAddress = localStorage.getItem('userAddress') || '🏠 🌍 🗽🎊😩-🎊😑😩'; - popup.innerHTML = ` - +// `; - popup.style.display = 'block'; - this.setupEventListeners(popup); +// popup.style.display = 'block'; +// this.setupEventListeners(popup); - // Ajouter le gestionnaire d'événements pour la bannière - const bannerImg = popup.querySelector('#popup-banner-img'); - const bannerInput = popup.querySelector('#banner-upload') as HTMLInputElement; +// // Ajouter le gestionnaire d'événements pour la bannière +// const bannerImg = popup.querySelector('#popup-banner-img'); +// const bannerInput = popup.querySelector('#banner-upload') as HTMLInputElement; - if (bannerImg && bannerInput) { - bannerImg.addEventListener('click', () => { - bannerInput.click(); - }); - } +// if (bannerImg && bannerInput) { +// bannerImg.addEventListener('click', () => { +// bannerInput.click(); +// }); +// } - const recoveryExported = localStorage.getItem('recoveryExported') === 'true'; - if (recoveryExported) { - const exportRecoveryBtn = popup.querySelector('.recovery-btn') as HTMLButtonElement; - if (exportRecoveryBtn) { - exportRecoveryBtn.disabled = true; - exportRecoveryBtn.style.opacity = '0.5'; - exportRecoveryBtn.style.cursor = 'not-allowed'; - } - } -} +// const recoveryExported = localStorage.getItem('recoveryExported') === 'true'; +// if (recoveryExported) { +// const exportRecoveryBtn = popup.querySelector('.recovery-btn') as HTMLButtonElement; +// if (exportRecoveryBtn) { +// exportRecoveryBtn.disabled = true; +// exportRecoveryBtn.style.opacity = '0.5'; +// exportRecoveryBtn.style.cursor = 'not-allowed'; +// } +// } +// } -private setupEventListeners(popup: HTMLElement): void { - // Gestionnaire pour la fermeture - const closeBtn = popup.querySelector('.close-popup'); - if (closeBtn) { - closeBtn.addEventListener('click', () => { - popup.style.display = 'none'; - }); - } +// private setupEventListeners(popup: HTMLElement): void { +// // Gestionnaire pour la fermeture +// const closeBtn = popup.querySelector('.close-popup'); +// if (closeBtn) { +// closeBtn.addEventListener('click', () => { +// popup.style.display = 'none'; +// }); +// } - // Gestionnaire pour l'upload d'avatar - const avatarUpload = popup.querySelector('#avatar-upload') as HTMLInputElement; - if (avatarUpload) { - avatarUpload.addEventListener('change', (e: Event) => { - const file = (e.target as HTMLInputElement).files?.[0]; - if (file) { - const reader = new FileReader(); - reader.onload = (e: ProgressEvent) => { - const result = e.target?.result as string; - // Mise à jour de l'avatar dans la preview et le popup - const popupAvatar = this.shadowRoot?.getElementById('popup-avatar-img') as HTMLImageElement; - const previewAvatar = this.shadowRoot?.querySelector('.preview-avatar') as HTMLImageElement; +// // Gestionnaire pour l'upload d'avatar +// const avatarUpload = popup.querySelector('#avatar-upload') as HTMLInputElement; +// if (avatarUpload) { +// avatarUpload.addEventListener('change', (e: Event) => { +// const file = (e.target as HTMLInputElement).files?.[0]; +// if (file) { +// const reader = new FileReader(); +// reader.onload = (e: ProgressEvent) => { +// const result = e.target?.result as string; +// // Mise à jour de l'avatar dans la preview et le popup +// const popupAvatar = this.shadowRoot?.getElementById('popup-avatar-img') as HTMLImageElement; +// const previewAvatar = this.shadowRoot?.querySelector('.preview-avatar') as HTMLImageElement; - if (popupAvatar) popupAvatar.src = result; - if (previewAvatar) previewAvatar.src = result; +// if (popupAvatar) popupAvatar.src = result; +// if (previewAvatar) previewAvatar.src = result; - localStorage.setItem('userAvatar', result); - }; - reader.readAsDataURL(file); - } - }); - } +// localStorage.setItem('userAvatar', result); +// }; +// reader.readAsDataURL(file); +// } +// }); +// } - // Gestionnaire pour l'upload de bannière - const bannerUpload = popup.querySelector('#banner-upload') as HTMLInputElement; - if (bannerUpload) { - bannerUpload.addEventListener('change', (e: Event) => { - const file = (e.target as HTMLInputElement).files?.[0]; - if (file) { - const reader = new FileReader(); - reader.onload = (e: ProgressEvent) => { - const result = e.target?.result as string; - // Mise à jour de la bannière dans la preview et le popup - const popupBanner = this.shadowRoot?.getElementById('popup-banner-img') as HTMLImageElement; - const previewBanner = this.shadowRoot?.querySelector('.preview-banner-img') as HTMLImageElement; +// // Gestionnaire pour l'upload de bannière +// const bannerUpload = popup.querySelector('#banner-upload') as HTMLInputElement; +// if (bannerUpload) { +// bannerUpload.addEventListener('change', (e: Event) => { +// const file = (e.target as HTMLInputElement).files?.[0]; +// if (file) { +// const reader = new FileReader(); +// reader.onload = (e: ProgressEvent) => { +// const result = e.target?.result as string; +// // Mise à jour de la bannière dans la preview et le popup +// const popupBanner = this.shadowRoot?.getElementById('popup-banner-img') as HTMLImageElement; +// const previewBanner = this.shadowRoot?.querySelector('.preview-banner-img') as HTMLImageElement; - if (popupBanner) popupBanner.src = result; - if (previewBanner) previewBanner.src = result; +// if (popupBanner) popupBanner.src = result; +// if (previewBanner) previewBanner.src = result; - localStorage.setItem('userBanner', result); - }; - reader.readAsDataURL(file); - } - }); - } +// localStorage.setItem('userBanner', result); +// }; +// reader.readAsDataURL(file); +// } +// }); +// } - // Gestionnaires pour les champs de texte - const nameInput = popup.querySelector('#userName') as HTMLInputElement; - const lastNameInput = popup.querySelector('#userLastName') as HTMLInputElement; +// // Gestionnaires pour les champs de texte +// const nameInput = popup.querySelector('#userName') as HTMLInputElement; +// const lastNameInput = popup.querySelector('#userLastName') as HTMLInputElement; - if (nameInput) { - nameInput.addEventListener('input', () => { - const newName = nameInput.value; - localStorage.setItem('userName', newName); - // Mise à jour du nom dans la preview - const previewName = this.shadowRoot?.querySelector('.preview-name'); - if (previewName) previewName.textContent = newName; - }); - } +// if (nameInput) { +// nameInput.addEventListener('input', () => { +// const newName = nameInput.value; +// localStorage.setItem('userName', newName); +// // Mise à jour du nom dans la preview +// const previewName = this.shadowRoot?.querySelector('.preview-name'); +// if (previewName) previewName.textContent = newName; +// }); +// } - if (lastNameInput) { - lastNameInput.addEventListener('input', () => { - const newLastName = lastNameInput.value; - localStorage.setItem('userLastName', newLastName); - // Mise à jour du nom de famille dans la preview - const previewLastName = this.shadowRoot?.querySelector('.preview-lastname'); - if (previewLastName) previewLastName.textContent = newLastName; - }); - } -} +// if (lastNameInput) { +// lastNameInput.addEventListener('input', () => { +// const newLastName = lastNameInput.value; +// localStorage.setItem('userLastName', newLastName); +// // Mise à jour du nom de famille dans la preview +// const previewLastName = this.shadowRoot?.querySelector('.preview-lastname'); +// if (previewLastName) previewLastName.textContent = newLastName; +// }); +// } +// } -private closeAvatarPopup(): void { - const popup = this.shadowRoot?.querySelector('.avatar-popup'); - if (popup) popup.remove(); -} +// private closeAvatarPopup(): void { +// const popup = this.shadowRoot?.querySelector('.avatar-popup'); +// if (popup) popup.remove(); +// } -private loadAvatar(): void { - const savedAvatar = localStorage.getItem('userAvatar'); - if (savedAvatar) { - const avatarImg = this.shadowRoot?.querySelector('.avatar') as HTMLImageElement; - if (avatarImg) { - avatarImg.src = savedAvatar; - } - } -} +// private loadAvatar(): void { +// const savedAvatar = localStorage.getItem('userAvatar'); +// if (savedAvatar) { +// const avatarImg = this.shadowRoot?.querySelector('.avatar') as HTMLImageElement; +// if (avatarImg) { +// avatarImg.src = savedAvatar; +// } +// } +// } -private loadUserInfo(): void { - const savedName = localStorage.getItem('userName'); - const savedLastName = localStorage.getItem('userLastName'); - const savedAvatar = localStorage.getItem('userAvatar'); - const savedBanner = localStorage.getItem('userBanner'); +// private loadUserInfo(): void { +// const savedName = localStorage.getItem('userName'); +// const savedLastName = localStorage.getItem('userLastName'); +// const savedAvatar = localStorage.getItem('userAvatar'); +// const savedBanner = localStorage.getItem('userBanner'); - // Mise à jour du nom dans la preview - if (savedName) { - const previewName = this.shadowRoot?.querySelector('.preview-name'); - if (previewName) { - previewName.textContent = savedName; - } - } +// // Mise à jour du nom dans la preview +// if (savedName) { +// const previewName = this.shadowRoot?.querySelector('.preview-name'); +// if (previewName) { +// previewName.textContent = savedName; +// } +// } - // Mise à jour du nom de famille dans la preview - if (savedLastName) { - const previewLastName = this.shadowRoot?.querySelector('.preview-lastname'); - if (previewLastName) { - previewLastName.textContent = savedLastName; - } - } +// // Mise à jour du nom de famille dans la preview +// if (savedLastName) { +// const previewLastName = this.shadowRoot?.querySelector('.preview-lastname'); +// if (previewLastName) { +// previewLastName.textContent = savedLastName; +// } +// } - // Mise à jour de l'avatar dans la preview - if (savedAvatar) { - const previewAvatar = this.shadowRoot?.querySelector('.preview-avatar') as HTMLImageElement; - if (previewAvatar) { - previewAvatar.src = savedAvatar; - } - } +// // Mise à jour de l'avatar dans la preview +// if (savedAvatar) { +// const previewAvatar = this.shadowRoot?.querySelector('.preview-avatar') as HTMLImageElement; +// if (previewAvatar) { +// previewAvatar.src = savedAvatar; +// } +// } - // Mise à jour de la bannière dans la preview - if (savedBanner) { - const previewBanner = this.shadowRoot?.querySelector('.preview-banner-img') as HTMLImageElement; - if (previewBanner) { - previewBanner.src = savedBanner; - } - } -} +// // Mise à jour de la bannière dans la preview +// if (savedBanner) { +// const previewBanner = this.shadowRoot?.querySelector('.preview-banner-img') as HTMLImageElement; +// if (previewBanner) { +// previewBanner.src = savedBanner; +// } +// } +// } -private updateNavbarName(name: string): void { - const nameElement = this.shadowRoot?.querySelector('.nav-wrapper .user-name'); - if (nameElement) { - nameElement.textContent = name; - } -} +// private updateNavbarName(name: string): void { +// const nameElement = this.shadowRoot?.querySelector('.nav-wrapper .user-name'); +// if (nameElement) { +// nameElement.textContent = name; +// } +// } -private updateNavbarLastName(lastName: string): void { - const lastNameElement = this.shadowRoot?.querySelector('.nav-wrapper .user-lastname'); - if (lastNameElement) { - lastNameElement.textContent = lastName; - } -} +// private updateNavbarLastName(lastName: string): void { +// const lastNameElement = this.shadowRoot?.querySelector('.nav-wrapper .user-lastname'); +// if (lastNameElement) { +// lastNameElement.textContent = lastName; +// } +// } -private updateProfilePreview(data: { - avatar?: string, - banner?: string, - name?: string, - lastName?: string -}): void { - if (data.avatar) { - const previewAvatar = this.shadowRoot?.querySelector('.preview-avatar') as HTMLImageElement; - if (previewAvatar) previewAvatar.src = data.avatar; - } +// private updateProfilePreview(data: { +// avatar?: string, +// banner?: string, +// name?: string, +// lastName?: string +// }): void { +// if (data.avatar) { +// const previewAvatar = this.shadowRoot?.querySelector('.preview-avatar') as HTMLImageElement; +// if (previewAvatar) previewAvatar.src = data.avatar; +// } - if (data.banner) { - const previewBanner = this.shadowRoot?.querySelector('.preview-banner-img') as HTMLImageElement; - if (previewBanner) previewBanner.src = data.banner; - } +// if (data.banner) { +// const previewBanner = this.shadowRoot?.querySelector('.preview-banner-img') as HTMLImageElement; +// if (previewBanner) previewBanner.src = data.banner; +// } - if (data.name) { - const previewName = this.shadowRoot?.querySelector('.preview-name'); - if (previewName) previewName.textContent = data.name; - } +// if (data.name) { +// const previewName = this.shadowRoot?.querySelector('.preview-name'); +// if (previewName) previewName.textContent = data.name; +// } - if (data.lastName) { - const previewLastName = this.shadowRoot?.querySelector('.preview-lastname'); - if (previewLastName) previewLastName.textContent = data.lastName; - } -} +// if (data.lastName) { +// const previewLastName = this.shadowRoot?.querySelector('.preview-lastname'); +// if (previewLastName) previewLastName.textContent = data.lastName; +// } +// } -private initializeEventListeners() { - this.shadowRoot?.addEventListener('DOMContentLoaded', () => { - this.showPairing(); - }); +// private initializeEventListeners() { +// this.shadowRoot?.addEventListener('DOMContentLoaded', () => { +// this.showPairing(); +// }); - const editableFields = this.shadowRoot?.querySelectorAll('.editable'); - if (editableFields) { - editableFields.forEach(field => { - field.addEventListener('click', () => { - if (!field.classList.contains('editing')) { - const currentValue = field.textContent || ''; - const input = document.createElement('input'); - input.type = 'text'; - input.value = currentValue; - input.className = 'edit-input'; +// const editableFields = this.shadowRoot?.querySelectorAll('.editable'); +// if (editableFields) { +// editableFields.forEach(field => { +// field.addEventListener('click', () => { +// if (!field.classList.contains('editing')) { +// const currentValue = field.textContent || ''; +// const input = document.createElement('input'); +// input.type = 'text'; +// input.value = currentValue; +// input.className = 'edit-input'; - field.textContent = ''; - field.appendChild(input); - field.classList.add('editing'); - input.focus(); - } - }); - }); - } +// field.textContent = ''; +// field.appendChild(input); +// field.classList.add('editing'); +// input.focus(); +// } +// }); +// }); +// } - const avatarInput = this.shadowRoot?.getElementById('avatar-upload') as HTMLInputElement; - if (avatarInput) { - avatarInput.addEventListener('change', this.handleAvatarUpload.bind(this)); - } -} +// const avatarInput = this.shadowRoot?.getElementById('avatar-upload') as HTMLInputElement; +// if (avatarInput) { +// avatarInput.addEventListener('change', this.handleAvatarUpload.bind(this)); +// } +// } -private showQRCodeModal(pairingId: string): void { - const modal = document.createElement('div'); - modal.className = 'qr-modal'; - modal.innerHTML = ` -
- × - QR Code Large -
${decodeURIComponent(pairingId)}
-
- `; +// private showQRCodeModal(pairingId: string): void { +// const modal = document.createElement('div'); +// modal.className = 'qr-modal'; +// modal.innerHTML = ` +//
+// × +// QR Code Large +//
${decodeURIComponent(pairingId)}
+//
+// `; - this.shadowRoot?.appendChild(modal); +// this.shadowRoot?.appendChild(modal); - const closeBtn = modal.querySelector('.close-qr-modal'); - closeBtn?.addEventListener('click', () => modal.remove()); - modal.addEventListener('click', (e) => { - if (e.target === modal) modal.remove(); - }); -} -} +// const closeBtn = modal.querySelector('.close-qr-modal'); +// closeBtn?.addEventListener('click', () => modal.remove()); +// modal.addEventListener('click', (e) => { +// if (e.target === modal) modal.remove(); +// }); +// } +// } -customElements.define('account-element', AccountElement); -export { AccountElement }; +// customElements.define('account-element', AccountElement); +// export { AccountElement }; diff --git a/src/pages/account/document-validation.ts b/src/pages/account/document-validation.ts index 0fe233a..2d5ecdd 100644 --- a/src/pages/account/document-validation.ts +++ b/src/pages/account/document-validation.ts @@ -1,321 +1,321 @@ -import { ProcessState } from '../../../pkg/sdk_client'; -import Services from '../../services/service'; +// import { ProcessState } from '../../../pkg/sdk_client'; +// import Services from '../../services/service'; -interface State { - file: File | null; - fileHash: string | null; - certificate: ProcessState | null; - commitmentHashes: string[]; -} +// interface State { +// file: File | null; +// fileHash: string | null; +// certificate: ProcessState | null; +// commitmentHashes: string[]; +// } -export interface Vin { - txid: string; // The txid of the previous transaction (being spent) - vout: number; // The output index in the previous tx - prevout: { - scriptpubkey: string; - scriptpubkey_asm: string; - scriptpubkey_type: string; - scriptpubkey_address: string; - value: number; - }; - scriptsig: string; - scriptsig_asm: string; - witness: string[]; - is_coinbase: boolean; - sequence: number; -} +// export interface Vin { +// txid: string; // The txid of the previous transaction (being spent) +// vout: number; // The output index in the previous tx +// prevout: { +// scriptpubkey: string; +// scriptpubkey_asm: string; +// scriptpubkey_type: string; +// scriptpubkey_address: string; +// value: number; +// }; +// scriptsig: string; +// scriptsig_asm: string; +// witness: string[]; +// is_coinbase: boolean; +// sequence: number; +// } -export interface TransactionInfo { - txid: string; - version: number; - locktime: number; - vin: Vin[]; - vout: any[]; - size: number; - weight: number; - fee: number; - status: { - confirmed: boolean; - block_height: number; - block_hash: string; - block_time: number; - }; -} +// export interface TransactionInfo { +// txid: string; +// version: number; +// locktime: number; +// vin: Vin[]; +// vout: any[]; +// size: number; +// weight: number; +// fee: number; +// status: { +// confirmed: boolean; +// block_height: number; +// block_hash: string; +// block_time: number; +// }; +// } -export function getDocumentValidation(container: HTMLElement) { - const state: State = { - file: null, - fileHash: null, - certificate: null, - commitmentHashes: [] - } +// export function getDocumentValidation(container: HTMLElement) { +// const state: State = { +// file: null, +// fileHash: null, +// certificate: null, +// commitmentHashes: [] +// } - container.innerHTML = ''; - container.style.cssText = ` - display: flex; - flex-direction: column; - justify-content: center; - align-items: center; - min-height: 100vh; - gap: 2rem; - `; +// container.innerHTML = ''; +// container.style.cssText = ` +// display: flex; +// flex-direction: column; +// justify-content: center; +// align-items: center; +// min-height: 100vh; +// gap: 2rem; +// `; - function createDropButton( - label: string, - onDrop: (file: File, updateVisuals: (file: File) => void) => void, - accept: string = '*/*' - ): HTMLElement { - const wrapper = document.createElement('div'); - wrapper.style.cssText = ` - width: 200px; - height: 100px; - border: 2px dashed #888; - border-radius: 8px; - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - cursor: pointer; - font-weight: bold; - background: #f8f8f8; - text-align: center; - padding: 0.5rem; - box-sizing: border-box; - `; +// function createDropButton( +// label: string, +// onDrop: (file: File, updateVisuals: (file: File) => void) => void, +// accept: string = '*/*' +// ): HTMLElement { +// const wrapper = document.createElement('div'); +// wrapper.style.cssText = ` +// width: 200px; +// height: 100px; +// border: 2px dashed #888; +// border-radius: 8px; +// display: flex; +// flex-direction: column; +// align-items: center; +// justify-content: center; +// cursor: pointer; +// font-weight: bold; +// background: #f8f8f8; +// text-align: center; +// padding: 0.5rem; +// box-sizing: border-box; +// `; - const title = document.createElement('div'); - title.textContent = label; +// const title = document.createElement('div'); +// title.textContent = label; - const filename = document.createElement('div'); - filename.style.cssText = ` - font-size: 0.85rem; - margin-top: 0.5rem; - color: #444; - word-break: break-word; - text-align: center; - `; +// const filename = document.createElement('div'); +// filename.style.cssText = ` +// font-size: 0.85rem; +// margin-top: 0.5rem; +// color: #444; +// word-break: break-word; +// text-align: center; +// `; - wrapper.appendChild(title); - wrapper.appendChild(filename); +// wrapper.appendChild(title); +// wrapper.appendChild(filename); - const updateVisuals = (file: File) => { - wrapper.style.borderColor = 'green'; - wrapper.style.background = '#e6ffed'; - filename.textContent = file.name; - }; +// const updateVisuals = (file: File) => { +// wrapper.style.borderColor = 'green'; +// wrapper.style.background = '#e6ffed'; +// filename.textContent = file.name; +// }; - // === Hidden file input === - const fileInput = document.createElement('input'); - fileInput.type = 'file'; - fileInput.accept = accept; - fileInput.style.display = 'none'; - document.body.appendChild(fileInput); +// // === Hidden file input === +// const fileInput = document.createElement('input'); +// fileInput.type = 'file'; +// fileInput.accept = accept; +// fileInput.style.display = 'none'; +// document.body.appendChild(fileInput); - fileInput.onchange = () => { - const file = fileInput.files?.[0]; - if (file) { - onDrop(file, updateVisuals); - fileInput.value = ''; // reset so same file can be re-selected - } - }; +// fileInput.onchange = () => { +// const file = fileInput.files?.[0]; +// if (file) { +// onDrop(file, updateVisuals); +// fileInput.value = ''; // reset so same file can be re-selected +// } +// }; - // === Handle drag-and-drop === - wrapper.ondragover = e => { - e.preventDefault(); - wrapper.style.background = '#e0e0e0'; - }; +// // === Handle drag-and-drop === +// wrapper.ondragover = e => { +// e.preventDefault(); +// wrapper.style.background = '#e0e0e0'; +// }; - wrapper.ondragleave = () => { - wrapper.style.background = '#f8f8f8'; - }; +// wrapper.ondragleave = () => { +// wrapper.style.background = '#f8f8f8'; +// }; - wrapper.ondrop = e => { - e.preventDefault(); - wrapper.style.background = '#f8f8f8'; +// wrapper.ondrop = e => { +// e.preventDefault(); +// wrapper.style.background = '#f8f8f8'; - const file = e.dataTransfer?.files?.[0]; - if (file) { - onDrop(file, updateVisuals); - } - }; +// const file = e.dataTransfer?.files?.[0]; +// if (file) { +// onDrop(file, updateVisuals); +// } +// }; - // === Handle click to open file manager === - wrapper.onclick = () => { - fileInput.click(); - }; +// // === Handle click to open file manager === +// wrapper.onclick = () => { +// fileInput.click(); +// }; - return wrapper; - } +// return wrapper; +// } - const fileDropButton = createDropButton('Drop file', async (file, updateVisuals) => { - try { - state.file = file; - updateVisuals(file); - console.log('Loaded file:', state.file); - checkReady(); - } catch (err) { - alert('Failed to drop the file.'); - console.error(err); - } - }); +// const fileDropButton = createDropButton('Drop file', async (file, updateVisuals) => { +// try { +// state.file = file; +// updateVisuals(file); +// console.log('Loaded file:', state.file); +// checkReady(); +// } catch (err) { +// alert('Failed to drop the file.'); +// console.error(err); +// } +// }); - const certDropButton = createDropButton('Drop certificate', async (file, updateVisuals) => { - try { - const text = await file.text(); - const json = JSON.parse(text); - if ( - typeof json === 'object' && - json !== null && - typeof json.pcd_commitment === 'object' && - typeof json.state_id === 'string' - ) { - state.certificate = json as ProcessState; +// const certDropButton = createDropButton('Drop certificate', async (file, updateVisuals) => { +// try { +// const text = await file.text(); +// const json = JSON.parse(text); +// if ( +// typeof json === 'object' && +// json !== null && +// typeof json.pcd_commitment === 'object' && +// typeof json.state_id === 'string' +// ) { +// state.certificate = json as ProcessState; - state.commitmentHashes = Object.values(json.pcd_commitment).map((h: string) => - h.toLowerCase() - ); +// state.commitmentHashes = Object.values(json.pcd_commitment).map((h: string) => +// h.toLowerCase() +// ); - updateVisuals(file); - console.log('Loaded certificate, extracted hashes:', state.commitmentHashes); - checkReady(); - } else { - alert('Invalid certificate structure.'); - } - } catch (err) { - alert('Failed to parse certificate JSON.'); - console.error(err); - } - }); +// updateVisuals(file); +// console.log('Loaded certificate, extracted hashes:', state.commitmentHashes); +// checkReady(); +// } else { +// alert('Invalid certificate structure.'); +// } +// } catch (err) { +// alert('Failed to parse certificate JSON.'); +// console.error(err); +// } +// }); - const buttonRow = document.createElement('div'); - buttonRow.style.display = 'flex'; - buttonRow.style.gap = '2rem'; - buttonRow.appendChild(fileDropButton); - buttonRow.appendChild(certDropButton); +// const buttonRow = document.createElement('div'); +// buttonRow.style.display = 'flex'; +// buttonRow.style.gap = '2rem'; +// buttonRow.appendChild(fileDropButton); +// buttonRow.appendChild(certDropButton); - container.appendChild(buttonRow); +// container.appendChild(buttonRow); - async function checkReady() { - if (state.file && state.certificate && state.commitmentHashes.length > 0) { - // We take the commited_in and all pcd_commitment keys to reconstruct all the possible hash - const fileBlob = { - type: state.file.type, - data: new Uint8Array(await state.file.arrayBuffer()) - }; - const service = await Services.getInstance(); - const commitedIn = state.certificate.commited_in; - if (!commitedIn) return; - const [prevTxid, prevTxVout] = commitedIn.split(':'); - const processId = state.certificate.process_id; - const stateId = state.certificate.state_id; - const process = await service.getProcess(processId); - if (!process) return; +// async function checkReady() { +// if (state.file && state.certificate && state.commitmentHashes.length > 0) { +// // We take the commited_in and all pcd_commitment keys to reconstruct all the possible hash +// const fileBlob = { +// type: state.file.type, +// data: new Uint8Array(await state.file.arrayBuffer()) +// }; +// const service = await Services.getInstance(); +// const commitedIn = state.certificate.commited_in; +// if (!commitedIn) return; +// const [prevTxid, prevTxVout] = commitedIn.split(':'); +// const processId = state.certificate.process_id; +// const stateId = state.certificate.state_id; +// const process = await service.getProcess(processId); +// if (!process) return; - // Get the transaction that comes right after the commited_in - const nextState = service.getNextStateAfterId(process, stateId); +// // Get the transaction that comes right after the commited_in +// const nextState = service.getNextStateAfterId(process, stateId); - if (!nextState) { - alert(`❌ Validation failed: No next state, is the state you're trying to validate commited?`); - return; - } +// if (!nextState) { +// alert(`❌ Validation failed: No next state, is the state you're trying to validate commited?`); +// return; +// } - const [outspentTxId, _] = nextState.commited_in.split(':'); - console.log(outspentTxId); +// const [outspentTxId, _] = nextState.commited_in.split(':'); +// console.log(outspentTxId); - // Check that the commitment transaction exists, and that it commits to the state id +// // Check that the commitment transaction exists, and that it commits to the state id - const txInfo = await fetchTransaction(outspentTxId); - if (!txInfo) { - console.error(`Validation error: Can't fetch new state commitment transaction`); - alert(`❌ Validation failed: invalid or non existent commited_in for state ${stateId}.`); - return; - } +// const txInfo = await fetchTransaction(outspentTxId); +// if (!txInfo) { +// console.error(`Validation error: Can't fetch new state commitment transaction`); +// alert(`❌ Validation failed: invalid or non existent commited_in for state ${stateId}.`); +// return; +// } - // We must check that this transaction indeed spend the commited_in we have in the certificate - let found = false; - for (const vin of txInfo.vin) { - if (vin.txid === prevTxid) { - found = true; - break; - } - } +// // We must check that this transaction indeed spend the commited_in we have in the certificate +// let found = false; +// for (const vin of txInfo.vin) { +// if (vin.txid === prevTxid) { +// found = true; +// break; +// } +// } - if (!found) { - console.error(`Validation error: new state doesn't spend previous state commitment transaction`); - alert('❌ Validation failed: Unconsistent commitment transactions history.'); - return; - } +// if (!found) { +// console.error(`Validation error: new state doesn't spend previous state commitment transaction`); +// alert('❌ Validation failed: Unconsistent commitment transactions history.'); +// return; +// } - // set found back to false for next check - found = false; +// // set found back to false for next check +// found = false; - // is the state_id commited in the transaction? - for (const vout of txInfo.vout) { - console.log(vout); - if (vout.scriptpubkey_type && vout.scriptpubkey_type === 'op_return') { - found = true; - } else { - continue; - } +// // is the state_id commited in the transaction? +// for (const vout of txInfo.vout) { +// console.log(vout); +// if (vout.scriptpubkey_type && vout.scriptpubkey_type === 'op_return') { +// found = true; +// } else { +// continue; +// } - if (vout.scriptpubkey_asm) { - const hash = extractHexFromScriptAsm(vout.scriptpubkey_asm); - if (hash) { - if (hash !== stateId) { - console.error(`Validation error: expected stateId ${stateId}, got ${hash}`); - alert('❌ Validation failed: Transaction does not commit to that state.'); - return; - } - } - } - } +// if (vout.scriptpubkey_asm) { +// const hash = extractHexFromScriptAsm(vout.scriptpubkey_asm); +// if (hash) { +// if (hash !== stateId) { +// console.error(`Validation error: expected stateId ${stateId}, got ${hash}`); +// alert('❌ Validation failed: Transaction does not commit to that state.'); +// return; +// } +// } +// } +// } - if (!found) { - alert('❌ Validation failed: Transaction does not contain data.'); - return; - } +// if (!found) { +// alert('❌ Validation failed: Transaction does not contain data.'); +// return; +// } - // set found back to false for next check - found = false; +// // set found back to false for next check +// found = false; - for (const label of Object.keys(state.certificate.pcd_commitment)) { - // Compute the hash for this label - console.log(`Computing hash with label ${label}`) - const fileHex = service.getHashForFile(commitedIn, label, fileBlob); - console.log(`Found hash ${fileHex}`); - found = state.commitmentHashes.includes(fileHex); - if (found) break; - } +// for (const label of Object.keys(state.certificate.pcd_commitment)) { +// // Compute the hash for this label +// console.log(`Computing hash with label ${label}`) +// const fileHex = service.getHashForFile(commitedIn, label, fileBlob); +// console.log(`Found hash ${fileHex}`); +// found = state.commitmentHashes.includes(fileHex); +// if (found) break; +// } - if (found) { - alert('✅ Validation successful: file hash found in pcd_commitment.'); - } else { - alert('❌ Validation failed: file hash NOT found in pcd_commitment.'); - } - } - } +// if (found) { +// alert('✅ Validation successful: file hash found in pcd_commitment.'); +// } else { +// alert('❌ Validation failed: file hash NOT found in pcd_commitment.'); +// } +// } +// } - async function fetchTransaction(txid: string): Promise { - const url = `https://mempool.4nkweb.com/api/tx/${txid}`; +// async function fetchTransaction(txid: string): Promise { +// const url = `https://mempool.4nkweb.com/api/tx/${txid}`; - const response = await fetch(url); - if (!response.ok) { - throw new Error(`Failed to fetch outspend status: ${response.statusText}`); - } +// const response = await fetch(url); +// if (!response.ok) { +// throw new Error(`Failed to fetch outspend status: ${response.statusText}`); +// } - const outspend: TransactionInfo = await response.json(); - return outspend; - } +// const outspend: TransactionInfo = await response.json(); +// return outspend; +// } - function extractHexFromScriptAsm(scriptAsm: string): string | null { - const parts = scriptAsm.trim().split(/\s+/); - const last = parts[parts.length - 1]; +// function extractHexFromScriptAsm(scriptAsm: string): string | null { +// const parts = scriptAsm.trim().split(/\s+/); +// const last = parts[parts.length - 1]; - // Basic validation: must be 64-char hex (32 bytes) - if (/^[0-9a-fA-F]{64}$/.test(last)) { - return last.toLowerCase(); - } +// // Basic validation: must be 64-char hex (32 bytes) +// if (/^[0-9a-fA-F]{64}$/.test(last)) { +// return last.toLowerCase(); +// } - return null; - } -} +// return null; +// } +// } diff --git a/src/pages/account/key-value-section.ts b/src/pages/account/key-value-section.ts index a43bfad..e26eced 100644 --- a/src/pages/account/key-value-section.ts +++ b/src/pages/account/key-value-section.ts @@ -1,196 +1,196 @@ -import { ValidationRule, RoleDefinition } from '../../../pkg/sdk_client'; -import { showValidationRuleModal } from '../../components/validation-rule-modal/validation-rule-modal'; +// import { ValidationRule, RoleDefinition } from '../../../pkg/sdk_client'; +// import { showValidationRuleModal } from '../../components/validation-rule-modal/validation-rule-modal'; -export function createKeyValueSection(title: string, id: string, isRoleSection = false) { - const section = document.createElement('div'); - section.id = id; - section.style.cssText = 'margin-bottom: 2rem; background: #fff; padding: 1rem; border-radius: 0.5rem; box-shadow: 0 1px 3px rgba(0,0,0,0.1);'; +// export function createKeyValueSection(title: string, id: string, isRoleSection = false) { +// const section = document.createElement('div'); +// section.id = id; +// section.style.cssText = 'margin-bottom: 2rem; background: #fff; padding: 1rem; border-radius: 0.5rem; box-shadow: 0 1px 3px rgba(0,0,0,0.1);'; - const titleEl = document.createElement('h2'); - titleEl.textContent = title; - titleEl.style.cssText = 'font-size: 1.25rem; font-weight: bold; margin-bottom: 1rem;'; - section.appendChild(titleEl); +// const titleEl = document.createElement('h2'); +// titleEl.textContent = title; +// titleEl.style.cssText = 'font-size: 1.25rem; font-weight: bold; margin-bottom: 1rem;'; +// section.appendChild(titleEl); - const rowContainer = document.createElement('div'); - section.appendChild(rowContainer); +// const rowContainer = document.createElement('div'); +// section.appendChild(rowContainer); - const addBtn = document.createElement('button'); - addBtn.textContent = '+ Add Row'; - addBtn.style.cssText = ` - margin-top: 1rem; - padding: 0.5rem 1rem; - border: 1px solid #888; - border-radius: 0.375rem; - background-color: #f9f9f9; - cursor: pointer; - `; - section.appendChild(addBtn); +// const addBtn = document.createElement('button'); +// addBtn.textContent = '+ Add Row'; +// addBtn.style.cssText = ` +// margin-top: 1rem; +// padding: 0.5rem 1rem; +// border: 1px solid #888; +// border-radius: 0.375rem; +// background-color: #f9f9f9; +// cursor: pointer; +// `; +// section.appendChild(addBtn); - const roleRowStates: { - roleNameInput: HTMLInputElement; - membersInput: HTMLInputElement; - storagesInput: HTMLInputElement; - validationRules: ValidationRule[]; - }[] = []; - type fileBlob = { - type: string, - data: Uint8Array - }; - const nonRoleRowStates: { - keyInput: HTMLInputElement, - valueInput: HTMLInputElement, - fileInput: HTMLInputElement, - fileBlob: fileBlob | null - }[] = []; +// const roleRowStates: { +// roleNameInput: HTMLInputElement; +// membersInput: HTMLInputElement; +// storagesInput: HTMLInputElement; +// validationRules: ValidationRule[]; +// }[] = []; +// type fileBlob = { +// type: string, +// data: Uint8Array +// }; +// const nonRoleRowStates: { +// keyInput: HTMLInputElement, +// valueInput: HTMLInputElement, +// fileInput: HTMLInputElement, +// fileBlob: fileBlob | null +// }[] = []; - const inputStyle = 'flex: 1; height: 2.5rem; padding: 0.5rem; border: 1px solid #ccc; border-radius: 0.375rem;'; +// const inputStyle = 'flex: 1; height: 2.5rem; padding: 0.5rem; border: 1px solid #ccc; border-radius: 0.375rem;'; - const createRow = () => { - const row = document.createElement('div'); - row.style.cssText = 'display: flex; gap: 1rem; margin-bottom: 0.5rem; align-items: center;'; +// const createRow = () => { +// const row = document.createElement('div'); +// row.style.cssText = 'display: flex; gap: 1rem; margin-bottom: 0.5rem; align-items: center;'; - const deleteBtn = document.createElement('button'); - deleteBtn.textContent = '🗑️'; - deleteBtn.style.cssText = 'background: none; border: none; font-size: 1.2rem; cursor: pointer;'; - deleteBtn.onclick = () => { - row.remove(); - updateDeleteButtons(); - }; +// const deleteBtn = document.createElement('button'); +// deleteBtn.textContent = '🗑️'; +// deleteBtn.style.cssText = 'background: none; border: none; font-size: 1.2rem; cursor: pointer;'; +// deleteBtn.onclick = () => { +// row.remove(); +// updateDeleteButtons(); +// }; - if (isRoleSection) { - const roleName = document.createElement('input'); - const members = document.createElement('input'); - const storages = document.createElement('input'); +// if (isRoleSection) { +// const roleName = document.createElement('input'); +// const members = document.createElement('input'); +// const storages = document.createElement('input'); - roleName.placeholder = 'Role name'; - members.placeholder = 'members'; - storages.placeholder = 'storages'; - [roleName, members, storages].forEach(input => { - input.type = 'text'; - input.style.cssText = inputStyle; - }); +// roleName.placeholder = 'Role name'; +// members.placeholder = 'members'; +// storages.placeholder = 'storages'; +// [roleName, members, storages].forEach(input => { +// input.type = 'text'; +// input.style.cssText = inputStyle; +// }); - const ruleButton = document.createElement('button'); - ruleButton.textContent = 'Add Validation Rule'; - ruleButton.style.cssText = 'padding: 0.3rem 0.75rem; border: 1px solid #ccc; border-radius: 0.375rem; background: #f0f0f0; cursor: pointer;'; +// const ruleButton = document.createElement('button'); +// ruleButton.textContent = 'Add Validation Rule'; +// ruleButton.style.cssText = 'padding: 0.3rem 0.75rem; border: 1px solid #ccc; border-radius: 0.375rem; background: #f0f0f0; cursor: pointer;'; - const rules: ValidationRule[] = []; - ruleButton.onclick = () => { - showValidationRuleModal(rule => { - rules.push(rule); - ruleButton.textContent = `Rules (${rules.length})`; - }); - }; +// const rules: ValidationRule[] = []; +// ruleButton.onclick = () => { +// showValidationRuleModal(rule => { +// rules.push(rule); +// ruleButton.textContent = `Rules (${rules.length})`; +// }); +// }; - row.appendChild(roleName); - row.appendChild(members); - row.appendChild(storages); - row.appendChild(ruleButton); - row.appendChild(deleteBtn); +// row.appendChild(roleName); +// row.appendChild(members); +// row.appendChild(storages); +// row.appendChild(ruleButton); +// row.appendChild(deleteBtn); - roleRowStates.push({ roleNameInput: roleName, membersInput: members, storagesInput: storages, validationRules: rules }); - } else { - const fileInput = document.createElement('input'); - fileInput.type = 'file'; - fileInput.style.display = 'none'; - fileInput.onchange = async () => { - const file = fileInput.files?.[0]; - if (!file) return; +// roleRowStates.push({ roleNameInput: roleName, membersInput: members, storagesInput: storages, validationRules: rules }); +// } else { +// const fileInput = document.createElement('input'); +// fileInput.type = 'file'; +// fileInput.style.display = 'none'; +// fileInput.onchange = async () => { +// const file = fileInput.files?.[0]; +// if (!file) return; - const buffer = await file.arrayBuffer(); - const uint8 = new Uint8Array(buffer); +// const buffer = await file.arrayBuffer(); +// const uint8 = new Uint8Array(buffer); - rowState.fileBlob = { - type: file.type, - data: uint8, - }; +// rowState.fileBlob = { +// type: file.type, +// data: uint8, +// }; - valueInput.value = `📄 ${file.name}`; - valueInput.disabled = true; - attachBtn.textContent = `📎 ${file.name}`; - }; +// valueInput.value = `📄 ${file.name}`; +// valueInput.disabled = true; +// attachBtn.textContent = `📎 ${file.name}`; +// }; - const attachBtn = document.createElement('button'); - attachBtn.textContent = '📎 Attach'; - attachBtn.style.cssText = 'padding: 0.3rem 0.75rem; border: 1px solid #ccc; border-radius: 0.375rem; background: #f0f0f0; cursor: pointer;'; - attachBtn.onclick = () => fileInput.click(); +// const attachBtn = document.createElement('button'); +// attachBtn.textContent = '📎 Attach'; +// attachBtn.style.cssText = 'padding: 0.3rem 0.75rem; border: 1px solid #ccc; border-radius: 0.375rem; background: #f0f0f0; cursor: pointer;'; +// attachBtn.onclick = () => fileInput.click(); - const keyInput = document.createElement('input'); - const valueInput = document.createElement('input'); +// const keyInput = document.createElement('input'); +// const valueInput = document.createElement('input'); - const rowState = { - keyInput, - valueInput, - fileInput, - fileBlob: null as fileBlob | null - }; - nonRoleRowStates.push(rowState); +// const rowState = { +// keyInput, +// valueInput, +// fileInput, +// fileBlob: null as fileBlob | null +// }; +// nonRoleRowStates.push(rowState); - keyInput.placeholder = 'Key'; - valueInput.placeholder = 'Value'; - [keyInput, valueInput].forEach(input => { - input.type = 'text'; - input.style.cssText = inputStyle; - }); +// keyInput.placeholder = 'Key'; +// valueInput.placeholder = 'Value'; +// [keyInput, valueInput].forEach(input => { +// input.type = 'text'; +// input.style.cssText = inputStyle; +// }); - row.appendChild(keyInput); - row.appendChild(valueInput); +// row.appendChild(keyInput); +// row.appendChild(valueInput); - row.appendChild(attachBtn); - row.appendChild(fileInput); +// row.appendChild(attachBtn); +// row.appendChild(fileInput); - row.appendChild(deleteBtn); - } +// row.appendChild(deleteBtn); +// } - rowContainer.appendChild(row); - updateDeleteButtons(); - }; +// rowContainer.appendChild(row); +// updateDeleteButtons(); +// }; - const updateDeleteButtons = () => { - const rows = Array.from(rowContainer.children); - rows.forEach(row => { - const btn = row.querySelector('button:last-child') as HTMLButtonElement; - if (rows.length === 1) { - btn.disabled = true; - btn.style.visibility = 'hidden'; - } else { - btn.disabled = false; - btn.style.visibility = 'visible'; - } - }); - }; +// const updateDeleteButtons = () => { +// const rows = Array.from(rowContainer.children); +// rows.forEach(row => { +// const btn = row.querySelector('button:last-child') as HTMLButtonElement; +// if (rows.length === 1) { +// btn.disabled = true; +// btn.style.visibility = 'hidden'; +// } else { +// btn.disabled = false; +// btn.style.visibility = 'visible'; +// } +// }); +// }; - createRow(); - addBtn.addEventListener('click', createRow); +// createRow(); +// addBtn.addEventListener('click', createRow); - return { - element: section, - getData: () => { - if (isRoleSection) { - const data: Record = {}; - for (const row of roleRowStates) { - const key = row.roleNameInput.value.trim(); - if (!key) continue; - data[key] = { - members: row.membersInput.value.split(',').map(x => x.trim()).filter(Boolean), - storages: row.storagesInput.value.split(',').map(x => x.trim()).filter(Boolean), - validation_rules: row.validationRules - }; - } - return data; - } else { - const data: Record = {}; - for (const row of nonRoleRowStates) { - const key = row.keyInput.value.trim(); - if (!key) continue; - if (row.fileBlob) { - data[key] = row.fileBlob; - } else { - data[key] = row.valueInput.value.trim(); - } - } - return data; - } - } - }; -} +// return { +// element: section, +// getData: () => { +// if (isRoleSection) { +// const data: Record = {}; +// for (const row of roleRowStates) { +// const key = row.roleNameInput.value.trim(); +// if (!key) continue; +// data[key] = { +// members: row.membersInput.value.split(',').map(x => x.trim()).filter(Boolean), +// storages: row.storagesInput.value.split(',').map(x => x.trim()).filter(Boolean), +// validation_rules: row.validationRules +// }; +// } +// return data; +// } else { +// const data: Record = {}; +// for (const row of nonRoleRowStates) { +// const key = row.keyInput.value.trim(); +// if (!key) continue; +// if (row.fileBlob) { +// data[key] = row.fileBlob; +// } else { +// data[key] = row.valueInput.value.trim(); +// } +// } +// return data; +// } +// } +// }; +// } diff --git a/src/pages/account/process-creation.ts b/src/pages/account/process-creation.ts index 586a108..2fa7f3f 100644 --- a/src/pages/account/process-creation.ts +++ b/src/pages/account/process-creation.ts @@ -1,91 +1,91 @@ -import { createKeyValueSection } from './key-value-section'; -import { loadValidationRuleModal } from '../../components/validation-rule-modal/validation-rule-modal'; -import Services from '../../services/service'; -import { RoleDefinition } from '../../../pkg/sdk_client'; +// import { createKeyValueSection } from './key-value-section'; +// import { loadValidationRuleModal } from '../../components/validation-rule-modal/validation-rule-modal'; +// import Services from '../../services/service'; +// import { RoleDefinition } from '../../../pkg/sdk_client'; -export async function getProcessCreation(container: HTMLElement) { - await loadValidationRuleModal(); +// export async function getProcessCreation(container: HTMLElement) { +// await loadValidationRuleModal(); - container.style.display = 'block'; - container.innerHTML = `
Process Creation
`; - const privateSec = createKeyValueSection('Private Data', 'private-section'); - const publicSec = createKeyValueSection('Public Data', 'public-section'); - const rolesSec = createKeyValueSection('Roles', 'roles-section', true); +// container.style.display = 'block'; +// container.innerHTML = `
Process Creation
`; +// const privateSec = createKeyValueSection('Private Data', 'private-section'); +// const publicSec = createKeyValueSection('Public Data', 'public-section'); +// const rolesSec = createKeyValueSection('Roles', 'roles-section', true); - container.appendChild(privateSec.element); - container.appendChild(publicSec.element); - container.appendChild(rolesSec.element); +// container.appendChild(privateSec.element); +// container.appendChild(publicSec.element); +// container.appendChild(rolesSec.element); - const btn = document.createElement('button'); - btn.textContent = 'Create Process'; - btn.style.cssText = ` - display: block; - margin: 2rem auto 0; - padding: 0.75rem 2rem; - font-size: 1rem; - font-weight: bold; - background-color: #4f46e5; - color: white; - border: none; - border-radius: 0.5rem; - cursor: pointer; - `; +// const btn = document.createElement('button'); +// btn.textContent = 'Create Process'; +// btn.style.cssText = ` +// display: block; +// margin: 2rem auto 0; +// padding: 0.75rem 2rem; +// font-size: 1rem; +// font-weight: bold; +// background-color: #4f46e5; +// color: white; +// border: none; +// border-radius: 0.5rem; +// cursor: pointer; +// `; - btn.onclick = async () => { - const privateData = privateSec.getData(); - const publicData = publicSec.getData(); - const roles = rolesSec.getData() as Record; +// btn.onclick = async () => { +// const privateData = privateSec.getData(); +// const publicData = publicSec.getData(); +// const roles = rolesSec.getData() as Record; - console.log('Private:', privateData); - console.log('Public:', publicData); - console.log('Roles:', roles); +// console.log('Private:', privateData); +// console.log('Public:', publicData); +// console.log('Roles:', roles); - const service = await Services.getInstance(); +// const service = await Services.getInstance(); - const createProcessResult = await service.createProcess(privateData, publicData, roles); - const processId = createProcessResult.updated_process!.process_id; - const stateId = createProcessResult.updated_process!.current_process.states[0].state_id; - await service.handleApiReturn(createProcessResult); +// const createProcessResult = await service.createProcess(privateData, publicData, roles); +// const processId = createProcessResult.updated_process!.process_id; +// const stateId = createProcessResult.updated_process!.current_process.states[0].state_id; +// await service.handleApiReturn(createProcessResult); - // Now we want to validate the update and register the first state of our new process - const updateProcessResult = await service.createPrdUpdate(processId, stateId); - await service.handleApiReturn(createProcessResult); +// // Now we want to validate the update and register the first state of our new process +// const updateProcessResult = await service.createPrdUpdate(processId, stateId); +// await service.handleApiReturn(createProcessResult); - const approveChangeResult = await service.approveChange(processId, stateId); - await service.handleApiReturn(approveChangeResult); - if (approveChangeResult) { - const process = await service.getProcess(processId); - let newState = service.getStateFromId(process, stateId); - if (!newState) return; - for (const label of Object.keys(newState.keys)) { - const hash = newState.pcd_commitment[label]; - const encryptedData = await service.getBlobFromDb(hash); - const filename = `${label}-${hash.slice(0,8)}.bin`; +// const approveChangeResult = await service.approveChange(processId, stateId); +// await service.handleApiReturn(approveChangeResult); +// if (approveChangeResult) { +// const process = await service.getProcess(processId); +// let newState = service.getStateFromId(process, stateId); +// if (!newState) return; +// for (const label of Object.keys(newState.keys)) { +// const hash = newState.pcd_commitment[label]; +// const encryptedData = await service.getBlobFromDb(hash); +// const filename = `${label}-${hash.slice(0,8)}.bin`; - const blob = new Blob([encryptedData], { type: "application/octet-stream" }); - const link = document.createElement("a"); - link.href = URL.createObjectURL(blob); - link.download = filename; - link.click(); +// const blob = new Blob([encryptedData], { type: "application/octet-stream" }); +// const link = document.createElement("a"); +// link.href = URL.createObjectURL(blob); +// link.download = filename; +// link.click(); - setTimeout(() => URL.revokeObjectURL(link.href), 1000); - } +// setTimeout(() => URL.revokeObjectURL(link.href), 1000); +// } - await service.generateProcessPdf(processId, newState); +// await service.generateProcessPdf(processId, newState); - // Add processId to the state we export - newState['process_id'] = processId; - const blob = new Blob([JSON.stringify(newState, null, 2)], { type: 'application/json' }); - const url = URL.createObjectURL(blob); +// // Add processId to the state we export +// newState['process_id'] = processId; +// const blob = new Blob([JSON.stringify(newState, null, 2)], { type: 'application/json' }); +// const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = `process_${processId}_${stateId}.json`; - a.click(); +// const a = document.createElement('a'); +// a.href = url; +// a.download = `process_${processId}_${stateId}.json`; +// a.click(); - URL.revokeObjectURL(url); // Clean up - } - }; +// URL.revokeObjectURL(url); // Clean up +// } +// }; - container.appendChild(btn); -} +// container.appendChild(btn); +// } diff --git a/src/pages/account/process.ts b/src/pages/account/process.ts index 10eaeb6..fa5f8b9 100644 --- a/src/pages/account/process.ts +++ b/src/pages/account/process.ts @@ -1,66 +1,66 @@ -export function createProcessTab(container: HTMLElement, processes: { name: string, publicData: Record }[]): HTMLElement { - container.id = 'process-tab'; - container.style.display = 'block'; - container.style.cssText = 'padding: 1.5rem;'; +// export function createProcessTab(container: HTMLElement, processes: { name: string, publicData: Record }[]): HTMLElement { +// container.id = 'process-tab'; +// container.style.display = 'block'; +// container.style.cssText = 'padding: 1.5rem;'; - const title = document.createElement('h2'); - title.textContent = 'Processes'; - title.style.cssText = 'font-size: 1.5rem; font-weight: bold; margin-bottom: 1rem;'; - container.appendChild(title); +// const title = document.createElement('h2'); +// title.textContent = 'Processes'; +// title.style.cssText = 'font-size: 1.5rem; font-weight: bold; margin-bottom: 1rem;'; +// container.appendChild(title); - processes.forEach(proc => { - const card = document.createElement('div'); - card.style.cssText = 'margin-bottom: 1rem; padding: 1rem; border: 1px solid #ddd; border-radius: 0.5rem; background: #fff;'; +// processes.forEach(proc => { +// const card = document.createElement('div'); +// card.style.cssText = 'margin-bottom: 1rem; padding: 1rem; border: 1px solid #ddd; border-radius: 0.5rem; background: #fff;'; - const nameEl = document.createElement('h3'); - nameEl.textContent = proc.name; - nameEl.style.cssText = 'font-size: 1.2rem; font-weight: bold; margin-bottom: 0.5rem;'; - card.appendChild(nameEl); +// const nameEl = document.createElement('h3'); +// nameEl.textContent = proc.name; +// nameEl.style.cssText = 'font-size: 1.2rem; font-weight: bold; margin-bottom: 0.5rem;'; +// card.appendChild(nameEl); - const dataList = document.createElement('div'); - for (const [key, value] of Object.entries(proc.publicData)) { - const item = document.createElement('div'); - item.style.cssText = 'margin-bottom: 0.5rem;'; +// const dataList = document.createElement('div'); +// for (const [key, value] of Object.entries(proc.publicData)) { +// const item = document.createElement('div'); +// item.style.cssText = 'margin-bottom: 0.5rem;'; - const label = document.createElement('strong'); - label.textContent = key + ': '; - item.appendChild(label); +// const label = document.createElement('strong'); +// label.textContent = key + ': '; +// item.appendChild(label); - // Let's trim the quotes - const trimmed = value.replace(/^'|'$/g, ''); - let parsed; - try { - parsed = JSON.parse(trimmed); - } catch (_) { - parsed = trimmed; - } +// // Let's trim the quotes +// const trimmed = value.replace(/^'|'$/g, ''); +// let parsed; +// try { +// parsed = JSON.parse(trimmed); +// } catch (_) { +// parsed = trimmed; +// } - if (parsed && typeof parsed === 'object') { - const saveBtn = document.createElement('button'); - saveBtn.textContent = '💾 Save as JSON'; - saveBtn.style.cssText = 'margin-left: 0.5rem; padding: 0.25rem 0.5rem; border: 1px solid #ccc; border-radius: 0.375rem; background: #f0f0f0; cursor: pointer;'; - saveBtn.onclick = () => { - const blob = new Blob([JSON.stringify(parsed, null, 2)], { type: 'application/json' }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = `${proc.name}_${key}.json`; - a.click(); - URL.revokeObjectURL(url); - }; - item.appendChild(saveBtn); - } else { - const span = document.createElement('span'); - span.textContent = String(parsed); - item.appendChild(span); - } +// if (parsed && typeof parsed === 'object') { +// const saveBtn = document.createElement('button'); +// saveBtn.textContent = '💾 Save as JSON'; +// saveBtn.style.cssText = 'margin-left: 0.5rem; padding: 0.25rem 0.5rem; border: 1px solid #ccc; border-radius: 0.375rem; background: #f0f0f0; cursor: pointer;'; +// saveBtn.onclick = () => { +// const blob = new Blob([JSON.stringify(parsed, null, 2)], { type: 'application/json' }); +// const url = URL.createObjectURL(blob); +// const a = document.createElement('a'); +// a.href = url; +// a.download = `${proc.name}_${key}.json`; +// a.click(); +// URL.revokeObjectURL(url); +// }; +// item.appendChild(saveBtn); +// } else { +// const span = document.createElement('span'); +// span.textContent = String(parsed); +// item.appendChild(span); +// } - dataList.appendChild(item); - } +// dataList.appendChild(item); +// } - card.appendChild(dataList); - container.appendChild(card); - }); +// card.appendChild(dataList); +// container.appendChild(card); +// }); - return container; -} +// return container; +// }