|
| 1 | +import './style.css' |
| 2 | +import { multiaddr } from '@multiformats/multiaddr' |
| 3 | +import { setup as libp2pSetup } from './libp2p' |
| 4 | +import { CID } from 'multiformats/cid' |
| 5 | + |
| 6 | +localStorage.debug = '*' |
| 7 | + |
| 8 | +declare global { |
| 9 | + interface Window { |
| 10 | + fetchBtn: HTMLButtonElement |
| 11 | + connectBtn: HTMLButtonElement |
| 12 | + peerInput: HTMLInputElement |
| 13 | + cidInput: HTMLInputElement |
| 14 | + statusEl: HTMLParagraphElement |
| 15 | + downloadEl: HTMLAnchorElement |
| 16 | + downloadCidWrapperEl: HTMLDivElement |
| 17 | + connlistWrapperEl: HTMLDivElement |
| 18 | + connlistEl: HTMLUListElement |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +(async function () { |
| 23 | + const { libp2p, bitswap } = await libp2pSetup() |
| 24 | + window.connectBtn.onclick = async () => { |
| 25 | + const ma = multiaddr(window.peerInput.value) |
| 26 | + await libp2p.dial(ma) |
| 27 | + } |
| 28 | + |
| 29 | + libp2p.connectionManager.addEventListener('peer:connect', (_connection) => { |
| 30 | + updateConnList() |
| 31 | + }) |
| 32 | + libp2p.connectionManager.addEventListener('peer:disconnect', (_connection) => { |
| 33 | + updateConnList() |
| 34 | + }) |
| 35 | + |
| 36 | + function updateConnList () { |
| 37 | + const addrs = libp2p.getConnections().map(c => c.remoteAddr.toString()) |
| 38 | + if (addrs.length > 0) { |
| 39 | + window.downloadCidWrapperEl.hidden = false |
| 40 | + window.connlistWrapperEl.hidden = false |
| 41 | + window.connlistEl.innerHTML = '' |
| 42 | + addrs.forEach(a => { |
| 43 | + const li = document.createElement('li') |
| 44 | + li.innerText = a |
| 45 | + window.connlistEl.appendChild(li) |
| 46 | + }) |
| 47 | + } else { |
| 48 | + window.downloadCidWrapperEl.hidden = true |
| 49 | + window.connlistWrapperEl.hidden = true |
| 50 | + window.connlistEl.innerHTML = '' |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + window.fetchBtn.onclick = async () => { |
| 55 | + const c = CID.parse(window.cidInput.value) |
| 56 | + window.statusEl.hidden = false |
| 57 | + const val = await bitswap.get(c) |
| 58 | + window.statusEl.hidden = true |
| 59 | + |
| 60 | + window.downloadEl.href = window.URL.createObjectURL(new Blob([val], { type: 'bytes' })) |
| 61 | + window.downloadEl.hidden = false |
| 62 | + } |
| 63 | +// eslint-disable-next-line no-console |
| 64 | +})().catch(err => console.error(err)) |
0 commit comments