added note content parser

This commit is contained in:
Ren Amamiya 2023-03-21 09:24:40 +07:00
parent b10a70b4ce
commit a17c5dfba5
6 changed files with 104 additions and 39 deletions

View File

@ -38,6 +38,7 @@
"react-dom": "^18.2.0",
"react-hook-form": "^7.43.7",
"react-player": "^2.12.0",
"react-string-replace": "^1.1.0",
"react-virtuoso": "^4.1.0",
"tauri-plugin-sql-api": "github:tauri-apps/tauri-plugin-sql",
"unique-names-generator": "^4.7.1",

View File

@ -48,6 +48,7 @@ specifiers:
react-dom: ^18.2.0
react-hook-form: ^7.43.7
react-player: ^2.12.0
react-string-replace: ^1.1.0
react-virtuoso: ^4.1.0
tailwindcss: ^3.2.7
tauri-plugin-sql-api: github:tauri-apps/tauri-plugin-sql
@ -82,6 +83,7 @@ dependencies:
react-dom: 18.2.0_react@18.2.0
react-hook-form: 7.43.7_react@18.2.0
react-player: 2.12.0_react@18.2.0
react-string-replace: 1.1.0
react-virtuoso: 4.1.0_biqbaboplfbrettd7655fr4n2y
tauri-plugin-sql-api: github.com/tauri-apps/tauri-plugin-sql/3a8b9a6b244df7512bc5ef8692cebdedbab3ccce
unique-names-generator: 4.7.1
@ -1682,7 +1684,7 @@ packages:
'@uiw/copy-to-clipboard': 1.0.12
react: 18.2.0
react-dom: 18.2.0_react@18.2.0
react-markdown: 8.0.5_pmekkgnqduwlme35zpnqhenc34
react-markdown: 8.0.6_pmekkgnqduwlme35zpnqhenc34
rehype-attr: 2.1.4
rehype-autolink-headings: 6.1.1
rehype-ignore: 1.0.4
@ -5240,9 +5242,9 @@ packages:
{ integrity: sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w== }
dev: false
/react-markdown/8.0.5_pmekkgnqduwlme35zpnqhenc34:
/react-markdown/8.0.6_pmekkgnqduwlme35zpnqhenc34:
resolution:
{ integrity: sha512-jGJolWWmOWAvzf+xMdB9zwStViODyyFQhNB/bwCerbBKmrTmgmA599CGiOlP58OId1IMoIRsA8UdI1Lod4zb5A== }
{ integrity: sha512-KgPWsYgHuftdx510wwIzpwf+5js/iHqBR+fzxefv8Khk3mFbnioF1bmL2idHN3ler0LMQmICKeDrWnZrX9mtbQ== }
peerDependencies:
'@types/react': '>=16'
react: '>=16'
@ -5319,6 +5321,12 @@ packages:
use-sidecar: 1.1.2_pmekkgnqduwlme35zpnqhenc34
dev: false
/react-string-replace/1.1.0:
resolution:
{ integrity: sha512-N6RalSDFGbOHs0IJi1H611WbZsvk3ZT47Jl2JEXFbiS3kTwsdCYij70Keo/tWtLy7sfhDsYm7CwNM/WmjXIaMw== }
engines: { node: '>=0.12.0' }
dev: false
/react-style-singleton/2.2.1_pmekkgnqduwlme35zpnqhenc34:
resolution:
{ integrity: sha512-ZWj0fHEMyWkHzKYUr2Bs/4zU6XLmq9HsgBURm7g5pAVfyn49DgUiNgY2d4lXRlYSiCif9YBGpQleewkcqddc7g== }

View File

@ -1,22 +1,35 @@
import NoteMetadata from '@components/note/content/metadata';
import NotePreview from '@components/note/content/preview';
import { UserExtend } from '@components/user/extend';
import { UserMention } from '@components/user/mention';
import dynamic from 'next/dynamic';
import { memo, useMemo } from 'react';
const MarkdownPreview = dynamic(() => import('@uiw/react-markdown-preview'), {
ssr: false,
loading: () => <div className="h-4 w-36 animate-pulse rounded bg-zinc-700" />,
});
import reactStringReplace from 'react-string-replace';
export const Content = memo(function Content({ data }: { data: any }) {
const content = useMemo(
() =>
// remove all image urls
data.content.replace(/(https?:\/\/.*\.(jpg|jpeg|gif|png|webp)((\?.*)$|$))/i, ''),
[data.content]
);
const content = useMemo(() => {
let parsedContent;
// get data tags
const tags = JSON.parse(data.tags);
// remove all image urls
parsedContent = data.content.replace(/(https?:\/\/.*\.(jpg|jpeg|gif|png|webp)((\?.*)$|$))/gim, '');
// handle urls
parsedContent = reactStringReplace(parsedContent, /(https?:\/\/\S+)/g, (match, i) => (
<a key={match + i} href={match} target="_blank" rel="noreferrer">
{match}
</a>
));
// handle hashtags
parsedContent = reactStringReplace(parsedContent, /#(\w+)/g, (match, i) => (
<span className="text-fuchsia-500">#{match}</span>
));
// handle mentions
parsedContent = reactStringReplace(parsedContent, /\#\[(\d+)\]/gm, (match, i) => (
<UserMention pubkey={tags[match][1]} key={i} />
));
return parsedContent;
}, [data.content, data.tags]);
return (
<div className="relative z-10 flex flex-col">
@ -24,23 +37,8 @@ export const Content = memo(function Content({ data }: { data: any }) {
<div className="-mt-5 pl-[52px]">
<div className="flex flex-col gap-6">
<div className="flex flex-col">
<div>
<MarkdownPreview
source={content}
className={
'prose prose-zinc max-w-none break-words dark:prose-invert prose-headings:mt-3 prose-headings:mb-2 prose-p:m-0 prose-p:text-[15px] prose-p:leading-tight prose-a:font-normal prose-a:text-fuchsia-500 prose-a:no-underline prose-ul:mt-2 prose-li:my-1'
}
linkTarget="_blank"
disallowedElements={[
'Table',
'Heading ID',
'Highlight',
'Fenced Code Block',
'Footnote',
'Definition List',
'Task List',
]}
/>
<div className="prose prose-zinc max-w-none break-words text-[15px] leading-tight dark:prose-invert prose-headings:mt-3 prose-headings:mb-2 prose-p:m-0 prose-p:text-[15px] prose-p:leading-tight prose-a:font-normal prose-a:text-fuchsia-500 prose-a:no-underline prose-ul:mt-2 prose-li:my-1">
{content}
</div>
<NotePreview content={data.content} />
</div>

View File

@ -1,23 +1,31 @@
import { Content } from '@components/note/content';
import { RootNote } from '@components/note/root';
import { memo, useEffect, useState } from 'react';
import { memo, useMemo } from 'react';
export const Note = memo(function Note({ event }: { event: any }) {
const [root, setRoot] = useState(null);
const tags = JSON.parse(event.tags);
useEffect(() => {
const fetchRootEvent = useMemo(() => {
if (tags.length > 0) {
if (tags[0][0] === 'e') {
setRoot(tags[0][1]);
return <RootNote id={tags[0][1]} />;
} else {
tags.every((tag) => {
if (tag[2] === 'root') {
return <RootNote id={tags[1]} />;
}
return <></>;
});
}
} else {
return <></>;
}
}, [tags]);
return (
<div className="relative z-10 flex h-min min-h-min w-full cursor-pointer select-text flex-col border-b border-zinc-800 py-5 px-3 hover:bg-black/20">
{root && <RootNote id={root} />}
<>{fetchRootEvent}</>
<Content data={event} />
</div>
);

View File

@ -75,7 +75,7 @@ export const RootNote = memo(function RootNote({ id }: { id: string }) {
} else {
return (
<div className="relative z-10 flex h-min animate-pulse select-text flex-col pb-5">
<div className="flex items-start gap-4">
<div className="flex items-start gap-2">
<div className="relative h-11 w-11 shrink overflow-hidden rounded-full bg-zinc-700" />
<div className="flex w-full flex-1 items-start justify-between">
<div className="flex w-full items-center justify-between">
@ -88,7 +88,7 @@ export const RootNote = memo(function RootNote({ id }: { id: string }) {
</div>
</div>
</div>
<div className="-mt-4 pl-[60px]">
<div className="-mt-5 pl-[52px]">
<div className="flex flex-col gap-6">
<div className="h-16 w-full rounded bg-zinc-700" />
<div className="flex items-center gap-8">

View File

@ -0,0 +1,50 @@
import { DatabaseContext } from '@components/contexts/database';
import { truncate } from '@utils/truncate';
import { memo, useCallback, useContext, useEffect, useState } from 'react';
export const UserMention = memo(function UserMention({ pubkey }: { pubkey: string }) {
const { db }: any = useContext(DatabaseContext);
const [profile, setProfile] = useState({ name: null });
const insertCacheProfile = useCallback(
async (event) => {
// insert to database
await db.execute('INSERT OR IGNORE INTO cache_profiles (id, metadata) VALUES (?, ?);', [pubkey, event.content]);
// update state
setProfile(JSON.parse(event.content));
},
[db, pubkey]
);
const getCacheProfile = useCallback(async () => {
const result: any = await db.select(`SELECT metadata FROM cache_profiles WHERE id = "${pubkey}"`);
return result[0];
}, [db, pubkey]);
useEffect(() => {
getCacheProfile()
.then((res) => {
if (res !== undefined) {
setProfile(JSON.parse(res.metadata));
} else {
fetch(`https://rbr.bio/${pubkey}/metadata.json`, { redirect: 'follow' })
.then((response) => {
if (response.ok) {
return response.json();
} else if (response.status === 404) {
return Promise.reject('error 404');
} else {
return Promise.reject('some other error: ' + response.status);
}
})
.then((data) => insertCacheProfile(data))
.catch((error) => console.log('error is', error));
}
})
.catch(console.error);
}, [getCacheProfile, insertCacheProfile, pubkey]);
return <span className="text-fuchsia-500">@{profile.name ? profile.name : truncate(pubkey, 16, ' .... ')}</span>;
});