Skip to content

Commit

Permalink
feat: pull in Adin changes
Browse files Browse the repository at this point in the history
  • Loading branch information
SgtPooki committed Mar 17, 2023
1 parent 8f7944c commit 722f487
Show file tree
Hide file tree
Showing 4 changed files with 126 additions and 65 deletions.
131 changes: 68 additions & 63 deletions src/app.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import React, { useState, useRef } from 'react';
import type { Helia } from '@helia/interface'
import { AddOptions, unixfs } from '@helia/unixfs'
import { CID } from 'multiformats/cid'

import { getHelia } from './get-helia.ts'
import ipfsLogo from './ipfs-logo.svg'
import Form from './form';

enum COLORS {
default = '#fff',
Expand All @@ -21,8 +23,8 @@ interface OutputLine {
function App() {
const [output, setOutput] = useState<OutputLine[]>([]);
const [helia, setHelia] = useState<Helia | null>(null);
const [fileContent, setFileContent] = useState('');
const [fileName, setFileName] = useState('');
const [fileCid, setFileCid] = useState('');


const terminalEl = useRef<HTMLDivElement>(null);

Expand All @@ -43,39 +45,77 @@ function App() {
terminalEl.current?.scroll?.({ top: terminalEl.current?.scrollHeight, behavior: 'smooth' })
}

const store = async (name, content) => {
let node: Helia | null = helia;
// const store = async (name, content) => {
// let node: Helia | null = helia;

// if (!helia) {
// showStatus('Creating Helia node...', COLORS.active)

// node = await getHelia()

// setHelia(node)
// }

// if (node == null) {
// throw new Error('Helia node is not available')
// }

// const peerId = node.libp2p.peerId
// console.log(peerId)
// showStatus(`My ID is ${peerId}`, COLORS.active, peerId.toString())

// const encoder = new TextEncoder()

// // const fileToAdd = {
// // path: `${name}`,
// // content: encoder.encode(content)
// // }

// const fs = unixfs(node)

// showStatus(`Adding file ${fileToAdd.path}...`, COLORS.active)
// const cid = await fs.addFile(fileToAdd, node.blockstore as Partial<AddOptions>)

// showStatus(`Added to ${cid}`, COLORS.success, cid.toString())
// showStatus('Reading file...', COLORS.active)
// const decoder = new TextDecoder()
// let text = ''

if (!helia) {
// for await (const chunk of fs.cat(cid)) {
// text += decoder.decode(chunk, {
// stream: true
// })
// }

// showStatus(`\u2514\u2500 ${name} ${text}`)
// showStatus(`Preview: https://ipfs.io/ipfs/${cid}`, COLORS.success)
// }

const getFile = async (fileCid) => {
let node = helia;

if (!helia || node == null) {
showStatus('Creating Helia node...', COLORS.active)

node = await getHelia()

globalThis.helia = node
setHelia(node)
}

if (node == null) {
throw new Error('Helia node is not available')
}
// if (node == null) {
// throw new Error('Helia node is not available')
// }


const peerId = node.libp2p.peerId
console.log(peerId)
showStatus(`Connecting to ${peerId}...`, COLORS.active, peerId.toString())

const encoder = new TextEncoder()

const fileToAdd = {
path: `${name}`,
content: encoder.encode(content)
}
showStatus(`My ID is ${peerId}`, COLORS.active, peerId.toString())

const fs = unixfs(node)
const cid = CID.parse(fileCid)

showStatus(`Adding file ${fileToAdd.path}...`, COLORS.active)
const cid = await fs.addFile(fileToAdd, node.blockstore as Partial<AddOptions>)

showStatus(`Added to ${cid}`, COLORS.success, cid.toString())
showStatus('Reading file...', COLORS.active)
showStatus(`Reading UnixFS text file ${cid}...`, COLORS.active)
const decoder = new TextDecoder()
let text = ''

Expand All @@ -85,25 +125,21 @@ function App() {
})
}

showStatus(`\u2514\u2500 ${name} ${text}`)
showStatus(`\u2514\u2500 CID: ${cid}`)
showStatus(`Preview: https://ipfs.io/ipfs/${cid}`, COLORS.success)
}

const handleSubmit = async (e) => {
e.preventDefault();

try {
if (fileName == null || fileName.trim() === '') {
throw new Error('File name is missing...')
}

if ((fileContent == null || fileContent.trim() === '')) {
throw new Error('File content is missing...')
if (fileCid == null || fileCid.trim() === '') {
throw new Error('File CID is missing...')
}

await store(fileName, fileContent)
await getFile(fileCid)
} catch (err) {
showStatus((err as Error).message, COLORS.error)
showStatus((err as Error)?.message, COLORS.error)
}
}

Expand All @@ -116,39 +152,8 @@ function App() {
</header>

<main className="pa4-l bg-snow mw7 mv5 center pa4">
<h1 className="pa0 f2 ma0 mb4 aqua tc">Add data to Helia from the browser</h1>

<form id="add-file" onSubmit={handleSubmit}>
<label htmlFor="file-name" className="f5 ma0 pb2 aqua fw4 db">Name</label>
<input
className="input-reset bn black-80 bg-white pa3 w-100 mb3"
id="file-name"
name="file-name"
type="text"
placeholder="file.txt"
required
value={fileName} onChange={(e) => setFileName(e.target.value)}
/>

<label htmlFor="file-content" className="f5 ma0 pb2 aqua fw4 db">Content</label>
<input
className="input-reset bn black-80 bg-white pa3 w-100 mb3 ft"
id="file-content"
name="file-content"
type="text"
placeholder="Hello world"
required
value={fileContent} onChange={(e) => setFileContent(e.target.value)}
/>

<button
className="button-reset pv3 tc bn bg-animate bg-black-80 hover-bg-aqua white pointer w-100"
id="add-submit"
type="submit"
>
Add file
</button>
</form>
<h1 className="pa0 f2 ma0 mb4 aqua tc">Fetch content from IPFS using Helia</h1>
<Form handleSubmit={handleSubmit} fileCid={fileCid} setFileCid={setFileCid} />

<h3>Output</h3>

Expand Down
24 changes: 24 additions & 0 deletions src/form.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import React from 'react'

export default ({ handleSubmit, fileCid, setFileCid }): JSX.Element => (
<form id="add-file" onSubmit={handleSubmit}>
<label htmlFor="file-name" className="f5 ma0 pb2 aqua fw4 db">CID</label>
<input
className="input-reset bn black-80 bg-white pa3 w-100 mb3"
id="file-name"
name="file-name"
type="text"
placeholder="bafk..."
required
value={fileCid} onChange={(e) => setFileCid(e.target.value)}
/>

<button
className="button-reset pv3 tc bn bg-animate bg-black-80 hover-bg-aqua white pointer w-100"
id="add-submit"
type="submit"
>
Fetch
</button>
</form>
)
31 changes: 30 additions & 1 deletion src/get-helia.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export async function getHelia (): Promise<Helia> {
// use default api settings
protocol: "https",
port: 443,
host: "node0.delegate.ipfs.io",
host: "node3.delegate.ipfs.io",
})

// libp2p is the networking layer that underpins Helia
Expand All @@ -41,6 +41,35 @@ export async function getHelia (): Promise<Helia> {
],
peerRouters: [delegatedPeerRouting(delegatedClient)],
contentRouters: [delegatedContentRouting(delegatedClient)],
/**
* @see https://github.com/libp2p/js-libp2p/blob/master/doc/CONFIGURATION.md#configuring-dialing
*/
// dialer: {
// dialTimeout: 120000,
// },
/**
* @see https://github.com/libp2p/js-libp2p/blob/master/doc/CONFIGURATION.md#configuring-connection-manager
*/
connectionManager: {
// Auto connect to discovered peers (limited by ConnectionManager minConnections)
autoDial: true,
// maxConnections: 10,
// minConnections: 0,
// pollInterval: 2000,
},
/**
* @see https://github.com/libp2p/js-libp2p/blob/master/doc/CONFIGURATION.md#configuring-peerstore
*/
// peerStore: {
// // persistence: true,
// /**
// * The threshold number represents the maximum number of "dirty peers" allowed in the PeerStore, i.e. peers that
// * are not updated in the datastore. In this context, browser nodes should use a threshold of 1, since they
// * might not "stop" properly in several scenarios and the PeerStore might end up with unflushed records when the
// * window is closed.
// */
// threshold: 1,
// },
})

// create a Helia node
Expand Down
5 changes: 4 additions & 1 deletion webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,10 @@ const dev = {
port: 3000
},

plugins: []
plugins: [
// Only update what has changed on hot reload
new webpack.HotModuleReplacementPlugin()
]
}

/**
Expand Down

0 comments on commit 722f487

Please sign in to comment.