main: convert remaining main to typescript

OFF0 2 years ago
parent 2f5e08de04
commit fdcba88bf2
Signed by: offbyn
GPG Key ID: 94A2F643C51F37FA

@ -18,7 +18,7 @@ export const options = {
'src/favicon.ico', 'src/favicon.ico',
'src/index.html', 'src/index.html',
'src/styles/main.css', 'src/styles/main.css',
'src/main.js', 'src/main.ts',
'src/manifest.json', 'src/manifest.json',
'src/worker.js', 'src/worker.js',
], ],

@ -1,6 +1,6 @@
import {nip19} from 'nostr-tools'; import {Event, nip19} from 'nostr-tools';
import {zeroLeadingBitsCount} from './utils/crypto'; import {zeroLeadingBitsCount} from './utils/crypto';
import {elem, parseTextContent} from './utils/dom'; import {elem, elemArticle, parseTextContent} from './utils/dom';
import {bounce, dateTime, formatTime} from './utils/time'; import {bounce, dateTime, formatTime} from './utils/time';
import {isWssUrl} from './utils/url'; import {isWssUrl} from './utils/url';
import {sub24hFeed, subNote, subProfile} from './subscriptions' import {sub24hFeed, subNote, subProfile} from './subscriptions'
@ -14,7 +14,7 @@ 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, relay) { function onEvent(evt: Event, relay: string) {
switch (evt.kind) { switch (evt.kind) {
case 0: case 0:
handleMetadata(evt, relay); handleMetadata(evt, relay);
@ -35,14 +35,28 @@ function onEvent(evt, relay) {
} }
} }
const textNoteList = []; // could use indexDB type EventWithNip19 = Event & {
const eventRelayMap = {}; // eventId: [relay1, relay2] nip19: {
note: string;
npub: string;
}
};
const textNoteList: Array<EventWithNip19> = []; // could use indexDB
type EventRelayMap = {
[eventId: string]: string[];
};
const eventRelayMap: EventRelayMap = {}; // eventId: [relay1, relay2]
const renderNote = (evt, i, sortedFeeds) => { const renderNote = (
evt: EventWithNip19,
i: number,
sortedFeeds: EventWithNip19[],
) => {
if (getViewElem(evt.id)) { // note already in view if (getViewElem(evt.id)) { // note already in view
return; return;
} }
const article = createTextNote(evt, eventRelayMap[evt.id]); const article = createTextNote(evt, eventRelayMap[evt.id][0]);
if (i === 0) { if (i === 0) {
getViewContent().append(article); getViewContent().append(article);
} else { } else {
@ -51,8 +65,11 @@ const renderNote = (evt, i, sortedFeeds) => {
setViewElem(evt.id, article); setViewElem(evt.id, article);
}; };
const hasEnoughPOW = ([tag, , commitment], eventId) => { const hasEnoughPOW = (
return tag === 'nonce' && commitment >= config.filterDifficulty && zeroLeadingBitsCount(eventId) >= config.filterDifficulty; [tag, , commitment]: string[],
eventId: string
) => {
return tag === 'nonce' && Number(commitment) >= config.filterDifficulty && zeroLeadingBitsCount(eventId) >= config.filterDifficulty;
}; };
const renderFeed = bounce(() => { const renderFeed = bounce(() => {
@ -67,9 +84,9 @@ 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, relay) { function handleTextNote(evt: Event, relay: string) {
if (eventRelayMap[evt.id]) { if (eventRelayMap[evt.id]) {
eventRelayMap[evt.id] = [relay, ...(eventRelayMap[evt.id])]; eventRelayMap[evt.id] = [...(eventRelayMap[evt.id]), relay]; // TODO: just push?
} else { } else {
eventRelayMap[evt.id] = [relay]; eventRelayMap[evt.id] = [relay];
const evtWithNip19 = { const evtWithNip19 = {
@ -90,9 +107,13 @@ function handleTextNote(evt, relay) {
} }
} }
const replyList = []; type EventWithNip19AndReplyTo = EventWithNip19 & {
replyTo: string;
}
const replyList: Array<EventWithNip19AndReplyTo> = [];
function handleReply(evt, relay) { function 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
@ -100,12 +121,16 @@ function handleReply(evt, relay) {
return; return;
} }
const replyTo = getReplyTo(evt); const replyTo = getReplyTo(evt);
if (!replyTo) {
console.warn('expected to find reply-to-event-id', evt);
return;
}
const evtWithReplyTo = {replyTo, ...evt}; const evtWithReplyTo = {replyTo, ...evt};
replyList.push(evtWithReplyTo); replyList.push(evtWithReplyTo);
renderReply(evtWithReplyTo, relay); renderReply(evtWithReplyTo, relay);
} }
function renderReply(evt, relay) { function renderReply(evt: EventWithNip19AndReplyTo, relay: string) {
const parent = getViewElem(evt.replyTo); const parent = getViewElem(evt.replyTo);
if (!parent) { // root article has not been rendered if (!parent) { // root article has not been rendered
return; return;
@ -126,20 +151,20 @@ config.rerenderFeed = () => {
}; };
setInterval(() => { setInterval(() => {
document.querySelectorAll('time[datetime]').forEach(timeElem => { document.querySelectorAll('time[datetime]').forEach((timeElem: HTMLTimeElement) => {
timeElem.textContent = formatTime(new Date(timeElem.dateTime)); timeElem.textContent = formatTime(new Date(timeElem.dateTime));
}); });
}, 10000); }, 10000);
function createTextNote(evt, relay) { function createTextNote(evt: EventWithNip19, relay: string) {
const {host, img, name, time, userName} = getMetadata(evt, relay); const {host, img, name, time, userName} = getMetadata(evt, relay);
const replies = replyList.filter(({replyTo}) => replyTo === evt.id); const replies = replyList.filter(({replyTo}) => replyTo === evt.id);
// const isLongContent = evt.content.trimRight().length > 280; // const isLongContent = evt.content.trimRight().length > 280;
// const content = isLongContent ? evt.content.slice(0, 280) : evt.content; // const content = isLongContent ? evt.content.slice(0, 280) : evt.content;
const reactions = getReactions(evt.id); const reactions = getReactions(evt.id);
const didReact = reactions.length && !!reactions.find(reaction => reaction.pubkey === config.pubkey); const didReact = reactions.length && !!reactions.find(reaction => reaction.pubkey === config.pubkey);
const replyFeed = replies[0] ? replies.sort(sortByCreatedAt).map(e => setViewElem(e.id, createTextNote(e, relay))) : []; const replyFeed: Array<HTMLElement> = replies[0] ? replies.sort(sortByCreatedAt).map(e => setViewElem(e.id, createTextNote(e, relay))) : [];
const [content, {firstLink}] = parseTextContent(evt.content); const [content, {firstLink}] = parseTextContent(evt.content);
const buttons = elem('div', {className: 'buttons'}, [ const buttons = elem('div', {className: 'buttons'}, [
elem('button', {name: 'reply', type: 'button'}, [ elem('button', {name: 'reply', type: 'button'}, [
@ -168,20 +193,21 @@ function createTextNote(evt, relay) {
]), ]),
elem('div', {/* data: isLongContent ? {append: evt.content.slice(280)} : null*/}, [ elem('div', {/* data: isLongContent ? {append: evt.content.slice(280)} : null*/}, [
...content, ...content,
(firstLink && validatePow(evt)) ? linkPreview(firstLink, evt.id, relay) : '', (firstLink && validatePow(evt)) ? linkPreview(firstLink, evt.id, relay) : null,
]), ]),
buttons, buttons,
]); ]);
if (localStorage.getItem('reply_to') === evt.id) { if (localStorage.getItem('reply_to') === evt.id) {
openWriteInput(buttons); openWriteInput(buttons, evt.id);
} }
return renderArticle([ return elemArticle([
elem('div', {className: 'mbox-img'}, [img]), body, elem('div', {className: 'mbox-img'}, img),
replies[0] ? elem('div', {className: 'mobx-replies'}, replyFeed.reverse()) : '', body,
...(replies[0] ? [elem('div', {className: 'mobx-replies'}, replyFeed.reverse())] : []),
], {data: {id: evt.id, pubkey: evt.pubkey, relay}}); ], {data: {id: evt.id, pubkey: evt.pubkey, relay}});
} }
function handleRecommendServer(evt, relay) { function handleRecommendServer(evt: Event, relay: string) {
if (getViewElem(evt.id) || !isWssUrl(evt.content)) { if (getViewElem(evt.id) || !isWssUrl(evt.content)) {
return; return;
} }
@ -190,14 +216,15 @@ function handleRecommendServer(evt, relay) {
getViewContent().append(art); getViewContent().append(art);
} else { } else {
const closestTextNotes = textNoteList const closestTextNotes = textNoteList
.filter(note => !config.filterDifficulty || note.tags.some(([tag, , commitment]) => tag === 'nonce' && commitment >= config.filterDifficulty)) // TODO: prob change to hasEnoughPOW // TODO: prob change to hasEnoughPOW
.filter(note => !config.filterDifficulty || note.tags.some(([tag, , commitment]) => tag === 'nonce' && Number(commitment) >= config.filterDifficulty))
.sort(sortEventCreatedAt(evt.created_at)); .sort(sortEventCreatedAt(evt.created_at));
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, relay) { function renderRecommendServer(evt: Event, relay: string) {
const {img, name, time, userName} = getMetadata(evt, relay); const {img, name, time, userName} = getMetadata(evt, relay);
const body = elem('div', {className: 'mbox-body', title: dateTime.format(time)}, [ const body = elem('div', {className: 'mbox-body', title: dateTime.format(time)}, [
elem('header', {className: 'mbox-header'}, [ elem('header', {className: 'mbox-header'}, [
@ -207,23 +234,22 @@ function renderRecommendServer(evt, relay) {
]), ]),
` recommends server: ${evt.content}`, ` recommends server: ${evt.content}`,
]); ]);
return renderArticle([ return elemArticle([
elem('div', {className: 'mbox-img'}, [img]), body elem('div', {className: 'mbox-img'}, [img]), body
], {className: 'mbox-recommend-server', data: {id: evt.id, pubkey: evt.pubkey}}); ], {className: 'mbox-recommend-server', data: {id: evt.id, pubkey: evt.pubkey}});
} }
function renderArticle(content, props = {}) {
const className = props.className ? ['mbox', props?.className].join(' ') : 'mbox';
return elem('article', {...props, className}, content);
}
// subscribe and change view // subscribe and change view
function route(path) { function route(path: string) {
if (path === '/') { if (path === '/') {
sub24hFeed(onEvent); sub24hFeed(onEvent);
view('/'); view('/');
} else if (path.length === 64 && path.match(/^\/[0-9a-z]+$/)) { } else if (path.length === 64 && path.match(/^\/[0-9a-z]+$/)) {
const {type, data} = nip19.decode(path.slice(1)); const {type, data} = nip19.decode(path.slice(1));
if (typeof data !== 'string') {
console.warn('nip19 ProfilePointer, EventPointer and AddressPointer are not yet supported');
return;
}
switch(type) { switch(type) {
case 'note': case 'note':
subNote(data, onEvent); subNote(data, onEvent);
@ -248,8 +274,12 @@ window.addEventListener('popstate', (event) => {
route(location.pathname); route(location.pathname);
}); });
const handleLink = (e, a) => { const handleLink = (a: HTMLAnchorElement, e: MouseEvent) => {
const href = a.getAttribute('href'); const href = a.getAttribute('href');
if (typeof href !== 'string') {
console.warn('expected anchor to have href attribute', a);
return;
}
if ( if (
href === '/' href === '/'
|| href.startsWith('/note') || href.startsWith('/note')
@ -258,20 +288,23 @@ const handleLink = (e, a) => {
closeSettingsView(); closeSettingsView();
closePublishView(); closePublishView();
route(href); route(href);
history.pushState({}, null, href); history.pushState({}, '', href);
e.preventDefault(); e.preventDefault();
} }
}; };
const handleButton = (e, button) => { const handleButton = (button: HTMLButtonElement) => {
const id = e.target.closest('[data-id]')?.dataset.id; const id = (button.closest('[data-id]') as HTMLElement)?.dataset.id;
if (!id) {
return;
}
switch(button.name) { switch(button.name) {
case 'reply': case 'reply':
openWriteInput(button, id); openWriteInput(button, id);
break; break;
case 'star': case 'star':
const note = replyList.find(r => r.id === id) || textNoteList.find(n => n.id === (id)); const note = replyList.find(r => r.id === id) || textNoteList.find(n => n.id === (id));
handleUpvote(note); note && handleUpvote(note);
break; break;
case 'settings': case 'settings':
toggleSettingsView(); toggleSettingsView();
@ -291,14 +324,16 @@ const handleButton = (e, button) => {
// } // }
}; };
document.body.addEventListener('click', (e) => { document.body.addEventListener('click', (event: MouseEvent) => {
const a = e.target.closest('a'); if (event.target instanceof HTMLElement) {
const a = event.target?.closest('a');
if (a) { if (a) {
handleLink(e, a); handleLink(a, event);
return; return;
} }
const button = e.target.closest('button'); const button = event.target.closest('button');
if (button) { if (button) {
handleButton(e, button); handleButton(button);
}
} }
}); });

@ -0,0 +1,8 @@
/**
* type-guarded function that tells TypeScript (in strictNullChecks mode) that you're filtering out null/undefined items.
* example: array.filter(isNotNull)
*/
export const isNotNull = <T>(item: T): item is NonNullable<T> => item != null;
// alternative
// const const isNotNull = <T>(item: T | null): item is T => item !== null;

@ -1,13 +1,18 @@
import {isNotNull} from './array';
import {isValidURL} from './url'; import {isValidURL} from './url';
type DataAttributes = { type DataAttributes = {
data: { data: {
[key: string]: string | number; [key: string]: string | number;
} },
} & {
dataset: never, // the dataset property itself is readonly
}; };
type Attributes<Type> = Partial<Type & DataAttributes>; type Attributes<Type> = Partial<Type & DataAttributes>;
type Children = Array<HTMLElement | string | null> | HTMLElement | string | number | null;
/** /**
* example usage: * example usage:
* *
@ -23,7 +28,7 @@ type Attributes<Type> = Partial<Type & DataAttributes>;
export const elem = <Name extends keyof HTMLElementTagNameMap>( export const elem = <Name extends keyof HTMLElementTagNameMap>(
name: Extract<Name, keyof HTMLElementTagNameMap>, name: Extract<Name, keyof HTMLElementTagNameMap>,
attrs?: Attributes<HTMLElementTagNameMap[Name]>, attrs?: Attributes<HTMLElementTagNameMap[Name]>,
children?: Array<HTMLElement | string> | string | number, children?: Children,
): HTMLElementTagNameMap[Name] => { ): HTMLElementTagNameMap[Name] => {
const el = document.createElement(name); const el = document.createElement(name);
if (attrs) { if (attrs) {
@ -37,7 +42,7 @@ export const elem = <Name extends keyof HTMLElementTagNameMap>(
} }
if (children != null) { if (children != null) {
if (Array.isArray(children)) { if (Array.isArray(children)) {
el.append(...children); el.append(...children.filter(isNotNull));
} else { } else {
switch (typeof children) { switch (typeof children) {
case 'number': case 'number':
@ -176,3 +181,11 @@ export const updateElemHeight = (
el.style.removeProperty('padding-top'); el.style.removeProperty('padding-top');
} }
}; };
export const elemArticle = (
content: Array<HTMLElement>,
attrs: Attributes<HTMLElementTagNameMap['div']> = {}
) => {
const className = attrs.className ? ['mbox', attrs?.className].join(' ') : 'mbox';
return elem('article', {...attrs, className}, content);
};

Loading…
Cancel
Save