added message parser, use for chat/channel

This commit is contained in:
Ren Amamiya 2023-04-17 08:30:44 +07:00
parent 637e081558
commit 15968db4a6
3 changed files with 54 additions and 1 deletions

View File

@ -0,0 +1,18 @@
import Image from 'next/image';
import { memo } from 'react';
export const MessageImagePreview = memo(function MesssageImagePreview({ url }: { url: string }) {
return (
<div className="relative mb-2 mt-3 h-full w-2/3 rounded-lg border border-zinc-800 xl:w-2/3">
<Image
src={url}
alt={url}
width="0"
height="0"
sizes="100vw"
className="h-auto w-full rounded-lg object-cover"
priority
/>
</div>
);
});

View File

@ -1,3 +1,5 @@
import { messageParser } from '@utils/parser';
import { nip04 } from 'nostr-tools';
import { useCallback, useEffect, useState } from 'react';
@ -30,5 +32,5 @@ export const useDecryptMessage = (
decrypt().catch(console.error);
}, [decrypt]);
return content;
return content.length > 0 ? messageParser(content) : '';
};

View File

@ -1,4 +1,5 @@
import { ImagePreview } from '@components/note/preview/image';
import { MessageImagePreview } from '@components/note/preview/messageImage';
import { VideoPreview } from '@components/note/preview/video';
import { NoteQuote } from '@components/note/quote';
import { UserMention } from '@components/user/mention';
@ -53,3 +54,35 @@ export const contentParser = (noteContent, noteTags) => {
return parsedContent;
};
export const messageParser = (noteContent) => {
let parsedContent = noteContent;
// handle urls
parsedContent = reactStringReplace(parsedContent, /(https?:\/\/\S+)/g, (match, i) => {
if (match.match(/\.(jpg|jpeg|gif|png|webp)$/i)) {
// image url
return <MessageImagePreview key={match + i} url={match} />;
} else if (match.match(/(www\.)?(youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]{11})/i)) {
// youtube
return <VideoPreview key={match + i} url={match} />;
} else if (match.match(/\.(mp4|webm)$/i)) {
// video
return <VideoPreview key={match + i} url={match} />;
} else {
return (
<a key={match + i} href={match} target="_blank" rel="noreferrer">
{match}
</a>
);
}
});
// handle #-hashtags
parsedContent = reactStringReplace(parsedContent, /#(\w+)/g, (match, i) => (
<span key={match + i} className="cursor-pointer text-fuchsia-500">
#{match}
</span>
));
return parsedContent;
};