/*
* @title show comment on this URL
* @description このページに言及しているNostrのコメントを表示する
* @include https://*
* @license CC0 1.0
* @require
*/
(() => {
const relayUrl = 'wss://yabu.me/';
const getEvent = (url) => {
return new Promise((resolve) => {
const ws = new WebSocket(relayUrl);
const subscription_id = 'getcommentofthispage';
let res = [];
ws.onopen = () => {
const req = ['REQ', subscription_id, { kinds: [1], '#r': [url] }];
ws.send(JSON.stringify(req));
};
ws.onmessage = (e) => {
const msg = JSON.parse(e.data);
switch (msg[0]) {
case 'EVENT':
res.push(msg[2]);
break;
case 'EOSE':
ws.send(JSON.stringify(['CLOSE', subscription_id]));
ws.close();
resolve(res);
break;
default:
console.log(msg);
break;
}
};
ws.onerror = () => {
console.error('failed to connect');
};
});
};
const tag = (name, props = {}, children = []) => {
const e = Object.assign(document.createElement(name), props);
if (typeof props.style === 'object') Object.assign(e.style, props.style);
(children.forEach ? children : [children]).forEach((c) => e.appendChild(c));
return e;
};
const main = async () => {
let events;
try {
events = await getEvent(location.href.replace(/#.*$/, ''));
} catch (error) {
console.warn(error);
return;
}
const comments = events.slice(0, 10).map((ev) => ev.content);
console.log(comments);
const div = document.createElement('div');
div.style.position = 'fixed';
div.style.top = '10px';
div.style.right = '10px';
div.style.whiteSpace = 'pre-wrap';
div.addEventListener('click', () => {
div.style.display = 'none';
});
document.body.append(div);
for (const comment of comments) {
const p = document.createElement('p');
const text = document.createTextNode(comment);
div.append(
tag(
'p',
{
style:
'width: 30em; min-height: 3em; background-color: rgba(200, 200, 200, 0.95); border-bottom: 1px solid #333'
},
[text]
)
);
}
};
main();
})();