refactor: function to es6 arrow functions

so that it doesnt depend on function hoisting.
pull/72/head
OFF0 2 years ago
parent bbfa4ae545
commit aec72b6c62
Signed by: offbyn
GPG Key ID: 94A2F643C51F37FA

@ -14,27 +14,6 @@ import {getMetadata, handleMetadata} from './profiles';
// curl -H 'accept: application/nostr+json' https://relay.nostr.ch/ // curl -H 'accept: application/nostr+json' https://relay.nostr.ch/
function onEvent(evt: Event, relay: string) {
switch (evt.kind) {
case 0:
handleMetadata(evt, relay);
break;
case 1:
handleTextNote(evt, relay);
break;
case 2:
handleRecommendServer(evt, relay);
break;
case 3:
// handleContactList(evt, relay);
break;
case 7:
handleReaction(evt, relay);
default:
// console.log(`TODO: add support for event kind ${evt.kind}`/*, evt*/)
}
}
type EventWithNip19 = Event & { type EventWithNip19 = Event & {
nip19: { nip19: {
note: string; note: string;
@ -48,6 +27,62 @@ type EventRelayMap = {
}; };
const eventRelayMap: EventRelayMap = {}; // eventId: [relay1, relay2] const eventRelayMap: EventRelayMap = {}; // eventId: [relay1, relay2]
type EventWithNip19AndReplyTo = EventWithNip19 & {
replyTo: string;
};
const replyList: Array<EventWithNip19AndReplyTo> = [];
const createTextNote = (evt: EventWithNip19, relay: string) => {
const {host, img, name, time, userName} = getMetadata(evt, relay);
const replies = replyList.filter(({replyTo}) => replyTo === evt.id);
// const isLongContent = evt.content.trimRight().length > 280;
// const content = isLongContent ? evt.content.slice(0, 280) : evt.content;
const reactions = getReactions(evt.id);
const didReact = reactions.length && !!reactions.find(reaction => reaction.pubkey === config.pubkey);
const replyFeed: Array<HTMLElement> = replies[0] ? replies.sort(sortByCreatedAt).map(e => setViewElem(e.id, createTextNote(e, relay))) : [];
const [content, {firstLink}] = parseTextContent(evt.content);
const buttons = elem('div', {className: 'buttons'}, [
elem('button', {name: 'reply', type: 'button'}, [
elem('img', {height: 24, width: 24, src: '/assets/comment.svg'})
]),
elem('button', {name: 'star', type: 'button'}, [
elem('img', {
alt: didReact ? '✭' : '✩', // ♥
height: 24, width: 24,
src: `/assets/${didReact ? 'star-fill' : 'star'}.svg`,
title: getReactionContents(evt.id).join(' '),
}),
elem('small', {data: {reactions: ''}}, reactions.length || ''),
]),
]);
const body = elem('div', {className: 'mbox-body'}, [
elem('header', {
className: 'mbox-header',
title: `User: ${userName}\n${time}\n\nUser pubkey: ${evt.pubkey}\n\nRelay: ${host}\n\nEvent-id: ${evt.id}
${evt.tags.length ? `\nTags ${JSON.stringify(evt.tags)}\n` : ''}
${evt.content}`
}, [
elem('a', {className: `mbox-username${name ? ' mbox-kind0-name' : ''}`, href: `/${evt.nip19.npub}`}, name || userName),
' ',
elem('a', {href: `/${evt.nip19.note}`}, elem('time', {dateTime: time.toISOString()}, formatTime(time))),
]),
elem('div', {/* data: isLongContent ? {append: evt.content.slice(280)} : null*/}, [
...content,
(firstLink && validatePow(evt)) ? linkPreview(firstLink, evt.id, relay) : null,
]),
buttons,
]);
if (localStorage.getItem('reply_to') === evt.id) {
openWriteInput(buttons, evt.id);
}
return elemArticle([
elem('div', {className: 'mbox-img'}, img),
body,
...(replies[0] ? [elem('div', {className: 'mobx-replies'}, replyFeed.reverse())] : []),
], {data: {id: evt.id, pubkey: evt.pubkey, relay}});
};
const renderNote = ( const renderNote = (
evt: EventWithNip19, evt: EventWithNip19,
i: number, i: number,
@ -84,36 +119,22 @@ const renderFeed = bounce(() => {
.forEach(renderNote); .forEach(renderNote);
}, 17); // (16.666 rounded, an arbitrary value to limit updates to max 60x per s) }, 17); // (16.666 rounded, an arbitrary value to limit updates to max 60x per s)
function handleTextNote(evt: Event, relay: string) { const renderReply = (evt: EventWithNip19AndReplyTo, relay: string) => {
if (eventRelayMap[evt.id]) { const parent = getViewElem(evt.replyTo);
eventRelayMap[evt.id] = [...(eventRelayMap[evt.id]), relay]; // TODO: just push? if (!parent) { // root article has not been rendered
} else { return;
eventRelayMap[evt.id] = [relay];
const evtWithNip19 = {
nip19: {
note: nip19.noteEncode(evt.id),
npub: nip19.npubEncode(evt.pubkey),
},
...evt
};
if (evt.tags.some(hasEventTag)) {
handleReply(evtWithNip19, relay);
} else {
textNoteList.push(evtWithNip19);
}
} }
if (!getViewElem(evt.id)) { let replyContainer = parent.querySelector('.mobx-replies');
renderFeed(); if (!replyContainer) {
replyContainer = elem('div', {className: 'mobx-replies'});
parent.append(replyContainer);
} }
} const reply = createTextNote(evt, relay);
replyContainer.append(reply);
type EventWithNip19AndReplyTo = EventWithNip19 & { setViewElem(evt.id, reply);
replyTo: string; };
}
const replyList: Array<EventWithNip19AndReplyTo> = [];
function handleReply(evt: EventWithNip19, relay: string) { const handleReply = (evt: EventWithNip19, relay: string) => {
if ( if (
getViewElem(evt.id) // already rendered probably received from another relay getViewElem(evt.id) // already rendered probably received from another relay
|| evt.tags.some(isMention) // ignore mentions for now || evt.tags.some(isMention) // ignore mentions for now
@ -128,22 +149,30 @@ function handleReply(evt: EventWithNip19, relay: string) {
const evtWithReplyTo = {replyTo, ...evt}; const evtWithReplyTo = {replyTo, ...evt};
replyList.push(evtWithReplyTo); replyList.push(evtWithReplyTo);
renderReply(evtWithReplyTo, relay); renderReply(evtWithReplyTo, relay);
} };
function renderReply(evt: EventWithNip19AndReplyTo, relay: string) { const handleTextNote = (evt: Event, relay: string) => {
const parent = getViewElem(evt.replyTo); if (eventRelayMap[evt.id]) {
if (!parent) { // root article has not been rendered eventRelayMap[evt.id] = [...(eventRelayMap[evt.id]), relay]; // TODO: just push?
return; } else {
eventRelayMap[evt.id] = [relay];
const evtWithNip19 = {
nip19: {
note: nip19.noteEncode(evt.id),
npub: nip19.npubEncode(evt.pubkey),
},
...evt,
};
if (evt.tags.some(hasEventTag)) {
handleReply(evtWithNip19, relay);
} else {
textNoteList.push(evtWithNip19);
}
} }
let replyContainer = parent.querySelector('.mobx-replies'); if (!getViewElem(evt.id)) {
if (!replyContainer) { renderFeed();
replyContainer = elem('div', {className: 'mobx-replies'});
parent.append(replyContainer);
} }
const reply = createTextNote(evt, relay); };
replyContainer.append(reply);
setViewElem(evt.id, reply);
}
config.rerenderFeed = () => { config.rerenderFeed = () => {
clearView(); clearView();
@ -156,58 +185,22 @@ setInterval(() => {
}); });
}, 10000); }, 10000);
const renderRecommendServer = (evt: Event, relay: string) => {
function createTextNote(evt: EventWithNip19, relay: string) { const {img, name, time, userName} = getMetadata(evt, relay);
const {host, img, name, time, userName} = getMetadata(evt, relay); const body = elem('div', {className: 'mbox-body', title: dateTime.format(time)}, [
const replies = replyList.filter(({replyTo}) => replyTo === evt.id); elem('header', {className: 'mbox-header'}, [
// const isLongContent = evt.content.trimRight().length > 280; elem('small', {}, [
// const content = isLongContent ? evt.content.slice(0, 280) : evt.content; elem('strong', {}, userName)
const reactions = getReactions(evt.id); ]),
const didReact = reactions.length && !!reactions.find(reaction => reaction.pubkey === config.pubkey);
const replyFeed: Array<HTMLElement> = replies[0] ? replies.sort(sortByCreatedAt).map(e => setViewElem(e.id, createTextNote(e, relay))) : [];
const [content, {firstLink}] = parseTextContent(evt.content);
const buttons = elem('div', {className: 'buttons'}, [
elem('button', {name: 'reply', type: 'button'}, [
elem('img', {height: 24, width: 24, src: '/assets/comment.svg'})
]),
elem('button', {name: 'star', type: 'button'}, [
elem('img', {
alt: didReact ? '✭' : '✩', // ♥
height: 24, width: 24,
src: `/assets/${didReact ? 'star-fill' : 'star'}.svg`,
title: getReactionContents(evt.id).join(' '),
}),
elem('small', {data: {reactions: ''}}, reactions.length || ''),
]),
]);
const body = elem('div', {className: 'mbox-body'}, [
elem('header', {
className: 'mbox-header',
title: `User: ${userName}\n${time}\n\nUser pubkey: ${evt.pubkey}\n\nRelay: ${host}\n\nEvent-id: ${evt.id}
${evt.tags.length ? `\nTags ${JSON.stringify(evt.tags)}\n` : ''}
${evt.content}`
}, [
elem('a', {className: `mbox-username${name ? ' mbox-kind0-name' : ''}`, href: `/${evt.nip19.npub}`}, name || userName),
' ',
elem('a', {href: `/${evt.nip19.note}`}, elem('time', {dateTime: time.toISOString()}, formatTime(time))),
]),
elem('div', {/* data: isLongContent ? {append: evt.content.slice(280)} : null*/}, [
...content,
(firstLink && validatePow(evt)) ? linkPreview(firstLink, evt.id, relay) : null,
]), ]),
buttons, ` recommends server: ${evt.content}`,
]); ]);
if (localStorage.getItem('reply_to') === evt.id) {
openWriteInput(buttons, evt.id);
}
return elemArticle([ return elemArticle([
elem('div', {className: 'mbox-img'}, img), elem('div', {className: 'mbox-img'}, [img]), body
body, ], {className: 'mbox-recommend-server', data: {id: evt.id, pubkey: evt.pubkey}});
...(replies[0] ? [elem('div', {className: 'mobx-replies'}, replyFeed.reverse())] : []), };
], {data: {id: evt.id, pubkey: evt.pubkey, relay}});
}
function handleRecommendServer(evt: Event, relay: string) { const handleRecommendServer = (evt: Event, relay: string) => {
if (getViewElem(evt.id) || !isWssUrl(evt.content)) { if (getViewElem(evt.id) || !isWssUrl(evt.content)) {
return; return;
} }
@ -222,25 +215,31 @@ function handleRecommendServer(evt: Event, relay: string) {
getViewElem(closestTextNotes[0].id)?.after(art); // TODO: note might not be in the dom yet, recommendedServers could be controlled by renderFeed getViewElem(closestTextNotes[0].id)?.after(art); // TODO: note might not be in the dom yet, recommendedServers could be controlled by renderFeed
} }
setViewElem(evt.id, art); setViewElem(evt.id, art);
} };
function renderRecommendServer(evt: Event, relay: string) { const onEvent = (evt: Event, relay: string) => {
const {img, name, time, userName} = getMetadata(evt, relay); switch (evt.kind) {
const body = elem('div', {className: 'mbox-body', title: dateTime.format(time)}, [ case 0:
elem('header', {className: 'mbox-header'}, [ handleMetadata(evt, relay);
elem('small', {}, [ break;
elem('strong', {}, userName) case 1:
]), handleTextNote(evt, relay);
]), break;
` recommends server: ${evt.content}`, case 2:
]); handleRecommendServer(evt, relay);
return elemArticle([ break;
elem('div', {className: 'mbox-img'}, [img]), body case 3:
], {className: 'mbox-recommend-server', data: {id: evt.id, pubkey: evt.pubkey}}); // handleContactList(evt, relay);
} break;
case 7:
handleReaction(evt, relay);
default:
// console.log(`TODO: add support for event kind ${evt.kind}`/*, evt*/)
}
};
// subscribe and change view // subscribe and change view
function route(path: string) { const route = (path: string) => {
if (path === '/') { if (path === '/') {
sub24hFeed(onEvent); sub24hFeed(onEvent);
view('/'); view('/');
@ -263,7 +262,7 @@ function route(path: string) {
console.warn(`type ${type} not yet supported`); console.warn(`type ${type} not yet supported`);
} }
} }
} };
// onload // onload
route(location.pathname); route(location.pathname);

@ -62,11 +62,6 @@
.mbox-header a { .mbox-header a {
font-size: var(--font-small); font-size: var(--font-small);
} }
.mbox-header time,
.mbox-username {
color: var(--color-accent);
cursor: pointer;
}
.mbox-kind0-name { .mbox-kind0-name {
color: var(--color); color: var(--color);

@ -1,7 +1,7 @@
import {getEventHash} from 'nostr-tools'; import {getEventHash} from 'nostr-tools';
import {zeroLeadingBitsCount} from './utils/crypto'; import {zeroLeadingBitsCount} from './utils/crypto';
function mine(event, difficulty, timeout = 5) { const mine = (event, difficulty, timeout = 5) => {
const max = 256; // arbitrary const max = 256; // arbitrary
if (!Number.isInteger(difficulty) || difficulty < 0 || difficulty > max) { if (!Number.isInteger(difficulty) || difficulty < 0 || difficulty > max) {
throw new Error(`difficulty must be an integer between 0 and ${max}`); throw new Error(`difficulty must be an integer between 0 and ${max}`);
@ -29,9 +29,9 @@ function mine(event, difficulty, timeout = 5) {
return {id, ...event}; return {id, ...event};
} }
} }
} };
addEventListener('message', async (msg) => { addEventListener('message', (msg) => {
const {difficulty, event, timeout} = msg.data; const {difficulty, event, timeout} = msg.data;
try { try {
const minedEvent = mine(event, difficulty, timeout); const minedEvent = mine(event, difficulty, timeout);

@ -34,6 +34,19 @@ export const togglePublishView = () => {
} }
}; };
const appendReplyForm = (el: HTMLElement) => {
writeForm.before(elemShrink(writeInput));
writeInput.blur();
writeInput.style.removeProperty('height');
el.after(writeForm);
if (writeInput.value && !writeInput.value.trimRight()) {
writeInput.value = '';
} else {
requestAnimationFrame(() => updateElemHeight(writeInput));
}
requestAnimationFrame(() => writeInput.focus());
};
const closeWriteInput = () => writeInput.blur(); const closeWriteInput = () => writeInput.blur();
export const openWriteInput = ( export const openWriteInput = (
@ -139,16 +152,3 @@ writeInput.addEventListener('input', () => {
}); });
writeInput.addEventListener('blur', () => sendStatus.textContent = ''); writeInput.addEventListener('blur', () => sendStatus.textContent = '');
function appendReplyForm(el: HTMLElement) {
writeForm.before(elemShrink(writeInput));
writeInput.blur();
writeInput.style.removeProperty('height');
el.after(writeForm);
if (writeInput.value && !writeInput.value.trimRight()) {
writeInput.value = '';
} else {
requestAnimationFrame(() => updateElemHeight(writeInput));
}
requestAnimationFrame(() => writeInput.focus());
}

Loading…
Cancel
Save