Merge pull request #85 from waku-org/html-examples

[relay-js/store-js] bump js-waku to next
This commit is contained in:
fryorcraken.eth 2022-08-31 15:47:12 +10:00 committed by GitHub
commit 13e24a68d4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 122 additions and 155 deletions

View File

@ -2,9 +2,9 @@
<html lang='en'>
<head>
<meta charset='UTF-8' />
<meta content='width=device-width, initial-scale=1.0' name='viewport' />
<title>JS-Waku Chat</title>
<meta charset='UTF-8'/>
<meta content='width=device-width, initial-scale=1.0' name='viewport'/>
<title>JS-Waku Chat</title>
</head>
<body>
@ -13,114 +13,88 @@
<div id='status'></div>
<input id='textInput' placeholder='Type your message here' type='text'>
<button id='sendButton' onclick='sendMessage();' type='button'>Send Message
<button id='sendButton' type='button'>Send Message
</button>
<div><h1>Messages</h1></div>
<div id='messages'></div>
<script
src='https://unpkg.com/js-waku@latest/build/umd/js-waku.min.bundle.js'></script>
<script>
/**
* Demonstrate usage of js-waku in the browser. Use relay, gossip sub protocol to send and receive messages.
* Recommended payload is protobuf. Using simple utf-8 string for demo purposes only.
*
* - API documentation: https://js-waku.wakuconnect.dev/
* - Guides: https://docs.wakuconnect.dev/
*
* Note: open this HTML in two different browsers to experience decentralized communication.
* A node will not show its own messages, this can be changed by modifying the `Waku.create` call:
*
* Waku.create({
* bootstrap: {default: true}, libp2p: {
* config: {
* pubsub: {
* enabled: true,
* emitSelf: true,
* },
* },
* },
* })
*
*/
<script type='module'>
/**
* Demonstrate usage of js-waku in the browser. Use relay, gossip sub protocol to send and receive messages.
* Recommended payload is protobuf. Using simple utf-8 string for demo purposes only.
*/
const { Waku, WakuMessage } = jswaku;
const statusDiv = document.getElementById('status');
const messagesDiv = document.getElementById('messages');
const textInput = document.getElementById('textInput');
const sendButton = document.getElementById('sendButton');
import {
waitForRemotePeer,
WakuMessage
} from 'https://unpkg.com/js-waku@next/bundle/index.js';
import {
createWaku
} from 'https://unpkg.com/js-waku@next/bundle/lib/create_waku.js'
// Keep it disabled until Waku node is ready
textInput.disabled = true;
sendButton.disabled = true;
const statusDiv = document.getElementById('status');
const messagesDiv = document.getElementById('messages');
const textInput = document.getElementById('textInput');
const sendButton = document.getElementById('sendButton');
// Every Waku Message has a content topic that categorizes it.
// It is always encoded in clear text.
// Recommendation: `/dapp-name/version/functionality/codec`
// We recommend to use protobuf as codec (`proto`), this demo uses utf-8
// for simplicity's sake.
const contentTopic = '/relay-demo/1/message/utf-8';
// Keep it disabled until Waku node is ready
textInput.disabled = true;
sendButton.disabled = true;
// Function to be used to send the text input over Waku.
let sendMessage = () => {
};
// Every Waku Message has a content topic that categorizes it.
// It is always encoded in clear text.
// Recommendation: `/dapp-name/version/functionality/codec`
// We recommend to use protobuf as codec (`proto`), this demo uses utf-8
// for simplicity's sake.
const contentTopic = '/relay-demo/1/message/utf-8';
try {
statusDiv.innerHTML = '<p>Starting</p>';
try {
statusDiv.innerHTML = '<p>Starting</p>';
// Create and starts a Waku node.
// `default: true` bootstraps by connecting to pre-defined/hardcoded Waku nodes.
// We are currently working on migrating this method to DNS Discovery.
//
// https://js-waku.wakuconnect.dev/classes/waku.Waku.html#create
Waku.create({ bootstrap: { default: true } }).catch(e => {
statusDiv.innerHTML = 'Error';
console.log('Issue starting Waku node', e);
}
).then(wakuNode => {
// Had a hook to process all incoming messages on a specified content topic.
//
// https://js-waku.wakuconnect.dev/classes/waku_relay.WakuRelay.html#addObserver
wakuNode.relay.addObserver((wakuMessage) => {
// Checks there is a payload on the message.
// Waku Message is encoded in protobuf, in proto v3 fields are always optional.
// Create and starts a Waku node.
// `default: true` bootstraps by connecting to pre-defined/hardcoded Waku nodes.
// We are currently working on migrating this method to DNS Discovery.
//
// https://js-waku.wakuconnect.dev/classes/waku_message.WakuMessage.html#payload
if (!wakuMessage.payload)
return;
// https://js-waku.wakuconnect.dev/classes/waku.Waku.html#create
const waku = await createWaku({defaultBootstrap: true});
await waku.start();
// Helper method to decode the payload to utf-8. A production dApp should
// use `wakuMessage.payload` (Uint8Array) which enables encoding a data
// structure of their choice.
// Had a hook to process all incoming messages on a specified content topic.
//
// https://js-waku.wakuconnect.dev/classes/waku_message.WakuMessage.html#payloadAsUtf8
const text = wakuMessage.payloadAsUtf8;
messagesDiv.innerHTML = `<p>${text}</p><br />` + messagesDiv.innerHTML;
}, [contentTopic]);
// https://js-waku.wakuconnect.dev/classes/waku_relay.WakuRelay.html#addObserver
waku.relay.addObserver((wakuMessage) => {
statusDiv.innerHTML = '<p>Connecting to a peer</p>';
// Checks there is a payload on the message.
// Waku Message is encoded in protobuf, in proto v3 fields are always optional.
//
// https://js-waku.wakuconnect.dev/classes/waku_message.WakuMessage.html#payload
if (!wakuMessage.payload)
return;
// Best effort method that waits for the Waku node to be connected to remote
// waku nodes (peers) and for appropriate handshakes to be done.
//
// https://js-waku.wakuconnect.dev/classes/waku.Waku.html#waitForRemotePeer
wakuNode.waitForRemotePeer()
.catch((e) => {
statusDiv.innerHTML = 'Failed to connect to peers: ' + e.toString();
})
.then(() => {
// Helper method to decode the payload to utf-8. A production dApp should
// use `wakuMessage.payload` (Uint8Array) which enables encoding a data
// structure of their choice.
//
// https://js-waku.wakuconnect.dev/classes/waku_message.WakuMessage.html#payloadAsUtf8
const text = wakuMessage.payloadAsUtf8;
messagesDiv.innerHTML = `<p>${text}</p><br />` + messagesDiv.innerHTML;
}, [contentTopic]);
// We are now connected to a remote peer, let's define the `sendMessage`
// function that sends the text input over Waku Relay, the gossipsub
// protocol.
sendMessage = () => {
statusDiv.innerHTML = '<p>Connecting to a peer</p>';
// Best effort method that waits for the Waku node to be connected to remote
// waku nodes (peers) and for appropriate handshakes to be done.
//
// https://js-waku.wakuconnect.dev/classes/waku.Waku.html#waitForRemotePeer
await waitForRemotePeer(waku);
// We are now connected to a remote peer, let's define the `sendMessage`
// function that sends the text input over Waku Relay, the gossipsub
// protocol.
sendButton.onclick = async () => {
const text = textInput.value;
// Reset the text input.
textInput.value = null;
// Helper functions are available to create a Waku Message.
// These functions also provide native symmetric, asymmetric encryption,
@ -131,32 +105,26 @@
// serialize a data structure.
//
// https://js-waku.wakuconnect.dev/classes/waku_message.WakuMessage.html#fromUtf8String
WakuMessage.fromUtf8String(text, contentTopic).catch(e => console.log('Error encoding message', e)).then(
wakuMessage => {
// Once the message is constructed, send it over Waku Relay.
//
// https://js-waku.wakuconnect.dev/classes/waku_relay.WakuRelay.html#send
wakuNode.relay.send(wakuMessage).catch((e) => {
console.log('Error sending message', e);
}).then(() => {
console.log('Message sent', text);
});
}
);
const wakuMessage = await WakuMessage.fromUtf8String(text, contentTopic);
// Once the message is constructed, send it over Waku Relay.
//
// https://js-waku.wakuconnect.dev/classes/waku_relay.WakuRelay.html#send
await waku.relay.send(wakuMessage);
console.log('Message sent!');
};
// Reset the text input.
textInput.value = null;
};
// Ready to send & receive messages, enable text input.
textInput.disabled = false;
sendButton.disabled = false;
statusDiv.innerHTML = '<p>Ready!</p>';
// Ready to send & receive messages, enable text input.
textInput.disabled = false;
sendButton.disabled = false;
statusDiv.innerHTML = '<p>Ready!</p>';
});
});
} catch (e) {
timestampDiv.innerHTML = 'Failed to start application';
console.log(e);
}
} catch (e) {
statusDiv.innerHTML = 'Failed to start application';
console.log(e);
}
</script>
</body>

View File

@ -4,17 +4,23 @@
<head>
<meta charset='UTF-8' />
<meta content='width=device-width, initial-scale=1.0' name='viewport' />
<title>JS-Waku unpkg example</title>
<title>JS-Waku store script tag example</title>
</head>
<body>
<div><h1>Timestamp of latest relay ping</h1></div>
<div><h1>Timestamp of latest message seen in store</h1></div>
<div id='timestamp'></div>
<script
src='https://unpkg.com/js-waku@latest/build/umd/js-waku.min.bundle.js'></script>
<script>
<script type='module'>
import {
waitForRemotePeer,
Protocols
} from 'https://unpkg.com/js-waku@next/bundle/index.js';
import {
createWaku
} from 'https://unpkg.com/js-waku@next/bundle/lib/create_waku.js'
/**
* This example demonstrates how to use the js-waku minified bundle
* available on unpkg.com.
@ -25,41 +31,39 @@
const timestampDiv = document.getElementById('timestamp');
try {
timestampDiv.innerHTML = '<p>Creating waku.</p>';
const node = await createWaku({ defaultBootstrap: true });
timestampDiv.innerHTML = '<p>Starting waku.</p>';
jswaku.Waku.create({ bootstrap: { default: true } }).catch(e => {
timestampDiv.innerHTML = 'Failed to create Waku: ' + e.toString();
await node.start();
timestampDiv.innerHTML = '<p>Connecting to a peer.</p>';
await waitForRemotePeer(node, [Protocols.Store]);
timestampDiv.innerHTML = '<p>Retrieving messages.</p>';
const callback = (wakuMessages) => {
// Messages are ordered with oldest first
// even with page direction `backward`
const latestFirst = wakuMessages.reverse();
const latestMessage = latestFirst[0];
if (latestMessage) {
timestampDiv.innerHTML = latestMessage.timestamp;
} else {
timestampDiv.innerHTML = '<p>No message available, go to <a href="https://js-waku.wakuconnect.dev/examples/web-chat/">web-chat</a> to send a message</p>';
}
).then(waku => {
timestampDiv.innerHTML = '<p>Connecting to a peer.</p>';
waku.waitForRemotePeer()
.catch((e) => {
timestampDiv.innerHTML = 'Failed to connect to peers' + e.toString();
})
.then(() => {
timestampDiv.innerHTML = '<p>Retrieving messages.</p>';
const callback = (wakuMessages) => {
// Messages are ordered with oldest first
// even with page direction `backward`
const latestFirst = wakuMessages.reverse();
const latestMessage = latestFirst[0];
if (latestMessage) {
timestampDiv.innerHTML = latestMessage.timestamp;
} else {
timestampDiv.innerHTML = '<p>No ping message available</p>';
}
// When returning true, `queryHistory` stops retrieving pages
// In our case, we only want one message, hence one page.
return true;
};
// When returning true, `queryHistory` stops retrieving pages
// In our case, we only want one message, hence one page.
return true;
};
const startTime = new Date();
// Only retrieve a week of messages
startTime.setTime(Date.now() - 7 * 24 * 60 * 60 * 1000);
const startTime = new Date();
// Only retrieve a week of messages
startTime.setTime(Date.now() - 7 * 24 * 60 * 60 * 1000);
waku.store
.queryHistory(['/relay-ping/1/ping/null'], {
await node.store
.queryHistory([], {
callback,
pageDirection: 'backward',
pageSize: 1,
@ -67,14 +71,9 @@
startTime,
endTime: new Date()
}
})
.catch((e) => {
timestampDiv.innerHTML = 'Failed to retrieve messages' + e.toString();
});
});
});
} catch (e) {
timestampDiv.innerHTML = 'Failed to start application' + e.toString();
timestampDiv.innerHTML = 'Error encountered: ' + e.toString();
}
</script>
</body>