import { RelayContext } from '@components/relaysProvider';
import { UserExtend } from '@components/user/extend';
import { UserMention } from '@components/user/mention';
import { relaysAtom } from '@stores/relays';
import { createCacheNote, getNoteByID } from '@utils/storage';
import destr from 'destr';
import { useAtomValue } from 'jotai';
import { memo, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import reactStringReplace from 'react-string-replace';
export const NoteRepost = memo(function NoteRepost({ id }: { id: string }) {
const pool: any = useContext(RelayContext);
const relays = useAtomValue(relaysAtom);
const [event, setEvent] = useState(null);
const fetchEvent = useCallback(() => {
pool.subscribe(
[
{
ids: [id],
kinds: [1],
},
],
relays,
(event: any) => {
// update state
setEvent(event);
// insert to database
createCacheNote(event);
},
undefined,
undefined,
{
unsubscribeOnEose: true,
}
);
}, [id, pool, relays]);
useEffect(() => {
getNoteByID(id).then((res) => {
if (res) {
setEvent(res);
} else {
fetchEvent();
}
});
}, [fetchEvent, id]);
const content = useMemo(() => {
let parsedContent = event ? event.content : null;
if (parsedContent !== null) {
// get data tags
const tags = destr(event.tags);
// handle urls
parsedContent = reactStringReplace(parsedContent, /(https?:\/\/\S+)/g, (match, i) => (
{match}
));
// handle #-hashtags
parsedContent = reactStringReplace(parsedContent, /#(\w+)/g, (match, i) => (
#{match}
));
// handle mentions
if (tags.length > 0) {
parsedContent = reactStringReplace(parsedContent, /\#\[(\d+)\]/gm, (match, i) => {
if (tags[match][0] === 'p') {
// @-mentions
return