refactor all widgets

This commit is contained in:
reya 2023-11-01 08:07:49 +07:00
parent e7738fb128
commit fd5ecc18a9
37 changed files with 1096 additions and 1271 deletions

View File

@ -6,8 +6,8 @@ import { useStorage } from '@libs/storage/provider';
import { ArrowLeftIcon, CheckCircleIcon, LoaderIcon } from '@shared/icons'; import { ArrowLeftIcon, CheckCircleIcon, LoaderIcon } from '@shared/icons';
import { WidgetKinds } from '@stores/constants';
import { useOnboarding } from '@stores/onboarding'; import { useOnboarding } from '@stores/onboarding';
import { WidgetKinds } from '@stores/widgets';
const data = [ const data = [
{ hashtag: '#bitcoin' }, { hashtag: '#bitcoin' },

View File

@ -1,23 +1,20 @@
import { useStorage } from '@libs/storage/provider'; import { PlusIcon } from '@shared/icons';
import { WidgetWrapper } from '@shared/widgets';
import { HandArrowDownIcon, PlusIcon } from '@shared/icons'; import { WidgetKinds } from '@stores/constants';
import { WidgetKinds, useWidgets } from '@stores/widgets'; import { useWidget } from '@utils/hooks/useWidget';
export function ToggleWidgetList() { export function ToggleWidgetList() {
const { db } = useStorage(); const { addWidget } = useWidget();
const setWidget = useWidgets((state) => state.setWidget);
return ( return (
<div className="flex h-full w-[420px] items-center justify-center border-r border-neutral-100 dark:border-neutral-900"> <WidgetWrapper>
<div className="relative"> <div className="relative flex h-full w-full flex-col items-center justify-center">
<div className="absolute -top-44 left-1/2 -translate-x-1/2 transform">
<HandArrowDownIcon className="text-neutral-100 dark:text-neutral-900" />
</div>
<button <button
type="button" type="button"
onClick={() => onClick={() =>
setWidget(db, { kind: WidgetKinds.tmp.list, title: '', content: '' }) addWidget.mutate({ kind: WidgetKinds.tmp.list, title: '', content: '' })
} }
className="inline-flex h-9 items-center gap-2 rounded-full bg-neutral-200 px-3 text-neutral-900 hover:bg-neutral-300 dark:bg-neutral-800 dark:text-neutral-100 dark:hover:bg-neutral-700" className="inline-flex h-9 items-center gap-2 rounded-full bg-neutral-200 px-3 text-neutral-900 hover:bg-neutral-300 dark:bg-neutral-800 dark:text-neutral-100 dark:hover:bg-neutral-700"
> >
@ -25,6 +22,6 @@ export function ToggleWidgetList() {
<p className="text-sm font-semibold leading-none">Add widget</p> <p className="text-sm font-semibold leading-none">Add widget</p>
</button> </button>
</div> </div>
</div> </WidgetWrapper>
); );
} }

View File

@ -1,7 +1,5 @@
import { useCallback } from 'react'; import { useCallback } from 'react';
import { useStorage } from '@libs/storage/provider';
import { import {
ArticleIcon, ArticleIcon,
BellIcon, BellIcon,
@ -13,22 +11,15 @@ import {
TrendingIcon, TrendingIcon,
} from '@shared/icons'; } from '@shared/icons';
import { TitleBar } from '@shared/titleBar'; import { TitleBar } from '@shared/titleBar';
import { WidgetWrapper } from '@shared/widgets';
import { DefaultWidgets, WidgetKinds, useWidgets } from '@stores/widgets'; import { DefaultWidgets, WidgetKinds } from '@stores/constants';
import { Widget, WidgetGroup, WidgetGroupItem } from '@utils/types'; import { useWidget } from '@utils/hooks/useWidget';
import { Widget, WidgetGroup } from '@utils/types';
export function WidgetList({ params }: { params: Widget }) { export function WidgetList({ params }: { params: Widget }) {
const { db } = useStorage(); const { addWidget } = useWidget();
const [setWidget, removeWidget] = useWidgets((state) => [
state.setWidget,
state.removeWidget,
]);
const openWidget = (widget: WidgetGroupItem) => {
setWidget(db, { kind: widget.kind, title: widget.title, content: '' });
removeWidget(db, params.id);
};
const renderIcon = useCallback( const renderIcon = useCallback(
(kind: number) => { (kind: number) => {
@ -71,52 +62,51 @@ export function WidgetList({ params }: { params: Widget }) {
[DefaultWidgets] [DefaultWidgets]
); );
const renderItem = useCallback( const renderItem = useCallback((row: WidgetGroup, index: number) => {
(row: WidgetGroup, index: number) => { return (
return ( <div key={index} className="flex flex-col gap-2">
<div key={index} className="flex flex-col gap-2"> <h3 className="text-sm font-semibold text-neutral-500 dark:text-neutral-300">
<h3 className="text-sm font-semibold text-neutral-500 dark:text-neutral-300"> {row.title}
{row.title} </h3>
</h3> <div className="flex flex-col divide-y divide-neutral-100 overflow-hidden rounded-xl bg-neutral-50 dark:divide-neutral-900 dark:bg-neutral-950">
<div className="flex flex-col divide-y divide-neutral-100 overflow-hidden rounded-xl bg-neutral-50 dark:divide-neutral-900 dark:bg-neutral-950"> {row.data.map((item, index) => (
{row.data.map((item, index) => ( <button
<button onClick={() =>
onClick={() => openWidget(item)} addWidget.mutate({ kind: item.kind, title: item.title, content: '' })
key={index} }
className="group flex items-center gap-2.5 px-4 hover:bg-neutral-200 dark:hover:bg-neutral-800" key={index}
> className="group flex items-center gap-2.5 px-4 hover:bg-neutral-200 dark:hover:bg-neutral-800"
{item.icon ? ( >
<div className="h-10 w-10 shrink-0 rounded-md"> {item.icon ? (
<img <div className="h-10 w-10 shrink-0 rounded-md">
src={item.icon} <img
alt={item.title} src={item.icon}
className="h-10 w-10 object-cover" alt={item.title}
/> className="h-10 w-10 object-cover"
</div> />
) : (
<div className="inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-neutral-200 group-hover:bg-neutral-300 dark:bg-neutral-800 dark:group-hover:bg-neutral-700">
{renderIcon(item.kind)}
</div>
)}
<div className="inline-flex h-16 w-full flex-col items-start justify-center">
<h5 className="line-clamp-1 text-sm font-semibold text-neutral-900 dark:text-neutral-100">
{item.title}
</h5>
<p className="line-clamp-1 text-sm text-neutral-500 dark:text-neutral-300">
{item.description}
</p>
</div> </div>
</button> ) : (
))} <div className="inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-neutral-200 group-hover:bg-neutral-300 dark:bg-neutral-800 dark:group-hover:bg-neutral-700">
</div> {renderIcon(item.kind)}
</div>
)}
<div className="inline-flex h-16 w-full flex-col items-start justify-center">
<h5 className="line-clamp-1 text-sm font-semibold text-neutral-900 dark:text-neutral-100">
{item.title}
</h5>
<p className="line-clamp-1 text-sm text-neutral-500 dark:text-neutral-300">
{item.description}
</p>
</div>
</button>
))}
</div> </div>
); </div>
}, );
[DefaultWidgets] }, []);
);
return ( return (
<div className="h-full w-[420px] border-r border-neutral-100 dark:border-neutral-900"> <WidgetWrapper>
<TitleBar id={params.id} title="Add widget" /> <TitleBar id={params.id} title="Add widget" />
<div className="h-full overflow-y-auto pb-20 scrollbar-none"> <div className="h-full overflow-y-auto pb-20 scrollbar-none">
<div className="flex flex-col gap-6 px-3"> <div className="flex flex-col gap-6 px-3">
@ -139,6 +129,6 @@ export function WidgetList({ params }: { params: Widget }) {
</div> </div>
</div> </div>
</div> </div>
</div> </WidgetWrapper>
); );
} }

View File

@ -1,4 +1,5 @@
import { useCallback, useEffect, useRef } from 'react'; import { useQuery } from '@tanstack/react-query';
import { useCallback, useRef, useState } from 'react';
import { VList, VListHandle } from 'virtua'; import { VList, VListHandle } from 'virtua';
import { ToggleWidgetList } from '@app/space/components/toggle'; import { ToggleWidgetList } from '@app/space/components/toggle';
@ -11,99 +12,134 @@ import {
GlobalArticlesWidget, GlobalArticlesWidget,
GlobalFilesWidget, GlobalFilesWidget,
GlobalHashtagWidget, GlobalHashtagWidget,
LearnNostrWidget,
LocalArticlesWidget, LocalArticlesWidget,
LocalFeedsWidget, LocalFeedsWidget,
LocalFilesWidget, LocalFilesWidget,
LocalFollowsWidget,
LocalNotificationWidget,
LocalThreadWidget, LocalThreadWidget,
LocalUserWidget, LocalUserWidget,
NewsfeedWidget, NewsfeedWidget,
NotificationWidget,
TrendingAccountsWidget, TrendingAccountsWidget,
TrendingNotesWidget, TrendingNotesWidget,
XfeedsWidget, XfeedsWidget,
XhashtagWidget, XhashtagWidget,
} from '@shared/widgets'; } from '@shared/widgets';
import { WidgetKinds, useWidgets } from '@stores/widgets'; import { WidgetKinds } from '@stores/constants';
import { Widget } from '@utils/types'; import { Widget } from '@utils/types';
export function SpaceScreen() { export function SpaceScreen() {
const ref = useRef<VListHandle>(null);
const [selectedIndex, setSelectedIndex] = useState(-1);
const { db } = useStorage(); const { db } = useStorage();
const vlistRef = useRef<VListHandle>(null); const { status, data } = useQuery({
queryKey: ['widgets'],
queryFn: async () => {
const dbWidgets = await db.getWidgets();
const defaultWidgets = [
{
id: '9998',
title: 'Notification',
content: '',
kind: WidgetKinds.local.notification,
},
{
id: '9999',
title: 'Newsfeed',
content: '',
kind: WidgetKinds.local.network,
},
];
const [widgets, fetchWidgets] = useWidgets((state) => [ return [...defaultWidgets, ...dbWidgets];
state.widgets,
state.fetchWidgets,
]);
const renderItem = useCallback(
(widget: Widget) => {
if (!widget) return;
switch (widget.kind) {
case WidgetKinds.local.network:
return <NewsfeedWidget key={widget.id} />;
case WidgetKinds.local.follows:
return <LocalFollowsWidget key={widget.id} params={widget} />;
case WidgetKinds.local.feeds:
return <LocalFeedsWidget key={widget.id} params={widget} />;
case WidgetKinds.local.files:
return <LocalFilesWidget key={widget.id} params={widget} />;
case WidgetKinds.local.articles:
return <LocalArticlesWidget key={widget.id} params={widget} />;
case WidgetKinds.local.user:
return <LocalUserWidget key={widget.id} params={widget} />;
case WidgetKinds.local.thread:
return <LocalThreadWidget key={widget.id} params={widget} />;
case WidgetKinds.global.hashtag:
return <GlobalHashtagWidget key={widget.id} params={widget} />;
case WidgetKinds.global.articles:
return <GlobalArticlesWidget key={widget.id} params={widget} />;
case WidgetKinds.global.files:
return <GlobalFilesWidget key={widget.id} params={widget} />;
case WidgetKinds.nostrBand.trendingAccounts:
return <TrendingAccountsWidget key={widget.id} params={widget} />;
case WidgetKinds.nostrBand.trendingNotes:
return <TrendingNotesWidget key={widget.id} params={widget} />;
case WidgetKinds.tmp.xfeed:
return <XfeedsWidget key={widget.id} params={widget} />;
case WidgetKinds.tmp.xhashtag:
return <XhashtagWidget key={widget.id} params={widget} />;
case WidgetKinds.tmp.list:
return <WidgetList key={widget.id} params={widget} />;
case WidgetKinds.other.learnNostr:
return <LearnNostrWidget key={widget.id} params={widget} />;
case WidgetKinds.local.notification:
return <LocalNotificationWidget key={widget.id} params={widget} />;
default:
return null;
}
}, },
[widgets] refetchOnMount: false,
); refetchOnReconnect: false,
refetchOnWindowFocus: false,
staleTime: Infinity,
});
useEffect(() => { const renderItem = useCallback((widget: Widget) => {
fetchWidgets(db); switch (widget.kind) {
case WidgetKinds.local.feeds:
return <LocalFeedsWidget key={widget.id} params={widget} />;
case WidgetKinds.local.files:
return <LocalFilesWidget key={widget.id} params={widget} />;
case WidgetKinds.local.articles:
return <LocalArticlesWidget key={widget.id} params={widget} />;
case WidgetKinds.local.user:
return <LocalUserWidget key={widget.id} params={widget} />;
case WidgetKinds.local.thread:
return <LocalThreadWidget key={widget.id} params={widget} />;
case WidgetKinds.global.hashtag:
return <GlobalHashtagWidget key={widget.id} params={widget} />;
case WidgetKinds.global.articles:
return <GlobalArticlesWidget key={widget.id} params={widget} />;
case WidgetKinds.global.files:
return <GlobalFilesWidget key={widget.id} params={widget} />;
case WidgetKinds.nostrBand.trendingAccounts:
return <TrendingAccountsWidget key={widget.id} params={widget} />;
case WidgetKinds.nostrBand.trendingNotes:
return <TrendingNotesWidget key={widget.id} params={widget} />;
case WidgetKinds.tmp.xfeed:
return <XfeedsWidget key={widget.id} params={widget} />;
case WidgetKinds.tmp.xhashtag:
return <XhashtagWidget key={widget.id} params={widget} />;
case WidgetKinds.tmp.list:
return <WidgetList key={widget.id} params={widget} />;
case WidgetKinds.local.notification:
return <NotificationWidget key={widget.id} />;
case WidgetKinds.local.network:
return <NewsfeedWidget key={widget.id} />;
default:
return null;
}
}, []); }, []);
if (status === 'pending') {
return (
<div className="flex h-full w-full items-center justify-center">
<LoaderIcon className="h-5 w-5 animate-spin" />
</div>
);
}
return ( return (
<VList <VList
className="h-full w-full flex-nowrap overflow-x-auto !overflow-y-hidden scrollbar-none focus:outline-none" className="h-full w-full flex-nowrap overflow-x-auto !overflow-y-hidden scrollbar-none focus:outline-none"
horizontal horizontal
ref={vlistRef} ref={ref}
initialItemSize={420} initialItemSize={420}
aria-current="step"
tabIndex={0} tabIndex={0}
onKeyDown={(e) => {
if (!ref.current) return;
switch (e.code) {
case 'ArrowLeft': {
e.preventDefault();
const prevIndex = Math.max(selectedIndex - 1, 0);
setSelectedIndex(prevIndex);
ref.current.scrollToIndex(prevIndex, {
align: 'center',
smooth: true,
});
break;
}
case 'ArrowRight': {
e.preventDefault();
const nextIndex = Math.min(selectedIndex + 1, data.length - 1);
setSelectedIndex(nextIndex);
ref.current.scrollToIndex(nextIndex, {
align: 'center',
smooth: true,
});
break;
}
}
}}
> >
{!widgets ? ( {data.map((widget) => renderItem(widget))}
<div className="flex h-full w-[420px] flex-col items-center justify-center">
<LoaderIcon className="h-5 w-5 animate-spin text-neutral-900 dark:text-neutral-100" />
</div>
) : (
widgets.map((widget) => renderItem(widget))
)}
<ToggleWidgetList /> <ToggleWidgetList />
</VList> </VList>
); );

View File

@ -254,7 +254,8 @@ export class LumeStorage {
} }
public async removeWidget(id: string) { public async removeWidget(id: string) {
return await this.db.execute('DELETE FROM widgets WHERE id = $1;', [id]); const res = await this.db.execute('DELETE FROM widgets WHERE id = $1;', [id]);
if (res) return id;
} }
public async createEvent(event: NDKEvent) { public async createEvent(event: NDKEvent) {

View File

@ -1,99 +1,22 @@
import { NDKFilter, NDKKind } from '@nostr-dev-kit/ndk';
import * as Avatar from '@radix-ui/react-avatar'; import * as Avatar from '@radix-ui/react-avatar';
import { minidenticon } from 'minidenticons'; import { minidenticon } from 'minidenticons';
import { useEffect } from 'react'; import { Link } from 'react-router-dom';
import { Link, useLocation } from 'react-router-dom';
import { useNDK } from '@libs/ndk/provider';
import { useStorage } from '@libs/storage/provider'; import { useStorage } from '@libs/storage/provider';
import { AccountMoreActions } from '@shared/accounts/more'; import { AccountMoreActions } from '@shared/accounts/more';
import { NetworkStatusIndicator } from '@shared/networkStatusIndicator'; import { NetworkStatusIndicator } from '@shared/networkStatusIndicator';
import { useActivities } from '@stores/activities';
import { useNostr } from '@utils/hooks/useNostr';
import { useProfile } from '@utils/hooks/useProfile'; import { useProfile } from '@utils/hooks/useProfile';
import { sendNativeNotification } from '@utils/notification';
export function ActiveAccount() { export function ActiveAccount() {
const { db } = useStorage(); const { db } = useStorage();
const { ndk } = useNDK();
const { status, user } = useProfile(db.account.pubkey); const { status, user } = useProfile(db.account.pubkey);
const { sub } = useNostr();
const location = useLocation();
const addActivity = useActivities((state) => state.addActivity);
const addNewMessage = useActivities((state) => state.addNewMessage);
const svgURI = const svgURI =
'data:image/svg+xml;utf8,' + 'data:image/svg+xml;utf8,' +
encodeURIComponent(minidenticon(db.account.pubkey, 90, 50)); encodeURIComponent(minidenticon(db.account.pubkey, 90, 50));
useEffect(() => {
const filter: NDKFilter = {
kinds: [
NDKKind.Text,
NDKKind.EncryptedDirectMessage,
NDKKind.Repost,
NDKKind.Reaction,
NDKKind.Zap,
],
since: Math.floor(Date.now() / 1000),
'#p': [db.account.pubkey],
};
sub(
filter,
async (event) => {
console.log('receive event: ', event.id);
if (event.kind !== NDKKind.EncryptedDirectMessage) {
addActivity(event);
}
const user = ndk.getUser({ hexpubkey: event.pubkey });
await user.fetchProfile();
switch (event.kind) {
case NDKKind.Text:
return await sendNativeNotification(
`${user.profile.displayName || user.profile.name} has replied to your note`
);
case NDKKind.EncryptedDirectMessage: {
if (location.pathname !== '/chats') {
addNewMessage();
return await sendNativeNotification(
`${
user.profile.displayName || user.profile.name
} has send you a encrypted message`
);
} else {
break;
}
}
case NDKKind.Repost:
return await sendNativeNotification(
`${user.profile.displayName || user.profile.name} has reposted to your note`
);
case NDKKind.Reaction:
return await sendNativeNotification(
`${user.profile.displayName || user.profile.name} has reacted ${
event.content
} to your note`
);
case NDKKind.Zap:
return await sendNativeNotification(
`${user.profile.displayName || user.profile.name} has zapped to your note`
);
default:
break;
}
},
false
);
}, []);
if (status === 'pending') { if (status === 'pending') {
return ( return (
<div className="aspect-square h-auto w-full animate-pulse rounded-lg bg-neutral-300 dark:bg-neutral-700" /> <div className="aspect-square h-auto w-full animate-pulse rounded-lg bg-neutral-300 dark:bg-neutral-700" />

View File

@ -11,12 +11,10 @@ import {
RelayIcon, RelayIcon,
} from '@shared/icons'; } from '@shared/icons';
import { useActivities } from '@stores/activities';
import { compactNumber } from '@utils/number'; import { compactNumber } from '@utils/number';
export function Navigation() { export function Navigation() {
const newMessages = useActivities((state) => state.newMessages); const newMessages = 0;
return ( return (
<div className="flex h-full w-full flex-col justify-between p-3"> <div className="flex h-full w-full flex-col justify-between p-3">

View File

@ -1,14 +1,14 @@
import * as Tooltip from '@radix-ui/react-tooltip'; import * as Tooltip from '@radix-ui/react-tooltip';
import { useStorage } from '@libs/storage/provider';
import { FocusIcon } from '@shared/icons'; import { FocusIcon } from '@shared/icons';
import { NoteReaction } from '@shared/notes/actions/reaction'; import { NoteReaction } from '@shared/notes/actions/reaction';
import { NoteReply } from '@shared/notes/actions/reply'; import { NoteReply } from '@shared/notes/actions/reply';
import { NoteRepost } from '@shared/notes/actions/repost'; import { NoteRepost } from '@shared/notes/actions/repost';
import { NoteZap } from '@shared/notes/actions/zap'; import { NoteZap } from '@shared/notes/actions/zap';
import { WidgetKinds, useWidgets } from '@stores/widgets'; import { WidgetKinds } from '@stores/constants';
import { useWidget } from '@utils/hooks/useWidget';
export function NoteActions({ export function NoteActions({
id, id,
@ -21,8 +21,7 @@ export function NoteActions({
extraButtons?: boolean; extraButtons?: boolean;
root?: string; root?: string;
}) { }) {
const { db } = useStorage(); const { addWidget } = useWidget();
const setWidget = useWidgets((state) => state.setWidget);
return ( return (
<Tooltip.Provider> <Tooltip.Provider>
@ -40,7 +39,7 @@ export function NoteActions({
<button <button
type="button" type="button"
onClick={() => onClick={() =>
setWidget(db, { addWidget.mutate({
kind: WidgetKinds.local.thread, kind: WidgetKinds.local.thread,
title: 'Thread', title: 'Thread',
content: id, content: id,

View File

@ -4,8 +4,6 @@ import {
MediaController, MediaController,
MediaMuteButton, MediaMuteButton,
MediaPlayButton, MediaPlayButton,
MediaSeekBackwardButton,
MediaSeekForwardButton,
MediaTimeDisplay, MediaTimeDisplay,
MediaTimeRange, MediaTimeRange,
MediaVolumeRange, MediaVolumeRange,
@ -37,19 +35,19 @@ export function FileNote(props: { event?: NDKEvent }) {
if (type === 'video') { if (type === 'video') {
return ( return (
<div className="mb-2 mt-3"> <div className="mb-2 mt-3">
<MediaController key={url} className="aspect-video overflow-hidden rounded-lg"> <MediaController
key={url}
className="aspect-video w-full overflow-hidden rounded-lg"
>
<video <video
slot="media" slot="media"
src={url} src={url}
poster={`https://thumbnail.video/api/get?url=${url}&seconds=1`} poster={`https://thumbnail.video/api/get?url=${url}&seconds=1`}
preload="none" preload="none"
muted muted
crossOrigin=""
/> />
<MediaControlBar> <MediaControlBar>
<MediaPlayButton></MediaPlayButton> <MediaPlayButton></MediaPlayButton>
<MediaSeekBackwardButton></MediaSeekBackwardButton>
<MediaSeekForwardButton></MediaSeekForwardButton>
<MediaTimeRange></MediaTimeRange> <MediaTimeRange></MediaTimeRange>
<MediaTimeDisplay showDuration></MediaTimeDisplay> <MediaTimeDisplay showDuration></MediaTimeDisplay>
<MediaMuteButton></MediaMuteButton> <MediaMuteButton></MediaMuteButton>

View File

@ -4,12 +4,20 @@ import { ImagePreview, LinkPreview, MentionNote, VideoPreview } from '@shared/no
import { parser } from '@utils/parser'; import { parser } from '@utils/parser';
export function TextNote(props: { content?: string }) { export function TextNote(props: { content?: string; truncate?: boolean }) {
const richContent = parser(props.content); const richContent = parser(props.content);
if (props.truncate) {
return (
<div className="break-p prose prose-neutral line-clamp-4 max-w-none select-text whitespace-pre-line leading-normal dark:prose-invert prose-headings:mb-1 prose-headings:mt-3 prose-p:mb-0 prose-p:mt-0 prose-p:last:mb-1 prose-a:font-normal prose-a:text-blue-500 prose-blockquote:mb-1 prose-blockquote:mt-1 prose-blockquote:border-l-[2px] prose-blockquote:border-blue-500 prose-blockquote:pl-2 prose-pre:whitespace-pre-wrap prose-pre:bg-white/10 prose-ol:m-0 prose-ol:mb-1 prose-ul:mb-1 prose-ul:mt-1 prose-img:mb-2 prose-img:mt-3 prose-hr:mx-0 prose-hr:my-2 hover:prose-a:text-blue-600 prose-a:hover:underline">
{props.content}
</div>
);
}
return ( return (
<div> <div>
<div className="break-p prose prose-neutral max-w-none select-text whitespace-pre-line leading-normal dark:prose-invert prose-headings:mb-1 prose-headings:mt-3 prose-p:mb-0 prose-p:mt-0 prose-p:last:mb-1 prose-a:font-normal prose-a:text-blue-500 prose-blockquote:mb-1 prose-blockquote:mt-1 prose-blockquote:border-l-[2px] prose-blockquote:border-blue-500 prose-blockquote:pl-2 prose-pre:whitespace-pre-wrap prose-pre:bg-white/10 prose-ol:m-0 prose-ol:mb-1 prose-ul:mb-1 prose-ul:mt-1 prose-img:mb-2 prose-img:mt-3 prose-hr:mx-0 prose-hr:my-2 hover:prose-a:text-blue-500"> <div className="break-p prose prose-neutral max-w-none select-text whitespace-pre-line leading-normal dark:prose-invert prose-headings:mb-1 prose-headings:mt-3 prose-p:mb-0 prose-p:mt-0 prose-p:last:mb-1 prose-a:font-normal prose-a:text-blue-500 prose-blockquote:mb-1 prose-blockquote:mt-1 prose-blockquote:border-l-[2px] prose-blockquote:border-blue-500 prose-blockquote:pl-2 prose-pre:whitespace-pre-wrap prose-pre:bg-white/10 prose-ol:m-0 prose-ol:mb-1 prose-ul:mb-1 prose-ul:mt-1 prose-img:mb-2 prose-img:mt-3 prose-hr:mx-0 prose-hr:my-2 hover:prose-a:text-blue-600 prose-a:hover:underline">
{richContent.parsed} {richContent.parsed}
</div> </div>
{richContent.images.length ? <ImagePreview urls={richContent.images} /> : null} {richContent.images.length ? <ImagePreview urls={richContent.images} /> : null}

View File

@ -1,24 +1,15 @@
import { useStorage } from '@libs/storage/provider'; import { WidgetKinds } from '@stores/constants';
import { WidgetKinds, useWidgets } from '@stores/widgets'; import { useWidget } from '@utils/hooks/useWidget';
export function Hashtag({ tag }: { tag: string }) { export function Hashtag({ tag }: { tag: string }) {
const { db } = useStorage(); const { addWidget } = useWidget();
const setWidget = useWidgets((state) => state.setWidget);
return ( return (
<span <button
role="button" type="button"
tabIndex={0}
onClick={() => onClick={() =>
setWidget(db, { addWidget.mutate({
kind: WidgetKinds.global.hashtag,
title: tag,
content: tag.replace('#', ''),
})
}
onKeyDown={() =>
setWidget(db, {
kind: WidgetKinds.global.hashtag, kind: WidgetKinds.global.hashtag,
title: tag, title: tag,
content: tag.replace('#', ''), content: tag.replace('#', ''),
@ -27,6 +18,6 @@ export function Hashtag({ tag }: { tag: string }) {
className="cursor-default break-all text-blue-500 hover:text-blue-600" className="cursor-default break-all text-blue-500 hover:text-blue-600"
> >
{tag} {tag}
</span> </button>
); );
} }

View File

@ -3,8 +3,8 @@ import { memo } from 'react';
export const Invoice = memo(function Invoice({ invoice }: { invoice: string }) { export const Invoice = memo(function Invoice({ invoice }: { invoice: string }) {
return ( return (
<span className="mt-2 flex items-center rounded-lg bg-neutral-200 p-2 dark:bg-neutral-800"> <div className="mt-2 flex items-center rounded-lg bg-neutral-200 p-2 dark:bg-neutral-800">
<QRCodeSVG value={invoice} includeMargin={true} className="rounded-lg" /> <QRCodeSVG value={invoice} includeMargin={true} className="rounded-lg" />
</span> </div>
); );
}); });

View File

@ -2,8 +2,6 @@ import { NDKEvent, NDKKind } from '@nostr-dev-kit/ndk';
import { nip19 } from 'nostr-tools'; import { nip19 } from 'nostr-tools';
import { memo } from 'react'; import { memo } from 'react';
import { useStorage } from '@libs/storage/provider';
import { import {
ArticleNote, ArticleNote,
FileNote, FileNote,
@ -14,20 +12,23 @@ import {
} from '@shared/notes'; } from '@shared/notes';
import { User } from '@shared/user'; import { User } from '@shared/user';
import { WidgetKinds, useWidgets } from '@stores/widgets'; import { WidgetKinds } from '@stores/constants';
import { useEvent } from '@utils/hooks/useEvent'; import { useEvent } from '@utils/hooks/useEvent';
import { useWidget } from '@utils/hooks/useWidget';
export const MentionNote = memo(function MentionNote({ id }: { id: string }) { export const MentionNote = memo(function MentionNote({ id }: { id: string }) {
const { db } = useStorage();
const { status, data } = useEvent(id); const { status, data } = useEvent(id);
const { addWidget } = useWidget();
const setWidget = useWidgets((state) => state.setWidget);
const openThread = (event, thread: string) => { const openThread = (event, thread: string) => {
const selection = window.getSelection(); const selection = window.getSelection();
if (selection.toString().length === 0) { if (selection.toString().length === 0) {
setWidget(db, { kind: WidgetKinds.local.thread, title: 'Thread', content: thread }); addWidget.mutate({
kind: WidgetKinds.local.thread,
title: 'Thread',
content: thread,
});
} else { } else {
event.stopPropagation(); event.stopPropagation();
} }
@ -74,15 +75,13 @@ export const MentionNote = memo(function MentionNote({ id }: { id: string }) {
} }
return ( return (
<div <button
type="button"
onClick={(e) => openThread(e, id)} onClick={(e) => openThread(e, id)}
onKeyDown={(e) => openThread(e, id)}
role="button"
tabIndex={0}
className="mt-3 cursor-default rounded-lg border border-neutral-300 bg-neutral-200 p-3 dark:border-neutral-700 dark:bg-neutral-800" className="mt-3 cursor-default rounded-lg border border-neutral-300 bg-neutral-200 p-3 dark:border-neutral-700 dark:bg-neutral-800"
> >
<User pubkey={data.pubkey} time={data.created_at} variant="mention" /> <User pubkey={data.pubkey} time={data.created_at} variant="mention" />
<div className="mt-1">{renderKind(data)}</div> <div className="mt-1 text-left">{renderKind(data)}</div>
</div> </button>
); );
}); });

View File

@ -1,30 +1,26 @@
import { memo } from 'react'; import { memo } from 'react';
import { useStorage } from '@libs/storage/provider'; import { WidgetKinds } from '@stores/constants';
import { WidgetKinds, useWidgets } from '@stores/widgets';
import { useProfile } from '@utils/hooks/useProfile'; import { useProfile } from '@utils/hooks/useProfile';
import { useWidget } from '@utils/hooks/useWidget';
export const MentionUser = memo(function MentionUser({ pubkey }: { pubkey: string }) { export const MentionUser = memo(function MentionUser({ pubkey }: { pubkey: string }) {
const { db } = useStorage();
const { user } = useProfile(pubkey); const { user } = useProfile(pubkey);
const { addWidget } = useWidget();
const setWidget = useWidgets((state) => state.setWidget);
return ( return (
<span <button
role="button" type="button"
tabIndex={0}
onClick={() => onClick={() =>
setWidget(db, { addWidget.mutate({
kind: WidgetKinds.local.user, kind: WidgetKinds.local.user,
title: user?.name || user?.display_name || user?.displayName, title: user?.name || user?.display_name || user?.displayName,
content: pubkey, content: pubkey,
}) })
} }
onKeyDown={() => onKeyDown={() =>
setWidget(db, { addWidget.mutate({
kind: WidgetKinds.local.user, kind: WidgetKinds.local.user,
title: user?.name || user?.display_name || user?.displayName, title: user?.name || user?.display_name || user?.displayName,
content: pubkey, content: pubkey,
@ -38,6 +34,6 @@ export const MentionUser = memo(function MentionUser({ pubkey }: { pubkey: strin
user?.displayName || user?.displayName ||
user?.username || user?.username ||
'unknown')} 'unknown')}
</span> </button>
); );
}); });

View File

@ -3,19 +3,13 @@ import { useQuery } from '@tanstack/react-query';
import { decode } from 'light-bolt11-decoder'; import { decode } from 'light-bolt11-decoder';
import { useNDK } from '@libs/ndk/provider'; import { useNDK } from '@libs/ndk/provider';
import { useStorage } from '@libs/storage/provider';
import { LoaderIcon } from '@shared/icons'; import { LoaderIcon } from '@shared/icons';
import { User } from '@shared/user'; import { User } from '@shared/user';
import { WidgetKinds, useWidgets } from '@stores/widgets';
import { compactNumber } from '@utils/number'; import { compactNumber } from '@utils/number';
export function NoteMetadata({ id }: { id: string }) { export function NoteMetadata({ id }: { id: string }) {
const setWidget = useWidgets((state) => state.setWidget);
const { db } = useStorage();
const { ndk } = useNDK(); const { ndk } = useNDK();
const { status, data } = useQuery({ const { status, data } = useQuery({
queryKey: ['note-metadata', id], queryKey: ['note-metadata', id],
@ -89,17 +83,7 @@ export function NoteMetadata({ id }: { id: string }) {
</div> </div>
</div> </div>
<div className="mt-2 inline-flex h-6 items-center gap-2"> <div className="mt-2 inline-flex h-6 items-center gap-2">
<button <button type="button" className="text-neutral-600 dark:text-neutral-400">
type="button"
onClick={() =>
setWidget(db, {
kind: WidgetKinds.local.thread,
title: 'Thread',
content: id,
})
}
className="text-neutral-600 dark:text-neutral-400"
>
<span className="font-semibold text-white">{data.replies}</span> replies <span className="font-semibold text-white">{data.replies}</span> replies
</button> </button>
<span className="text-neutral-600 dark:text-neutral-400">·</span> <span className="text-neutral-600 dark:text-neutral-400">·</span>

View File

@ -2,6 +2,10 @@ import { Link } from 'react-router-dom';
import { useOpenGraph } from '@utils/hooks/useOpenGraph'; import { useOpenGraph } from '@utils/hooks/useOpenGraph';
function isImage(url: string) {
return /^https?:\/\/.+\.(jpg|jpeg|png|webp|avif)$/.test(url);
}
export function LinkPreview({ urls }: { urls: string[] }) { export function LinkPreview({ urls }: { urls: string[] }) {
const { status, data, error } = useOpenGraph(urls[0]); const { status, data, error } = useOpenGraph(urls[0]);
const domain = new URL(urls[0]); const domain = new URL(urls[0]);
@ -37,25 +41,25 @@ export function LinkPreview({ urls }: { urls: string[] }) {
</div> </div>
) : ( ) : (
<> <>
{data.image && ( {isImage(data.image) ? (
<img <img
src={data.image} src={data.image}
alt={urls[0]} alt={urls[0]}
className="h-44 w-full rounded-t-lg bg-white object-cover" className="h-44 w-full rounded-t-lg bg-white object-cover"
/> />
)} ) : null}
<div className="flex flex-col px-3 py-3"> <div className="flex flex-col items-start px-3 py-3">
<div className="flex flex-col gap-1"> <div className="flex flex-col items-start gap-1 text-left">
{data.title && ( {data.title && (
<h5 className="line-clamp-1 text-base font-semibold text-neutral-900 dark:text-neutral-100"> <h5 className="line-clamp-1 text-base font-semibold text-neutral-900 dark:text-neutral-100">
{data.title} {data.title}
</h5> </h5>
)} )}
{data.description && ( {data.description ? (
<p className="mb-2.5 line-clamp-3 break-all text-sm text-neutral-700 dark:text-neutral-400"> <p className="mb-2.5 line-clamp-3 break-all text-sm text-neutral-700 dark:text-neutral-400">
{data.description} {data.description}
</p> </p>
)} ) : null}
</div> </div>
<span className="break-all text-sm text-neutral-600 dark:text-neutral-400"> <span className="break-all text-sm text-neutral-600 dark:text-neutral-400">
{domain.hostname} {domain.hostname}

View File

@ -1,7 +1,5 @@
import { NDKEvent, NDKKind } from '@nostr-dev-kit/ndk'; import { NDKEvent, NDKKind } from '@nostr-dev-kit/ndk';
import { useStorage } from '@libs/storage/provider';
import { import {
ArticleNote, ArticleNote,
FileNote, FileNote,
@ -11,33 +9,37 @@ import {
} from '@shared/notes'; } from '@shared/notes';
import { User } from '@shared/user'; import { User } from '@shared/user';
import { WidgetKinds, useWidgets } from '@stores/widgets'; import { WidgetKinds } from '@stores/constants';
import { formatCreatedAt } from '@utils/createdAt'; import { formatCreatedAt } from '@utils/createdAt';
import { useEvent } from '@utils/hooks/useEvent'; import { useEvent } from '@utils/hooks/useEvent';
import { useWidget } from '@utils/hooks/useWidget';
export function NotifyNote({ event }: { event: NDKEvent }) { export function NotifyNote({ event }: { event: NDKEvent }) {
const createdAt = formatCreatedAt(event.created_at, false); const createdAt = formatCreatedAt(event.created_at, false);
const rootEventId = event.tags.find((el) => el[0] === 'e')?.[1]; const rootEventId = event.tags.find((el) => el[0] === 'e')?.[1];
const { db } = useStorage();
const { status, data } = useEvent(rootEventId); const { status, data } = useEvent(rootEventId);
const { addWidget } = useWidget();
const setWidget = useWidgets((state) => state.setWidget);
const openThread = (event, thread: string) => { const openThread = (event, thread: string) => {
const selection = window.getSelection(); const selection = window.getSelection();
if (selection.toString().length === 0) { if (selection.toString().length === 0) {
setWidget(db, { kind: WidgetKinds.local.thread, title: 'Thread', content: thread }); addWidget.mutate({
kind: WidgetKinds.local.thread,
title: 'Thread',
content: thread,
});
} else { } else {
event.stopPropagation(); event.stopPropagation();
} }
}; };
const renderKind = (event: NDKEvent) => { const renderKind = (event: NDKEvent) => {
if (!event) return null;
switch (event.kind) { switch (event.kind) {
case NDKKind.Text: case NDKKind.Text:
return <TextNote content={event.content} />; return <TextNote content={event.content} truncate />;
case NDKKind.Article: case NDKKind.Article:
return <ArticleNote event={event} />; return <ArticleNote event={event} />;
case 1063: case 1063:
@ -88,13 +90,13 @@ export function NotifyNote({ event }: { event: NDKEvent }) {
{event.kind === 1 ? <TextNote content={event.content} /> : null} {event.kind === 1 ? <TextNote content={event.content} /> : null}
</div> </div>
<div <div
onClick={(e) => openThread(e, data.id)} onClick={(e) => openThread(e, data?.id)}
onKeyDown={(e) => openThread(e, data.id)} onKeyDown={(e) => openThread(e, data?.id)}
role="button" role="button"
tabIndex={0} tabIndex={0}
className="cursor-default rounded-lg border border-neutral-300 bg-neutral-200 p-3 dark:border-neutral-700 dark:bg-neutral-800" className="cursor-default rounded-lg border border-neutral-300 bg-neutral-200 p-3 dark:border-neutral-700 dark:bg-neutral-800"
> >
<User pubkey={data.pubkey} time={data.created_at} variant="mention" /> <User pubkey={data?.pubkey} time={data?.created_at} variant="mention" />
<div className="mt-1">{renderKind(data)}</div> <div className="mt-1">{renderKind(data)}</div>
</div> </div>
</div> </div>

View File

@ -3,11 +3,11 @@ import { useStorage } from '@libs/storage/provider';
import { CancelIcon } from '@shared/icons'; import { CancelIcon } from '@shared/icons';
import { User } from '@shared/user'; import { User } from '@shared/user';
import { useWidgets } from '@stores/widgets'; import { useWidget } from '@utils/hooks/useWidget';
export function TitleBar({ id, title }: { id?: string; title?: string }) { export function TitleBar({ id, title }: { id?: string; title?: string }) {
const { db } = useStorage(); const { db } = useStorage();
const remove = useWidgets((state) => state.removeWidget); const { removeWidget } = useWidget();
return ( return (
<div className="flex h-11 w-full shrink-0 items-center justify-between overflow-hidden px-3"> <div className="flex h-11 w-full shrink-0 items-center justify-between overflow-hidden px-3">
@ -33,7 +33,7 @@ export function TitleBar({ id, title }: { id?: string; title?: string }) {
{id !== '9999' ? ( {id !== '9999' ? (
<button <button
type="button" type="button"
onClick={() => remove(db, id)} onClick={() => removeWidget.mutate(id)}
className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded text-neutral-900 backdrop-blur-xl hover:bg-neutral-100 dark:text-neutral-100 dark:hover:bg-neutral-900" className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded text-neutral-900 backdrop-blur-xl hover:bg-neutral-100 dark:text-neutral-100 dark:hover:bg-neutral-900"
> >
<CancelIcon className="h-3 w-3" /> <CancelIcon className="h-3 w-3" />

View File

@ -1,58 +1,70 @@
import { NDKEvent, NDKKind } from '@nostr-dev-kit/ndk'; import { NDKEvent, NDKKind } from '@nostr-dev-kit/ndk';
import { useQuery } from '@tanstack/react-query'; import { useInfiniteQuery } from '@tanstack/react-query';
import { useCallback } from 'react'; import { useMemo } from 'react';
import { VList } from 'virtua'; import { VList } from 'virtua';
import { useNDK } from '@libs/ndk/provider'; import { useNDK } from '@libs/ndk/provider';
import { LoaderIcon } from '@shared/icons'; import { ArrowRightCircleIcon, LoaderIcon } from '@shared/icons';
import { ArticleNote, NoteWrapper } from '@shared/notes'; import { ArticleNote, NoteWrapper } from '@shared/notes';
import { TitleBar } from '@shared/titleBar'; import { TitleBar } from '@shared/titleBar';
import { WidgetWrapper } from '@shared/widgets'; import { WidgetWrapper } from '@shared/widgets';
import { FETCH_LIMIT } from '@stores/constants';
import { Widget } from '@utils/types'; import { Widget } from '@utils/types';
export function GlobalArticlesWidget({ params }: { params: Widget }) { export function GlobalArticlesWidget({ params }: { params: Widget }) {
const { ndk } = useNDK(); const { ndk, relayUrls, fetcher } = useNDK();
const { status, data } = useQuery({ const { status, data, hasNextPage, isFetchingNextPage, fetchNextPage } =
queryKey: ['global-articles'], useInfiniteQuery({
queryFn: async () => { queryKey: ['global-articles'],
const events = await ndk.fetchEvents({ initialPageParam: 0,
kinds: [NDKKind.Article], queryFn: async ({
limit: 200, signal,
}); pageParam,
const sortedEvents = [...events].sort((x, y) => y.created_at - x.created_at); }: {
return sortedEvents; signal: AbortSignal;
}, pageParam: number;
refetchOnWindowFocus: false, }) => {
}); const events = await fetcher.fetchLatestEvents(
relayUrls,
{
kinds: [NDKKind.Article],
},
FETCH_LIMIT,
{ asOf: pageParam === 0 ? undefined : pageParam, abortSignal: signal }
);
// render event match event kind const ndkEvents = events.map((event) => {
const renderItem = useCallback( return new NDKEvent(ndk, event);
(event: NDKEvent) => { });
return (
<NoteWrapper key={event.id} event={event}> return ndkEvents.sort((a, b) => b.created_at - a.created_at);
<ArticleNote /> },
</NoteWrapper> getNextPageParam: (lastPage) => {
); const lastEvent = lastPage.at(-1);
}, if (!lastEvent) return;
return lastEvent.created_at - 1;
},
refetchOnWindowFocus: false,
refetchOnReconnect: false,
});
const allEvents = useMemo(
() => (data ? data.pages.flatMap((page) => page) : []),
[data] [data]
); );
return ( return (
<WidgetWrapper> <WidgetWrapper>
<TitleBar id={params.id} title={params.title} /> <TitleBar id={params.id} title={params.title} />
<div className="flex-1"> <VList className="flex-1">
{status === 'pending' ? ( {status === 'pending' ? (
<div className="flex h-full w-full items-center justify-center "> <div className="flex h-full w-full items-center justify-center">
<div className="inline-flex flex-col items-center justify-center gap-2"> <LoaderIcon className="h-5 w-5 animate-spin" />
<LoaderIcon className="h-5 w-5 animate-spin text-black dark:text-white" />
<p className="text-sm font-medium text-neutral-500 dark:text-neutral-400">
Loading article...
</p>
</div>
</div> </div>
) : data.length === 0 ? ( ) : allEvents.length === 0 ? (
<div className="flex h-full w-full flex-col items-center justify-center px-3"> <div className="flex h-full w-full flex-col items-center justify-center px-3">
<div className="flex flex-col items-center gap-4"> <div className="flex flex-col items-center gap-4">
<img src="/ghost.png" alt="empty feeds" className="h-16 w-16" /> <img src="/ghost.png" alt="empty feeds" className="h-16 w-16" />
@ -67,12 +79,32 @@ export function GlobalArticlesWidget({ params }: { params: Widget }) {
</div> </div>
</div> </div>
) : ( ) : (
<VList className="h-full" style={{ contentVisibility: 'auto' }}> allEvents.map((item) => (
{data.map((item) => renderItem(item))} <NoteWrapper key={item.id} event={item}>
<div className="h-14" /> <ArticleNote />
</VList> </NoteWrapper>
))
)} )}
</div> <div className="flex h-16 items-center justify-center px-3 pb-3">
{hasNextPage ? (
<button
type="button"
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetchingNextPage}
className="inline-flex h-10 w-max items-center justify-center gap-2 rounded-full bg-blue-500 px-6 font-medium text-white hover:bg-blue-600 focus:outline-none"
>
{isFetchingNextPage ? (
<LoaderIcon className="h-4 w-4 animate-spin" />
) : (
<>
<ArrowRightCircleIcon className="h-5 w-5" />
Load more
</>
)}
</button>
) : null}
</div>
</VList>
</WidgetWrapper> </WidgetWrapper>
); );
} }

View File

@ -1,66 +1,76 @@
import { NDKEvent } from '@nostr-dev-kit/ndk'; import { NDKEvent } from '@nostr-dev-kit/ndk';
import { useQuery } from '@tanstack/react-query'; import { useInfiniteQuery } from '@tanstack/react-query';
import { useCallback } from 'react'; import { useMemo } from 'react';
import { VList } from 'virtua'; import { VList } from 'virtua';
import { useNDK } from '@libs/ndk/provider'; import { useNDK } from '@libs/ndk/provider';
import { LoaderIcon } from '@shared/icons'; import { ArrowRightCircleIcon, LoaderIcon } from '@shared/icons';
import { FileNote, NoteWrapper } from '@shared/notes'; import { FileNote, NoteWrapper } from '@shared/notes';
import { TitleBar } from '@shared/titleBar'; import { TitleBar } from '@shared/titleBar';
import { WidgetWrapper } from '@shared/widgets'; import { WidgetWrapper } from '@shared/widgets';
import { nHoursAgo } from '@utils/date'; import { FETCH_LIMIT } from '@stores/constants';
import { Widget } from '@utils/types'; import { Widget } from '@utils/types';
export function GlobalFilesWidget({ params }: { params: Widget }) { export function GlobalFilesWidget({ params }: { params: Widget }) {
const { ndk } = useNDK(); const { ndk, relayUrls, fetcher } = useNDK();
const { status, data } = useQuery({ const { status, data, hasNextPage, isFetchingNextPage, fetchNextPage } =
queryKey: ['global-file-sharing'], useInfiniteQuery({
queryFn: async () => { queryKey: ['global-files'],
const events = await ndk.fetchEvents({ initialPageParam: 0,
// @ts-expect-error, NDK not support file metadata yet queryFn: async ({
kinds: [1063], signal,
since: nHoursAgo(24), pageParam,
}); }: {
const sortedEvents = [...events].sort((x, y) => y.created_at - x.created_at); signal: AbortSignal;
return sortedEvents; pageParam: number;
}, }) => {
refetchOnWindowFocus: false, const events = await fetcher.fetchLatestEvents(
}); relayUrls,
{
kinds: [1063],
},
FETCH_LIMIT,
{ asOf: pageParam === 0 ? undefined : pageParam, abortSignal: signal }
);
// render event match event kind const ndkEvents = events.map((event) => {
const renderItem = useCallback( return new NDKEvent(ndk, event);
(event: NDKEvent) => { });
return (
<NoteWrapper key={event.id} event={event}> return ndkEvents.sort((a, b) => b.created_at - a.created_at);
<FileNote /> },
</NoteWrapper> getNextPageParam: (lastPage) => {
); const lastEvent = lastPage.at(-1);
}, if (!lastEvent) return;
return lastEvent.created_at - 1;
},
refetchOnWindowFocus: false,
refetchOnReconnect: false,
});
const allEvents = useMemo(
() => (data ? data.pages.flatMap((page) => page) : []),
[data] [data]
); );
return ( return (
<WidgetWrapper> <WidgetWrapper>
<TitleBar id={params.id} title={params.title} /> <TitleBar id={params.id} title={params.title} />
<div className="flex-1"> <VList className="flex-1">
{status === 'pending' ? ( {status === 'pending' ? (
<div className="flex h-full w-full items-center justify-center "> <div className="flex h-full w-full items-center justify-center">
<div className="inline-flex flex-col items-center justify-center gap-2"> <LoaderIcon className="h-5 w-5 animate-spin" />
<LoaderIcon className="h-5 w-5 animate-spin text-black dark:text-white" />
<p className="text-sm font-medium text-neutral-500 dark:text-neutral-400">
Loading file sharing event...
</p>
</div>
</div> </div>
) : data.length === 0 ? ( ) : allEvents.length === 0 ? (
<div className="flex h-full w-full flex-col items-center justify-center px-3"> <div className="flex h-full w-full flex-col items-center justify-center px-3">
<div className="flex flex-col items-center gap-4"> <div className="flex flex-col items-center gap-4">
<img src="/ghost.png" alt="empty feeds" className="h-16 w-16" /> <img src="/ghost.png" alt="empty feeds" className="h-16 w-16" />
<div className="text-center"> <div className="text-center">
<h3 className="font-semibold leading-tight text-neutral-900 dark:text-neutral-100"> <h3 className="font-semibold leading-tight text-neutral-900 dark:text-neutral-100">
Oops, it looks like there are no file sharing events. Oops, it looks like there are no files.
</h3> </h3>
<p className="text-neutral-500 dark:text-neutral-400"> <p className="text-neutral-500 dark:text-neutral-400">
You can close this widget You can close this widget
@ -69,12 +79,32 @@ export function GlobalFilesWidget({ params }: { params: Widget }) {
</div> </div>
</div> </div>
) : ( ) : (
<VList className="h-full" style={{ contentVisibility: 'auto' }}> allEvents.map((item) => (
{data.map((item) => renderItem(item))} <NoteWrapper key={item.id} event={item}>
<div className="h-14" /> <FileNote />
</VList> </NoteWrapper>
))
)} )}
</div> <div className="flex h-16 items-center justify-center px-3 pb-3">
{hasNextPage ? (
<button
type="button"
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetchingNextPage}
className="inline-flex h-10 w-max items-center justify-center gap-2 rounded-full bg-blue-500 px-6 font-medium text-white hover:bg-blue-600 focus:outline-none"
>
{isFetchingNextPage ? (
<LoaderIcon className="h-4 w-4 animate-spin" />
) : (
<>
<ArrowRightCircleIcon className="h-5 w-5" />
Load more
</>
)}
</button>
) : null}
</div>
</VList>
</WidgetWrapper> </WidgetWrapper>
); );
} }

View File

@ -1,11 +1,11 @@
import { NDKEvent, NDKKind } from '@nostr-dev-kit/ndk'; import { NDKEvent, NDKKind } from '@nostr-dev-kit/ndk';
import { useQuery } from '@tanstack/react-query'; import { useInfiniteQuery } from '@tanstack/react-query';
import { useCallback } from 'react'; import { useCallback, useMemo } from 'react';
import { VList } from 'virtua'; import { VList } from 'virtua';
import { useNDK } from '@libs/ndk/provider'; import { useNDK } from '@libs/ndk/provider';
import { LoaderIcon } from '@shared/icons'; import { ArrowRightCircleIcon, LoaderIcon } from '@shared/icons';
import { import {
ArticleNote, ArticleNote,
FileNote, FileNote,
@ -17,74 +17,94 @@ import {
import { TitleBar } from '@shared/titleBar'; import { TitleBar } from '@shared/titleBar';
import { WidgetWrapper } from '@shared/widgets'; import { WidgetWrapper } from '@shared/widgets';
import { nHoursAgo } from '@utils/date'; import { FETCH_LIMIT } from '@stores/constants';
import { Widget } from '@utils/types'; import { Widget } from '@utils/types';
export function GlobalHashtagWidget({ params }: { params: Widget }) { export function GlobalHashtagWidget({ params }: { params: Widget }) {
const { ndk } = useNDK(); const { ndk, relayUrls, fetcher } = useNDK();
const { status, data } = useQuery({ const { status, data, hasNextPage, isFetchingNextPage, fetchNextPage } =
queryKey: ['hashtag-' + params.title], useInfiniteQuery({
queryFn: async () => { queryKey: ['hashtag-' + params.title],
const events = await ndk.fetchEvents({ initialPageParam: 0,
kinds: [NDKKind.Text, NDKKind.Repost, NDKKind.Article], queryFn: async ({
'#t': [params.content], signal,
since: nHoursAgo(24), pageParam,
}); }: {
const sortedEvents = [...events].sort((x, y) => y.created_at - x.created_at); signal: AbortSignal;
return sortedEvents; pageParam: number;
}, }) => {
refetchOnWindowFocus: false, const events = await fetcher.fetchLatestEvents(
}); relayUrls,
{
kinds: [NDKKind.Text, NDKKind.Repost, 1063, NDKKind.Article],
'#t': [params.content],
},
FETCH_LIMIT,
{ asOf: pageParam === 0 ? undefined : pageParam, abortSignal: signal }
);
// render event match event kind const ndkEvents = events.map((event) => {
const renderItem = useCallback( return new NDKEvent(ndk, event);
(event: NDKEvent) => { });
switch (event.kind) {
case NDKKind.Text: return ndkEvents.sort((a, b) => b.created_at - a.created_at);
return ( },
<NoteWrapper key={event.id} event={event}> getNextPageParam: (lastPage) => {
<TextNote /> const lastEvent = lastPage.at(-1);
</NoteWrapper> if (!lastEvent) return;
); return lastEvent.created_at - 1;
case NDKKind.Repost: },
return <Repost key={event.id} event={event} />; refetchOnWindowFocus: false,
case 1063: refetchOnReconnect: false,
return ( });
<NoteWrapper key={event.id} event={event}>
<FileNote /> const allEvents = useMemo(
</NoteWrapper> () => (data ? data.pages.flatMap((page) => page) : []),
);
case NDKKind.Article:
return (
<NoteWrapper key={event.id} event={event}>
<ArticleNote />
</NoteWrapper>
);
default:
return (
<NoteWrapper key={event.id} event={event}>
<UnknownNote />
</NoteWrapper>
);
}
},
[data] [data]
); );
// render event match event kind
const renderItem = useCallback((event: NDKEvent) => {
switch (event.kind) {
case NDKKind.Text:
return (
<NoteWrapper key={event.id} event={event}>
<TextNote />
</NoteWrapper>
);
case NDKKind.Repost:
return <Repost key={event.id} event={event} />;
case 1063:
return (
<NoteWrapper key={event.id} event={event}>
<FileNote />
</NoteWrapper>
);
case NDKKind.Article:
return (
<NoteWrapper key={event.id} event={event}>
<ArticleNote />
</NoteWrapper>
);
default:
return (
<NoteWrapper key={event.id} event={event}>
<UnknownNote />
</NoteWrapper>
);
}
}, []);
return ( return (
<WidgetWrapper> <WidgetWrapper>
<TitleBar id={params.id} title={params.title} /> <TitleBar id={params.id} title={params.title} />
<div className="flex-1"> <VList className="flex-1">
{status === 'pending' ? ( {status === 'pending' ? (
<div className="flex h-full w-full items-center justify-center"> <div className="flex h-full w-full items-center justify-center">
<div className="inline-flex flex-col items-center justify-center gap-2"> <LoaderIcon className="h-5 w-5 animate-spin" />
<LoaderIcon className="h-5 w-5 animate-spin text-black dark:text-white" />
<p className="text-sm font-medium text-neutral-500 dark:text-neutral-400">
Loading event related to the hashtag {params.title}...
</p>
</div>
</div> </div>
) : data.length === 0 ? ( ) : allEvents.length === 0 ? (
<div className="flex h-full w-full flex-col items-center justify-center px-3"> <div className="flex h-full w-full flex-col items-center justify-center px-3">
<div className="flex flex-col items-center gap-4"> <div className="flex flex-col items-center gap-4">
<img src="/ghost.png" alt="empty feeds" className="h-16 w-16" /> <img src="/ghost.png" alt="empty feeds" className="h-16 w-16" />
@ -93,18 +113,34 @@ export function GlobalHashtagWidget({ params }: { params: Widget }) {
Oops, it looks like there are no events related to {params.title}. Oops, it looks like there are no events related to {params.title}.
</h3> </h3>
<p className="text-neutral-500 dark:text-neutral-400"> <p className="text-neutral-500 dark:text-neutral-400">
You can close this widget or try with other hashtag You can close this widget
</p> </p>
</div> </div>
</div> </div>
</div> </div>
) : ( ) : (
<VList className="h-full" style={{ contentVisibility: 'auto' }}> allEvents.map((item) => renderItem(item))
{data.map((item) => renderItem(item))}
<div className="h-16" />
</VList>
)} )}
</div> <div className="flex h-16 items-center justify-center px-3 pb-3">
{hasNextPage ? (
<button
type="button"
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetchingNextPage}
className="inline-flex h-10 w-max items-center justify-center gap-2 rounded-full bg-blue-500 px-6 font-medium text-white hover:bg-blue-600 focus:outline-none"
>
{isFetchingNextPage ? (
<LoaderIcon className="h-4 w-4 animate-spin" />
) : (
<>
<ArrowRightCircleIcon className="h-5 w-5" />
Load more
</>
)}
</button>
) : null}
</div>
</VList>
</WidgetWrapper> </WidgetWrapper>
); );
} }

View File

@ -1,11 +1,9 @@
export * from './wrapper'; export * from './wrapper';
export * from './local/feeds'; export * from './local/feeds';
export * from './local/network';
export * from './local/user'; export * from './local/user';
export * from './local/thread'; export * from './local/thread';
export * from './local/files'; export * from './local/files';
export * from './local/articles'; export * from './local/articles';
export * from './local/follows';
export * from './global/articles'; export * from './global/articles';
export * from './global/files'; export * from './global/files';
export * from './global/hashtag'; export * from './global/hashtag';
@ -13,7 +11,5 @@ export * from './nostrBand/trendingNotes';
export * from './nostrBand/trendingAccounts'; export * from './nostrBand/trendingAccounts';
export * from './tmp/feeds'; export * from './tmp/feeds';
export * from './tmp/hashtag'; export * from './tmp/hashtag';
export * from './other/learnNostr';
export * from './eventLoader';
export * from './newsfeed'; export * from './newsfeed';
export * from './notification'; export * from './notification';

View File

@ -1,8 +1,9 @@
import { NDKEvent, NDKKind } from '@nostr-dev-kit/ndk'; import { NDKEvent, NDKKind } from '@nostr-dev-kit/ndk';
import { useInfiniteQuery } from '@tanstack/react-query'; import { useInfiniteQuery } from '@tanstack/react-query';
import { useCallback, useMemo } from 'react'; import { useMemo } from 'react';
import { VList } from 'virtua'; import { VList } from 'virtua';
import { useNDK } from '@libs/ndk/provider';
import { useStorage } from '@libs/storage/provider'; import { useStorage } from '@libs/storage/provider';
import { ArrowRightCircleIcon, LoaderIcon } from '@shared/icons'; import { ArrowRightCircleIcon, LoaderIcon } from '@shared/icons';
@ -10,52 +11,63 @@ import { ArticleNote, NoteWrapper } from '@shared/notes';
import { TitleBar } from '@shared/titleBar'; import { TitleBar } from '@shared/titleBar';
import { WidgetWrapper } from '@shared/widgets'; import { WidgetWrapper } from '@shared/widgets';
import { DBEvent, Widget } from '@utils/types'; import { FETCH_LIMIT } from '@stores/constants';
import { Widget } from '@utils/types';
export function LocalArticlesWidget({ params }: { params: Widget }) { export function LocalArticlesWidget({ params }: { params: Widget }) {
const { db } = useStorage(); const { db } = useStorage();
const { ndk, relayUrls, fetcher } = useNDK();
const { status, data, hasNextPage, isFetchingNextPage, fetchNextPage } = const { status, data, hasNextPage, isFetchingNextPage, fetchNextPage } =
useInfiniteQuery({ useInfiniteQuery({
queryKey: ['local-articles'], queryKey: ['local-articles'],
initialPageParam: 0, initialPageParam: 0,
queryFn: async ({ pageParam = 0 }) => { queryFn: async ({
return await db.getAllEventsByKinds([NDKKind.Article], 20, pageParam); signal,
pageParam,
}: {
signal: AbortSignal;
pageParam: number;
}) => {
const events = await fetcher.fetchLatestEvents(
relayUrls,
{
kinds: [NDKKind.Article],
authors: db.account.circles,
},
FETCH_LIMIT,
{ asOf: pageParam === 0 ? undefined : pageParam, abortSignal: signal }
);
const ndkEvents = events.map((event) => {
return new NDKEvent(ndk, event);
});
return ndkEvents.sort((a, b) => b.created_at - a.created_at);
}, },
getNextPageParam: (lastPage) => lastPage.nextCursor, getNextPageParam: (lastPage) => {
const lastEvent = lastPage.at(-1);
if (!lastEvent) return;
return lastEvent.created_at - 1;
},
refetchOnWindowFocus: false,
refetchOnReconnect: false,
}); });
const dbEvents = useMemo( const allEvents = useMemo(
() => (data ? data.pages.flatMap((d: { data: DBEvent[] }) => d.data) : []), () => (data ? data.pages.flatMap((page) => page) : []),
[data]
);
// render event match event kind
const renderItem = useCallback(
(dbEvent: DBEvent) => {
const event: NDKEvent = JSON.parse(dbEvent.event as string);
return (
<NoteWrapper key={event.id} event={event}>
<ArticleNote />
</NoteWrapper>
);
},
[data] [data]
); );
return ( return (
<WidgetWrapper> <WidgetWrapper>
<TitleBar id={params.id} title={params.title} /> <TitleBar id={params.id} title={params.title} />
<div className="flex-1"> <VList className="flex-1">
{status === 'pending' ? ( {status === 'pending' ? (
<div className="flex h-full w-full items-center justify-center "> <div className="flex h-full w-full items-center justify-center">
<div className="inline-flex flex-col items-center justify-center gap-2"> <LoaderIcon className="h-5 w-5 animate-spin" />
<LoaderIcon className="h-5 w-5 animate-spin text-black dark:text-white" />
<p className="text-sm font-medium text-neutral-500 dark:text-neutral-400">
Loading article...
</p>
</div>
</div> </div>
) : dbEvents.length === 0 ? ( ) : allEvents.length === 0 ? (
<div className="flex h-full w-full flex-col items-center justify-center px-3"> <div className="flex h-full w-full flex-col items-center justify-center px-3">
<div className="flex flex-col items-center gap-4"> <div className="flex flex-col items-center gap-4">
<img src="/ghost.png" alt="empty feeds" className="h-16 w-16" /> <img src="/ghost.png" alt="empty feeds" className="h-16 w-16" />
@ -70,38 +82,32 @@ export function LocalArticlesWidget({ params }: { params: Widget }) {
</div> </div>
</div> </div>
) : ( ) : (
<VList className="h-full" style={{ contentVisibility: 'auto' }}> allEvents.map((item) => (
{dbEvents.map((item) => renderItem(item))} <NoteWrapper key={item.id} event={item}>
<div className="flex items-center justify-center px-3 py-1.5"> <ArticleNote />
{dbEvents.length > 0 ? ( </NoteWrapper>
<button ))
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetchingNextPage}
className="inline-flex h-10 w-max items-center justify-center gap-2 rounded-full bg-blue-500 px-6 font-medium text-white hover:bg-blue-600 focus:outline-none"
>
{isFetchingNextPage ? (
<>
<span>Loading...</span>
<LoaderIcon className="h-5 w-5 animate-spin text-neutral-900 dark:text-neutral-100" />
</>
) : hasNextPage ? (
<>
<ArrowRightCircleIcon className="h-5 w-5 text-neutral-900 dark:text-neutral-100" />
<span>Load more</span>
</>
) : (
<>
<ArrowRightCircleIcon className="h-5 w-5 text-neutral-900 dark:text-neutral-100" />
<span>Nothing more to load</span>
</>
)}
</button>
) : null}
</div>
<div className="h-14" />
</VList>
)} )}
</div> <div className="flex h-16 items-center justify-center px-3 pb-3">
{hasNextPage ? (
<button
type="button"
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetchingNextPage}
className="inline-flex h-10 w-max items-center justify-center gap-2 rounded-full bg-blue-500 px-6 font-medium text-white hover:bg-blue-600 focus:outline-none"
>
{isFetchingNextPage ? (
<LoaderIcon className="h-4 w-4 animate-spin" />
) : (
<>
<ArrowRightCircleIcon className="h-5 w-5" />
Load more
</>
)}
</button>
) : null}
</div>
</VList>
</WidgetWrapper> </WidgetWrapper>
); );
} }

View File

@ -3,141 +3,132 @@ import { useInfiniteQuery } from '@tanstack/react-query';
import { useCallback, useMemo } from 'react'; import { useCallback, useMemo } from 'react';
import { VList } from 'virtua'; import { VList } from 'virtua';
import { useStorage } from '@libs/storage/provider'; import { useNDK } from '@libs/ndk/provider';
import { ArrowRightCircleIcon, LoaderIcon } from '@shared/icons'; import { ArrowRightCircleIcon, LoaderIcon } from '@shared/icons';
import { import {
ArticleNote, MemoizedArticleNote,
FileNote, MemoizedFileNote,
MemoizedRepost,
MemoizedTextNote,
NoteSkeleton,
NoteWrapper, NoteWrapper,
Repost,
TextNote,
UnknownNote, UnknownNote,
} from '@shared/notes'; } from '@shared/notes';
import { TitleBar } from '@shared/titleBar'; import { TitleBar } from '@shared/titleBar';
import { WidgetWrapper } from '@shared/widgets'; import { WidgetWrapper } from '@shared/widgets';
import { DBEvent, Widget } from '@utils/types'; import { FETCH_LIMIT } from '@stores/constants';
import { Widget } from '@utils/types';
export function LocalFeedsWidget({ params }: { params: Widget }) { export function LocalFeedsWidget({ params }: { params: Widget }) {
const { db } = useStorage(); const { relayUrls, ndk, fetcher } = useNDK();
const { status, data, hasNextPage, isFetchingNextPage, fetchNextPage } = const { status, data, hasNextPage, isFetchingNextPage, fetchNextPage } =
useInfiniteQuery({ useInfiniteQuery({
queryKey: ['group-feeds-' + params.id], queryKey: ['group-feeds-' + params.id],
initialPageParam: 0, initialPageParam: 0,
queryFn: async ({ pageParam = 0 }) => { queryFn: async ({
const authors = JSON.parse(params.content); signal,
return await db.getAllEventsByAuthors(authors, 20, pageParam); pageParam,
}: {
signal: AbortSignal;
pageParam: number;
}) => {
const events = await fetcher.fetchLatestEvents(
relayUrls,
{
kinds: [NDKKind.Text, NDKKind.Repost, 1063, NDKKind.Article],
authors: JSON.parse(params.content),
},
FETCH_LIMIT,
{ asOf: pageParam === 0 ? undefined : pageParam, abortSignal: signal }
);
const ndkEvents = events.map((event) => {
return new NDKEvent(ndk, event);
});
return ndkEvents.sort((a, b) => b.created_at - a.created_at);
}, },
getNextPageParam: (lastPage) => lastPage.nextCursor, getNextPageParam: (lastPage) => {
const lastEvent = lastPage.at(-1);
if (!lastEvent) return;
return lastEvent.created_at - 1;
},
refetchOnWindowFocus: false,
refetchOnReconnect: false,
}); });
const dbEvents = useMemo( const allEvents = useMemo(
() => (data ? data.pages.flatMap((d: { data: DBEvent[] }) => d.data) : []), () => (data ? data.pages.flatMap((page) => page) : []),
[data] [data]
); );
// render event match event kind const renderItem = useCallback((event: NDKEvent) => {
const renderItem = useCallback( switch (event.kind) {
(dbEvent: DBEvent) => { case NDKKind.Text:
const event: NDKEvent = JSON.parse(dbEvent.event as string); return (
switch (event.kind) { <NoteWrapper key={event.id} event={event}>
case NDKKind.Text: <MemoizedTextNote />
return ( </NoteWrapper>
<NoteWrapper );
key={dbEvent.id + dbEvent.root_id + dbEvent.reply_id} case NDKKind.Repost:
event={event} return <MemoizedRepost key={event.id} event={event} />;
root={dbEvent.root_id} case 1063:
reply={dbEvent.reply_id} return (
> <NoteWrapper key={event.id} event={event}>
<TextNote /> <MemoizedFileNote />
</NoteWrapper> </NoteWrapper>
); );
case NDKKind.Repost: case NDKKind.Article:
return <Repost key={dbEvent.id} event={event} />; return (
case 1063: <NoteWrapper key={event.id} event={event}>
return ( <MemoizedArticleNote />
<NoteWrapper key={dbEvent.id} event={event}> </NoteWrapper>
<FileNote /> );
</NoteWrapper> default:
); return (
case NDKKind.Article: <NoteWrapper key={event.id} event={event}>
return ( <UnknownNote />
<NoteWrapper key={dbEvent.id} event={event}> </NoteWrapper>
<ArticleNote /> );
</NoteWrapper> }
); }, []);
default:
return (
<NoteWrapper key={dbEvent.id} event={event}>
<UnknownNote />
</NoteWrapper>
);
}
},
[dbEvents]
);
return ( return (
<WidgetWrapper> <WidgetWrapper>
<TitleBar id={params.id} title={params.title} /> <TitleBar id={params.id} title={params.title} />
<div className="flex-1"> <VList className="flex-1">
{status === 'pending' ? ( {status === 'pending' ? (
<div className="flex h-full w-full items-center justify-center"> <div className="px-3 py-1.5">
<div className="inline-flex flex-col items-center justify-center gap-2"> <div className="rounded-xl bg-neutral-100 px-3 py-3 dark:bg-neutral-900">
<LoaderIcon className="h-5 w-5 animate-spin text-black dark:text-white" /> <NoteSkeleton />
<p className="text-sm font-medium text-neutral-500 dark:text-neutral-400">
Loading newsfeed...
</p>
</div>
</div>
) : dbEvents.length === 0 ? (
<div className="flex h-full w-full flex-col items-center justify-center px-3">
<div className="flex flex-col items-center gap-4">
<img src="/ghost.png" alt="empty feeds" className="h-16 w-16" />
<div className="text-center">
<h3 className="font-semibold leading-tight text-neutral-900 dark:text-neutral-100">
Oops, it looks like there are no posts.
</h3>
<p className="text-neutral-500 dark:text-neutral-400">
You can close this widget
</p>
</div>
</div> </div>
</div> </div>
) : ( ) : (
<VList className="h-full" style={{ contentVisibility: 'auto' }}> allEvents.map((item) => renderItem(item))
{dbEvents.map((item) => renderItem(item))}
<div className="flex items-center justify-center px-3 py-1.5">
{dbEvents.length > 0 ? (
<button
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetchingNextPage}
className="inline-flex h-10 w-max items-center justify-center gap-2 rounded-full bg-blue-500 px-6 font-medium text-white hover:bg-blue-600 focus:outline-none"
>
{isFetchingNextPage ? (
<>
<span>Loading...</span>
<LoaderIcon className="h-5 w-5 animate-spin text-neutral-900 dark:text-neutral-100" />
</>
) : hasNextPage ? (
<>
<ArrowRightCircleIcon className="h-5 w-5 text-neutral-900 dark:text-neutral-100" />
<span>Load more</span>
</>
) : (
<>
<ArrowRightCircleIcon className="h-5 w-5 text-neutral-900 dark:text-neutral-100" />
<span>Nothing more to load</span>
</>
)}
</button>
) : null}
</div>
<div className="h-14" />
</VList>
)} )}
</div> <div className="flex h-16 items-center justify-center px-3 pb-3">
{hasNextPage ? (
<button
type="button"
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetchingNextPage}
className="inline-flex h-10 w-max items-center justify-center gap-2 rounded-full bg-blue-500 px-6 font-medium text-white hover:bg-blue-600 focus:outline-none"
>
{isFetchingNextPage ? (
<LoaderIcon className="h-4 w-4 animate-spin" />
) : (
<>
<ArrowRightCircleIcon className="h-5 w-5" />
Load more
</>
)}
</button>
) : null}
</div>
</VList>
</WidgetWrapper> </WidgetWrapper>
); );
} }

View File

@ -1,8 +1,9 @@
import { NDKEvent } from '@nostr-dev-kit/ndk'; import { NDKEvent } from '@nostr-dev-kit/ndk';
import { useInfiniteQuery } from '@tanstack/react-query'; import { useInfiniteQuery } from '@tanstack/react-query';
import { useCallback, useMemo } from 'react'; import { useMemo } from 'react';
import { VList } from 'virtua'; import { VList } from 'virtua';
import { useNDK } from '@libs/ndk/provider';
import { useStorage } from '@libs/storage/provider'; import { useStorage } from '@libs/storage/provider';
import { ArrowRightCircleIcon, LoaderIcon } from '@shared/icons'; import { ArrowRightCircleIcon, LoaderIcon } from '@shared/icons';
@ -10,58 +11,69 @@ import { FileNote, NoteWrapper } from '@shared/notes';
import { TitleBar } from '@shared/titleBar'; import { TitleBar } from '@shared/titleBar';
import { WidgetWrapper } from '@shared/widgets'; import { WidgetWrapper } from '@shared/widgets';
import { DBEvent, Widget } from '@utils/types'; import { FETCH_LIMIT } from '@stores/constants';
import { Widget } from '@utils/types';
export function LocalFilesWidget({ params }: { params: Widget }) { export function LocalFilesWidget({ params }: { params: Widget }) {
const { db } = useStorage(); const { db } = useStorage();
const { ndk, relayUrls, fetcher } = useNDK();
const { status, data, hasNextPage, isFetchingNextPage, fetchNextPage } = const { status, data, hasNextPage, isFetchingNextPage, fetchNextPage } =
useInfiniteQuery({ useInfiniteQuery({
queryKey: ['local-file-sharing'], queryKey: ['local-files'],
initialPageParam: 0, initialPageParam: 0,
queryFn: async ({ pageParam = 0 }) => { queryFn: async ({
return await db.getAllEventsByKinds([1063], 20, pageParam); signal,
pageParam,
}: {
signal: AbortSignal;
pageParam: number;
}) => {
const events = await fetcher.fetchLatestEvents(
relayUrls,
{
kinds: [1063],
authors: db.account.circles,
},
FETCH_LIMIT,
{ asOf: pageParam === 0 ? undefined : pageParam, abortSignal: signal }
);
const ndkEvents = events.map((event) => {
return new NDKEvent(ndk, event);
});
return ndkEvents.sort((a, b) => b.created_at - a.created_at);
}, },
getNextPageParam: (lastPage) => lastPage.nextCursor, getNextPageParam: (lastPage) => {
const lastEvent = lastPage.at(-1);
if (!lastEvent) return;
return lastEvent.created_at - 1;
},
refetchOnWindowFocus: false,
refetchOnReconnect: false,
}); });
const dbEvents = useMemo( const allEvents = useMemo(
() => (data ? data.pages.flatMap((d: { data: DBEvent[] }) => d.data) : []), () => (data ? data.pages.flatMap((page) => page) : []),
[data]
);
// render event match event kind
const renderItem = useCallback(
(dbEvent: DBEvent) => {
const event: NDKEvent = JSON.parse(dbEvent.event as string);
return (
<NoteWrapper key={event.id} event={event}>
<FileNote />
</NoteWrapper>
);
},
[data] [data]
); );
return ( return (
<WidgetWrapper> <WidgetWrapper>
<TitleBar id={params.id} title={params.title} /> <TitleBar id={params.id} title={params.title} />
<div className="flex-1"> <VList className="flex-1">
{status === 'pending' ? ( {status === 'pending' ? (
<div className="flex h-full w-full items-center justify-center "> <div className="flex h-full w-full items-center justify-center">
<div className="inline-flex flex-col items-center justify-center gap-2"> <LoaderIcon className="h-5 w-5 animate-spin" />
<LoaderIcon className="h-5 w-5 animate-spin text-black dark:text-white" />
<p className="text-sm font-medium text-neutral-500 dark:text-neutral-400">
Loading file sharing event...
</p>
</div>
</div> </div>
) : dbEvents.length === 0 ? ( ) : allEvents.length === 0 ? (
<div className="flex h-full w-full flex-col items-center justify-center px-3"> <div className="flex h-full w-full flex-col items-center justify-center px-3">
<div className="flex flex-col items-center gap-4"> <div className="flex flex-col items-center gap-4">
<img src="/ghost.png" alt="empty feeds" className="h-16 w-16" /> <img src="/ghost.png" alt="empty feeds" className="h-16 w-16" />
<div className="text-center"> <div className="text-center">
<h3 className="font-semibold leading-tight text-neutral-900 dark:text-neutral-100"> <h3 className="font-semibold leading-tight text-neutral-900 dark:text-neutral-100">
Oops, it looks like there are no file sharing events. Oops, it looks like there are no files.
</h3> </h3>
<p className="text-neutral-500 dark:text-neutral-400"> <p className="text-neutral-500 dark:text-neutral-400">
You can close this widget You can close this widget
@ -70,38 +82,32 @@ export function LocalFilesWidget({ params }: { params: Widget }) {
</div> </div>
</div> </div>
) : ( ) : (
<VList className="h-full" style={{ contentVisibility: 'auto' }}> allEvents.map((item) => (
{dbEvents.map((item) => renderItem(item))} <NoteWrapper key={item.id} event={item}>
<div className="flex items-center justify-center px-3 py-1.5"> <FileNote />
{dbEvents.length > 0 ? ( </NoteWrapper>
<button ))
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetchingNextPage}
className="inline-flex h-10 w-max items-center justify-center gap-2 rounded-full bg-blue-500 px-6 font-medium text-white hover:bg-blue-600 focus:outline-none"
>
{isFetchingNextPage ? (
<>
<span>Loading...</span>
<LoaderIcon className="h-5 w-5 animate-spin text-neutral-900 dark:text-neutral-100" />
</>
) : hasNextPage ? (
<>
<ArrowRightCircleIcon className="h-5 w-5 text-neutral-900 dark:text-neutral-100" />
<span>Load more</span>
</>
) : (
<>
<ArrowRightCircleIcon className="h-5 w-5 text-neutral-900 dark:text-neutral-100" />
<span>Nothing more to load</span>
</>
)}
</button>
) : null}
</div>
<div className="h-14" />
</VList>
)} )}
</div> <div className="flex h-16 items-center justify-center px-3 pb-3">
{hasNextPage ? (
<button
type="button"
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetchingNextPage}
className="inline-flex h-10 w-max items-center justify-center gap-2 rounded-full bg-blue-500 px-6 font-medium text-white hover:bg-blue-600 focus:outline-none"
>
{isFetchingNextPage ? (
<LoaderIcon className="h-4 w-4 animate-spin" />
) : (
<>
<ArrowRightCircleIcon className="h-5 w-5" />
Load more
</>
)}
</button>
) : null}
</div>
</VList>
</WidgetWrapper> </WidgetWrapper>
); );
} }

View File

@ -1,140 +0,0 @@
import { NDKEvent, NDKKind } from '@nostr-dev-kit/ndk';
import { useInfiniteQuery } from '@tanstack/react-query';
import { useCallback, useMemo } from 'react';
import { VList } from 'virtua';
import { useStorage } from '@libs/storage/provider';
import { ArrowRightCircleIcon, LoaderIcon } from '@shared/icons';
import {
MemoizedArticleNote,
MemoizedFileNote,
MemoizedRepost,
MemoizedTextNote,
NoteWrapper,
UnknownNote,
} from '@shared/notes';
import { TitleBar } from '@shared/titleBar';
import { WidgetWrapper } from '@shared/widgets';
import { DBEvent, Widget } from '@utils/types';
export function LocalFollowsWidget({ params }: { params: Widget }) {
const { db } = useStorage();
const { status, data, hasNextPage, isFetchingNextPage, fetchNextPage } =
useInfiniteQuery({
queryKey: ['follows-' + params.title],
initialPageParam: 0,
queryFn: async ({ pageParam = 0 }) => {
return await db.getAllEventsByAuthors(db.account.follows, 20, pageParam);
},
getNextPageParam: (lastPage) => lastPage.nextCursor,
});
const dbEvents = useMemo(
() => (data ? data.pages.flatMap((d: { data: DBEvent[] }) => d.data) : []),
[data]
);
// render event match event kind
const renderItem = useCallback(
(dbEvent: DBEvent) => {
const event: NDKEvent = JSON.parse(dbEvent.event as string);
switch (event.kind) {
case NDKKind.Text:
return (
<NoteWrapper
key={dbEvent.id + dbEvent.root_id + dbEvent.reply_id}
event={event}
>
<MemoizedTextNote />
</NoteWrapper>
);
case NDKKind.Repost:
return <MemoizedRepost key={dbEvent.id} event={event} />;
case 1063:
return (
<NoteWrapper key={dbEvent.id} event={event}>
<MemoizedFileNote />
</NoteWrapper>
);
case NDKKind.Article:
return (
<NoteWrapper key={dbEvent.id} event={event}>
<MemoizedArticleNote />
</NoteWrapper>
);
default:
return (
<NoteWrapper key={dbEvent.id} event={event}>
<UnknownNote />
</NoteWrapper>
);
}
},
[dbEvents]
);
return (
<WidgetWrapper>
<TitleBar id={params.id} title="Follows" />
<div className="flex-1">
{status === 'pending' ? (
<div className="flex h-full w-full items-center justify-center ">
<div className="inline-flex flex-col items-center justify-center gap-2">
<LoaderIcon className="h-5 w-5 animate-spin text-black dark:text-white" />
<p className="text-sm font-medium text-neutral-500 dark:text-neutral-400">
Loading post...
</p>
</div>
</div>
) : dbEvents.length === 0 ? (
<div className="flex h-full w-full flex-col items-center justify-center px-3">
<div className="flex flex-col items-center gap-4">
<img src="/ghost.png" alt="empty feeds" className="h-16 w-16" />
<div className="text-center">
<h3 className="font-semibold leading-tight text-neutral-900 dark:text-neutral-100">
Oops, it looks like there are no posts.
</h3>
<p className="text-neutral-500 dark:text-neutral-400">
You can close this widget
</p>
</div>
</div>
</div>
) : (
<VList className="h-full" style={{ contentVisibility: 'auto' }}>
{dbEvents.map((item) => renderItem(item))}
<div className="flex items-center justify-center px-3 py-1.5">
{dbEvents.length > 0 ? (
<button
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetchingNextPage}
className="inline-flex h-10 w-max items-center justify-center gap-2 rounded-full bg-blue-500 px-6 font-medium text-white hover:bg-blue-600 focus:outline-none"
>
{isFetchingNextPage ? (
<>
<span>Loading...</span>
<LoaderIcon className="h-5 w-5 animate-spin text-neutral-900 dark:text-neutral-100" />
</>
) : hasNextPage ? (
<>
<ArrowRightCircleIcon className="h-5 w-5 text-neutral-900 dark:text-neutral-100" />
<span>Load more</span>
</>
) : (
<>
<ArrowRightCircleIcon className="h-5 w-5 text-neutral-900 dark:text-neutral-100" />
<span>Nothing more to load</span>
</>
)}
</button>
) : null}
</div>
<div className="h-14" />
</VList>
)}
</div>
</WidgetWrapper>
);
}

View File

@ -26,14 +26,30 @@ export function LocalUserWidget({ params }: { params: Widget }) {
const { status, data } = useQuery({ const { status, data } = useQuery({
queryKey: ['user-posts', params.content], queryKey: ['user-posts', params.content],
queryFn: async () => { queryFn: async () => {
const rootIds = new Set();
const dedupQueue = new Set();
const events = await ndk.fetchEvents({ const events = await ndk.fetchEvents({
// @ts-expect-error, NDK not support file metadata yet // @ts-expect-error, NDK not support file metadata yet
kinds: [NDKKind.Text, NDKKind.Repost, 1063, NDKKind.Article], kinds: [NDKKind.Text, NDKKind.Repost, 1063, NDKKind.Article],
authors: [params.content], authors: [params.content],
since: nHoursAgo(24), since: nHoursAgo(24),
}); });
const sortedEvents = [...events].sort((x, y) => y.created_at - x.created_at);
return sortedEvents; const ndkEvents = [...events];
ndkEvents.forEach((event) => {
const tags = event.tags.filter((el) => el[0] === 'e');
if (tags && tags.length > 0) {
const rootId = tags.filter((el) => el[3] === 'root')[1] ?? tags[0][1];
if (rootIds.has(rootId)) return dedupQueue.add(event.id);
rootIds.add(rootId);
}
});
return ndkEvents
.filter((event) => !dedupQueue.has(event.id))
.sort((a, b) => b.created_at - a.created_at);
}, },
staleTime: Infinity, staleTime: Infinity,
refetchOnMount: false, refetchOnMount: false,

View File

@ -1,6 +1,6 @@
import { NDKEvent, NDKFilter, NDKKind } from '@nostr-dev-kit/ndk'; import { NDKEvent, NDKFilter, NDKKind } from '@nostr-dev-kit/ndk';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { useInfiniteQuery, useQueryClient } from '@tanstack/react-query';
import { useCallback, useEffect } from 'react'; import { useCallback, useEffect, useMemo } from 'react';
import { VList } from 'virtua'; import { VList } from 'virtua';
import { useNDK } from '@libs/ndk/provider'; import { useNDK } from '@libs/ndk/provider';
@ -19,92 +19,66 @@ import {
import { TitleBar } from '@shared/titleBar'; import { TitleBar } from '@shared/titleBar';
import { WidgetWrapper } from '@shared/widgets'; import { WidgetWrapper } from '@shared/widgets';
import { nHoursAgo } from '@utils/date';
import { useNostr } from '@utils/hooks/useNostr'; import { useNostr } from '@utils/hooks/useNostr';
export function NewsfeedWidget() { export function NewsfeedWidget() {
const queryClient = useQueryClient();
const { db } = useStorage(); const { db } = useStorage();
const { sub } = useNostr(); const { sub } = useNostr();
const { relayUrls, ndk, fetcher } = useNDK(); const { relayUrls, ndk, fetcher } = useNDK();
const { status, data } = useQuery({ const { status, data, hasNextPage, isFetchingNextPage, fetchNextPage } =
queryKey: ['newsfeed'], useInfiniteQuery({
queryFn: async ({ signal }: { signal: AbortSignal }) => { queryKey: ['newsfeed'],
const rootIds = new Set(); initialPageParam: 0,
const dedupQueue = new Set(); queryFn: async ({
signal,
pageParam,
}: {
signal: AbortSignal;
pageParam: number;
}) => {
const rootIds = new Set();
const dedupQueue = new Set();
const events = await fetcher.fetchAllEvents( const events = await fetcher.fetchLatestEvents(
relayUrls, relayUrls,
{ {
kinds: [NDKKind.Text, NDKKind.Repost, 1063, NDKKind.Article], kinds: [NDKKind.Text, NDKKind.Repost, 1063, NDKKind.Article],
authors: db.account.circles, authors: db.account.circles,
}, },
{ 50,
since: db.account.last_login_at === 0 ? nHoursAgo(4) : db.account.last_login_at, { asOf: pageParam === 0 ? undefined : pageParam, abortSignal: signal }
}, );
{ abortSignal: signal }
);
const ndkEvents = events.map((event) => { const ndkEvents = events.map((event) => {
return new NDKEvent(ndk, event); return new NDKEvent(ndk, event);
}); });
ndkEvents.forEach((event) => { ndkEvents.forEach((event) => {
const tags = event.tags.filter((el) => el[0] === 'e'); const tags = event.tags.filter((el) => el[0] === 'e');
if (tags && tags.length > 0) { if (tags && tags.length > 0) {
const rootId = tags.filter((el) => el[3] === 'root')[1] ?? tags[0][1]; const rootId = tags.filter((el) => el[3] === 'root')[1] ?? tags[0][1];
if (rootIds.has(rootId)) return dedupQueue.add(event.id); if (rootIds.has(rootId)) return dedupQueue.add(event.id);
rootIds.add(rootId); rootIds.add(rootId);
} }
}); });
return ndkEvents return ndkEvents
.filter((event) => !dedupQueue.has(event.id)) .filter((event) => !dedupQueue.has(event.id))
.sort((a, b) => b.created_at - a.created_at); .sort((a, b) => b.created_at - a.created_at);
}, },
}); getNextPageParam: (lastPage) => {
const lastEvent = lastPage.at(-1);
if (!lastEvent) return;
return lastEvent.created_at - 1;
},
});
const queryClient = useQueryClient(); const allEvents = useMemo(
const mutation = useMutation({ () => (data ? data.pages.flatMap((page) => page) : []),
mutationFn: async () => { [data]
const currentLastEvent = data.at(-1); );
const lastCreatedAt = currentLastEvent.created_at - 1;
const rootIds = new Set();
const dedupQueue = new Set();
const events = await fetcher.fetchLatestEvents(
relayUrls,
{
kinds: [NDKKind.Text, NDKKind.Repost, 1063, NDKKind.Article],
authors: db.account.circles,
},
100,
{
asOf: lastCreatedAt,
}
);
const ndkEvents = events.map((event) => {
return new NDKEvent(ndk, event);
});
ndkEvents.forEach((event) => {
const tags = event.tags.filter((el) => el[0] === 'e');
if (tags && tags.length > 0) {
const rootId = tags.filter((el) => el[3] === 'root')[1] ?? tags[0][1];
if (rootIds.has(rootId)) return dedupQueue.add(event.id);
rootIds.add(rootId);
}
});
return ndkEvents
.filter((event) => !dedupQueue.has(event.id))
.sort((a, b) => b.created_at - a.created_at);
},
onSuccess: async (data) => {
queryClient.setQueryData(['newsfeed'], (old: NDKEvent[]) => [...old, ...data]);
},
});
const renderItem = useCallback((event: NDKEvent) => { const renderItem = useCallback((event: NDKEvent) => {
switch (event.kind) { switch (event.kind) {
@ -138,46 +112,55 @@ export function NewsfeedWidget() {
}, []); }, []);
useEffect(() => { useEffect(() => {
if (db.account && db.account.circles.length > 0) { if (status === 'success' && db.account && db.account.circles.length > 0) {
queryClient.fetchQuery({ queryKey: ['notification'] });
const filter: NDKFilter = { const filter: NDKFilter = {
kinds: [NDKKind.Text, NDKKind.Repost], kinds: [NDKKind.Text, NDKKind.Repost],
authors: db.account.circles, authors: db.account.circles,
since: Math.floor(Date.now() / 1000), since: Math.floor(Date.now() / 1000),
}; };
sub(filter, async (event) => { sub(
queryClient.setQueryData(['newsfeed'], (old: NDKEvent[]) => [event, ...old]); filter,
}); async (event) => {
queryClient.setQueryData(['newsfeed'], (old: NDKEvent[]) => [event, ...old]);
},
false,
'newsfeed'
);
} }
}, []); }, [status]);
return ( return (
<WidgetWrapper> <WidgetWrapper>
<TitleBar id="9999" /> <TitleBar id="9999" />
<VList className="flex-1"> <VList className="flex-1">
{status === 'pending' ? ( {status === 'pending' ? (
<div> <div className="px-3 py-1.5">
<div className="px-3 py-1.5"> <div className="rounded-xl bg-neutral-100 px-3 py-3 dark:bg-neutral-900">
<div className="rounded-xl bg-neutral-100 px-3 py-3 dark:bg-neutral-900"> <NoteSkeleton />
<NoteSkeleton />
</div>
</div>
<div className="flex h-11 items-center justify-center">
<LoaderIcon className="h-4 w-4 animate-spin" />
</div> </div>
</div> </div>
) : ( ) : (
data.map((item) => renderItem(item)) allEvents.map((item) => renderItem(item))
)} )}
<div className="flex h-16 items-center justify-center px-3 pb-3"> <div className="flex h-16 items-center justify-center px-3 pb-3">
{data ? ( {hasNextPage ? (
<button <button
type="button" type="button"
onClick={() => mutation.mutate()} onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetchingNextPage}
className="inline-flex h-10 w-max items-center justify-center gap-2 rounded-full bg-blue-500 px-6 font-medium text-white hover:bg-blue-600 focus:outline-none" className="inline-flex h-10 w-max items-center justify-center gap-2 rounded-full bg-blue-500 px-6 font-medium text-white hover:bg-blue-600 focus:outline-none"
> >
<ArrowRightCircleIcon className="h-5 w-5" /> {isFetchingNextPage ? (
Load more <LoaderIcon className="h-4 w-4 animate-spin" />
) : (
<>
<ArrowRightCircleIcon className="h-5 w-5" />
Load more
</>
)}
</button> </button>
) : null} ) : null}
</div> </div>

View File

@ -1,59 +1,145 @@
import { NDKEvent } from '@nostr-dev-kit/ndk'; import { NDKEvent, NDKKind } from '@nostr-dev-kit/ndk';
import { useCallback, useEffect } from 'react'; import { useInfiniteQuery, useQueryClient } from '@tanstack/react-query';
import { useCallback, useEffect, useMemo } from 'react';
import { VList } from 'virtua'; import { VList } from 'virtua';
import { useNDK } from '@libs/ndk/provider';
import { useStorage } from '@libs/storage/provider'; import { useStorage } from '@libs/storage/provider';
import { LoaderIcon } from '@shared/icons'; import { ArrowRightCircleIcon, LoaderIcon } from '@shared/icons';
import { NoteSkeleton } from '@shared/notes';
import { NotifyNote } from '@shared/notification/notifyNote'; import { NotifyNote } from '@shared/notification/notifyNote';
import { TitleBar } from '@shared/titleBar'; import { TitleBar } from '@shared/titleBar';
import { WidgetWrapper } from '@shared/widgets'; import { WidgetWrapper } from '@shared/widgets';
import { useActivities } from '@stores/activities';
import { useNostr } from '@utils/hooks/useNostr'; import { useNostr } from '@utils/hooks/useNostr';
import { Widget } from '@utils/types'; import { sendNativeNotification } from '@utils/notification';
export function NotificationWidget() {
const queryClient = useQueryClient();
export function LocalNotificationWidget({ params }: { params: Widget }) {
const { db } = useStorage(); const { db } = useStorage();
const { getAllActivities } = useNostr(); const { sub } = useNostr();
const { ndk, relayUrls, fetcher } = useNDK();
const { status, data, hasNextPage, isFetchingNextPage, fetchNextPage } =
useInfiniteQuery({
queryKey: ['notification'],
initialPageParam: 0,
queryFn: async ({
signal,
pageParam,
}: {
signal: AbortSignal;
pageParam: number;
}) => {
const events = await fetcher.fetchLatestEvents(
relayUrls,
{
kinds: [NDKKind.Text, NDKKind.Repost, NDKKind.Reaction, NDKKind.Zap],
'#p': [db.account.pubkey],
},
50,
{ asOf: pageParam === 0 ? undefined : pageParam, abortSignal: signal }
);
const [activities, setActivities] = useActivities((state) => [ const ndkEvents = events.map((event) => {
state.activities, return new NDKEvent(ndk, event);
state.setActivities, });
]);
const renderEvent = useCallback( return ndkEvents.sort((a, b) => b.created_at - a.created_at);
(event: NDKEvent) => { },
if (event.pubkey === db.account.pubkey) return null; getNextPageParam: (lastPage) => {
return <NotifyNote key={event.id} event={event} />; const lastEvent = lastPage.at(-1);
}, if (!lastEvent) return;
[activities] return lastEvent.created_at - 1;
},
enabled: false,
});
const allEvents = useMemo(
() => (data ? data.pages.flatMap((page) => page) : []),
[data]
); );
useEffect(() => { const renderEvent = useCallback((event: NDKEvent) => {
async function getActivities() { if (event.pubkey === db.account.pubkey) return null;
const events = await getAllActivities(48); return <NotifyNote key={event.id} event={event} />;
setActivities(events);
}
getActivities();
}, []); }, []);
useEffect(() => {
if (status === 'success' && db.account) {
const filter = {
kinds: [NDKKind.Text, NDKKind.Repost, NDKKind.Reaction, NDKKind.Zap],
'#p': [db.account.pubkey],
since: Math.floor(Date.now() / 1000),
};
sub(
filter,
async (event) => {
queryClient.setQueryData(['notification'], (old: NDKEvent[]) => [
event,
...old,
]);
const user = ndk.getUser({ hexpubkey: event.pubkey });
await user.fetchProfile();
switch (event.kind) {
case NDKKind.Text:
return await sendNativeNotification(
`${
user.profile.displayName || user.profile.name
} has replied to your note`
);
case NDKKind.EncryptedDirectMessage: {
if (location.pathname !== '/chats') {
return await sendNativeNotification(
`${
user.profile.displayName || user.profile.name
} has send you a encrypted message`
);
} else {
break;
}
}
case NDKKind.Repost:
return await sendNativeNotification(
`${
user.profile.displayName || user.profile.name
} has reposted to your note`
);
case NDKKind.Reaction:
return await sendNativeNotification(
`${user.profile.displayName || user.profile.name} has reacted ${
event.content
} to your note`
);
case NDKKind.Zap:
return await sendNativeNotification(
`${user.profile.displayName || user.profile.name} has zapped to your note`
);
default:
break;
}
},
false,
'notification'
);
}
}, [status]);
return ( return (
<WidgetWrapper> <WidgetWrapper>
<TitleBar id={params.id} title={params.title} /> <TitleBar id="9998" title="Notification" />
<div className="flex-1"> <VList className="flex-1">
{!activities ? ( {status === 'pending' ? (
<div className="flex h-full w-full items-center justify-center"> <div className="px-3 py-1.5">
<div className="flex flex-col items-center gap-1.5"> <div className="rounded-xl bg-neutral-100 px-3 py-3 dark:bg-neutral-900">
<LoaderIcon className="h-5 w-5 animate-spin text-neutral-900 dark:text-neutral-100" /> <NoteSkeleton />
<p className="text-sm font-medium text-neutral-600 dark:text-neutral-400">
Loading...
</p>
</div> </div>
</div> </div>
) : activities.length < 1 ? ( ) : allEvents.length < 1 ? (
<div className="flex h-full w-full flex-col items-center justify-center"> <div className="flex h-full w-full flex-col items-center justify-center">
<p className="mb-1 text-4xl">🎉</p> <p className="mb-1 text-4xl">🎉</p>
<p className="text-center font-medium text-neutral-600 dark:text-neutral-400"> <p className="text-center font-medium text-neutral-600 dark:text-neutral-400">
@ -61,12 +147,28 @@ export function LocalNotificationWidget({ params }: { params: Widget }) {
</p> </p>
</div> </div>
) : ( ) : (
<VList className="h-full" style={{ contentVisibility: 'auto' }}> allEvents.map((event) => renderEvent(event))
{activities.map((event) => renderEvent(event))}
<div className="h-14" />
</VList>
)} )}
</div> <div className="flex h-16 items-center justify-center px-3 pb-3">
{hasNextPage ? (
<button
type="button"
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetchingNextPage}
className="inline-flex h-10 w-max items-center justify-center gap-2 rounded-full bg-blue-500 px-6 font-medium text-white hover:bg-blue-600 focus:outline-none"
>
{isFetchingNextPage ? (
<LoaderIcon className="h-4 w-4 animate-spin" />
) : (
<>
<ArrowRightCircleIcon className="h-5 w-5" />
Load more
</>
)}
</button>
) : null}
</div>
</VList>
</WidgetWrapper> </WidgetWrapper>
); );
} }

View File

@ -1,70 +0,0 @@
import { useNavigate } from 'react-router-dom';
import { ArrowRightIcon } from '@shared/icons';
import { TitleBar } from '@shared/titleBar';
import { WidgetWrapper } from '@shared/widgets';
import { useResources } from '@stores/resources';
import { Widget } from '@utils/types';
export function LearnNostrWidget({ params }: { params: Widget }) {
const navigate = useNavigate();
const openResource = useResources((state) => state.openResource);
const resources = useResources((state) => state.resources);
const seens = useResources((state) => state.seens);
const open = (naddr: string) => {
// add resource to seen list
openResource(naddr);
// redirect
navigate(`/notes/article/${naddr}`);
};
return (
<WidgetWrapper>
<TitleBar id={params.id} title="The Joy of Nostr" />
<div className="h-full overflow-y-auto px-3 pb-20 scrollbar-none">
{resources.map((resource, index) => (
<div key={index} className="mb-6">
<h3 className="mb-2 text-sm font-medium text-neutral-500 dark:text-neutral-400">
{resource.title}
</h3>
<div className="flex flex-col gap-2">
{resource.data.length ? (
resource.data.map((item, index) => (
<button
key={index}
type="button"
onClick={() => open(item.id)}
className="flex items-center justify-between rounded-xl bg-neutral-100 px-4 py-3 hover:bg-neutral-200 dark:bg-neutral-900 dark:hover:bg-neutral-800"
>
<div className="flex flex-col items-start">
<h5 className="font-semibold text-neutral-900 dark:text-neutral-100">
{item.title}
</h5>
{seens.has(item.id) ? (
<p className="text-sm text-green-500">Readed</p>
) : (
<p className="text-sm text-neutral-500 dark:text-neutral-400">
Unread
</p>
)}
</div>
<ArrowRightIcon className="h-5 w-5 text-neutral-100 dark:text-neutral-900" />
</button>
))
) : (
<div className="flex h-14 items-center justify-center rounded-xl bg-neutral-100 px-3 py-3 dark:bg-neutral-900">
<p className="text-sm font-medium text-neutral-900 dark:text-neutral-100">
More resources are coming, stay tuned.
</p>
</div>
)}
</div>
</div>
))}
</div>
</WidgetWrapper>
);
}

View File

@ -5,17 +5,15 @@ import { useStorage } from '@libs/storage/provider';
import { ArrowRightCircleIcon, CheckCircleIcon } from '@shared/icons'; import { ArrowRightCircleIcon, CheckCircleIcon } from '@shared/icons';
import { User } from '@shared/user'; import { User } from '@shared/user';
import { WidgetKinds, useWidgets } from '@stores/widgets'; import { WidgetKinds } from '@stores/constants';
import { useWidget } from '@utils/hooks/useWidget';
import { Widget } from '@utils/types'; import { Widget } from '@utils/types';
export function XfeedsWidget({ params }: { params: Widget }) { export function XfeedsWidget({ params }: { params: Widget }) {
const { db } = useStorage(); const { db } = useStorage();
const { addWidget, removeWidget } = useWidget();
const [setWidget, removeWidget] = useWidgets((state) => [
state.setWidget,
state.removeWidget,
]);
const [title, setTitle] = useState<string>(''); const [title, setTitle] = useState<string>('');
const [groups, setGroups] = useState<Array<string>>([]); const [groups, setGroups] = useState<Array<string>>([]);
@ -28,17 +26,17 @@ export function XfeedsWidget({ params }: { params: Widget }) {
}; };
const cancel = () => { const cancel = () => {
removeWidget(db, params.id); removeWidget.mutate(params.id);
}; };
const submit = async () => { const submit = async () => {
setWidget(db, { addWidget.mutate({
kind: WidgetKinds.local.feeds, kind: WidgetKinds.local.feeds,
title: title || 'Group', title: title || 'Group',
content: JSON.stringify(groups), content: JSON.stringify(groups),
}); });
// remove temp widget // remove temp widget
removeWidget(db, params.id); removeWidget.mutate(params.id);
}; };
return ( return (

View File

@ -1,11 +1,10 @@
import { Resolver, useForm } from 'react-hook-form'; import { Resolver, useForm } from 'react-hook-form';
import { useStorage } from '@libs/storage/provider';
import { ArrowRightCircleIcon } from '@shared/icons'; import { ArrowRightCircleIcon } from '@shared/icons';
import { WidgetKinds, useWidgets } from '@stores/widgets'; import { WidgetKinds } from '@stores/constants';
import { useWidget } from '@utils/hooks/useWidget';
import { Widget } from '@utils/types'; import { Widget } from '@utils/types';
type FormValues = { type FormValues = {
@ -27,12 +26,7 @@ const resolver: Resolver<FormValues> = async (values) => {
}; };
export function XhashtagWidget({ params }: { params: Widget }) { export function XhashtagWidget({ params }: { params: Widget }) {
const [setWidget, removeWidget] = useWidgets((state) => [ const { addWidget, removeWidget } = useWidget();
state.setWidget,
state.removeWidget,
]);
const { db } = useStorage();
const { const {
register, register,
setError, setError,
@ -41,18 +35,18 @@ export function XhashtagWidget({ params }: { params: Widget }) {
} = useForm<FormValues>({ resolver }); } = useForm<FormValues>({ resolver });
const cancel = () => { const cancel = () => {
removeWidget(db, params.id); removeWidget.mutate(params.id);
}; };
const onSubmit = async (data: FormValues) => { const onSubmit = async (data: FormValues) => {
try { try {
setWidget(db, { addWidget.mutate({
kind: WidgetKinds.global.hashtag, kind: WidgetKinds.global.hashtag,
title: data.hashtag, title: data.hashtag,
content: data.hashtag.replace('#', ''), content: data.hashtag.replace('#', ''),
}); });
// remove temp widget // remove temp widget
removeWidget(db, params.id); removeWidget.mutate(params.id);
} catch (e) { } catch (e) {
setError('hashtag', { setError('hashtag', {
type: 'custom', type: 'custom',

View File

@ -1,32 +0,0 @@
import { NDKEvent } from '@nostr-dev-kit/ndk';
import { create } from 'zustand';
interface ActivitiesState {
activities: Array<NDKEvent>;
newMessages: number;
setActivities: (events: NDKEvent[]) => void;
addActivity: (event: NDKEvent) => void;
addNewMessage: () => void;
clearNewMessage: () => void;
}
export const useActivities = create<ActivitiesState>((set) => ({
activities: null,
newMessages: 0,
setActivities: (events: NDKEvent[]) => {
set(() => ({
activities: events,
}));
},
addActivity: (event: NDKEvent) => {
set((state) => ({
activities: state.activities ? [event, ...state.activities] : [event],
}));
},
addNewMessage: () => {
set((state) => ({ newMessages: state.newMessages + 1 }));
},
clearNewMessage: () => {
set(() => ({ newMessages: 0 }));
},
}));

View File

@ -1,3 +1,5 @@
import { WidgetGroup } from '@utils/types';
export const FULL_RELAYS = [ export const FULL_RELAYS = [
'wss://relay.damus.io', 'wss://relay.damus.io',
'wss://relay.primal.net', 'wss://relay.primal.net',
@ -5,3 +7,104 @@ export const FULL_RELAYS = [
'wss://relay.nostr.band/all', 'wss://relay.nostr.band/all',
'wss://nostr.mutinywallet.com', 'wss://nostr.mutinywallet.com',
]; ];
export const FETCH_LIMIT = 50;
export const WidgetKinds = {
local: {
network: 100,
feeds: 101,
files: 102,
articles: 103,
user: 104,
thread: 105,
follows: 106,
notification: 107,
},
global: {
feeds: 1000,
files: 1001,
articles: 1002,
hashtag: 1003,
},
nostrBand: {
trendingAccounts: 1,
trendingNotes: 2,
},
other: {
learnNostr: 90000,
},
tmp: {
list: 10000,
xfeed: 10001,
xhashtag: 10002,
},
};
export const DefaultWidgets: Array<WidgetGroup> = [
{
title: 'Circles / Follows',
data: [
{
kind: WidgetKinds.tmp.xfeed,
title: 'Group feeds',
description: 'All posts from specific people you want to keep up with',
},
{
kind: WidgetKinds.local.files,
title: 'Files',
description: 'All files shared by people in your circle',
},
{
kind: WidgetKinds.local.articles,
title: 'Articles',
description: 'All articles shared by people in your circle',
},
],
},
{
title: 'Global',
data: [
{
kind: WidgetKinds.tmp.xhashtag,
title: 'Hashtag',
description: 'All posts have a specific hashtag',
},
{
kind: WidgetKinds.global.files,
title: 'Files',
description: 'All files shared by people in your current relay set',
},
{
kind: WidgetKinds.global.articles,
title: 'Articles',
description: 'All articles shared by people in your current relay set',
},
],
},
{
title: 'nostr.band',
data: [
{
kind: WidgetKinds.nostrBand.trendingAccounts,
title: 'Accounts',
description: 'Trending accounts from the last 24 hours',
},
{
kind: WidgetKinds.nostrBand.trendingNotes,
title: 'Notes',
description: 'Trending notes from the last 24 hours',
},
],
},
{
title: 'Other',
data: [
{
kind: WidgetKinds.local.notification,
title: 'Notification',
description: 'Everything happens around you',
},
],
},
];

View File

@ -1,183 +0,0 @@
import { create } from 'zustand';
import { createJSONStorage, persist } from 'zustand/middleware';
import { LumeStorage } from '@libs/storage/instance';
import { Widget, WidgetGroup } from '@utils/types';
interface WidgetState {
widgets: null | Array<Widget>;
isFetched: boolean;
fetchWidgets: (db: LumeStorage) => void;
setWidget: (db: LumeStorage, { kind, title, content }: Widget) => void;
removeWidget: (db: LumeStorage, id: string) => void;
reorderWidget: (id: string, position: number) => void;
setIsFetched: () => void;
}
export const WidgetKinds = {
local: {
network: 100,
feeds: 101,
files: 102,
articles: 103,
user: 104,
thread: 105,
follows: 106,
notification: 107,
},
global: {
feeds: 1000,
files: 1001,
articles: 1002,
hashtag: 1003,
},
nostrBand: {
trendingAccounts: 1,
trendingNotes: 2,
},
other: {
learnNostr: 90000,
},
tmp: {
list: 10000,
xfeed: 10001,
xhashtag: 10002,
},
};
export const DefaultWidgets: Array<WidgetGroup> = [
{
title: 'Circles / Follows',
data: [
{
kind: WidgetKinds.tmp.xfeed,
title: 'Group feeds',
description: 'All posts from specific people you want to keep up with',
},
{
kind: WidgetKinds.local.files,
title: 'Files',
description: 'All files shared by people in your circle',
},
{
kind: WidgetKinds.local.articles,
title: 'Articles',
description: 'All articles shared by people in your circle',
},
{
kind: WidgetKinds.local.follows,
title: 'Follows',
description: 'All posts from people you are following',
},
],
},
{
title: 'Global',
data: [
{
kind: WidgetKinds.tmp.xhashtag,
title: 'Hashtag',
description: 'All posts have a specific hashtag',
},
{
kind: WidgetKinds.global.files,
title: 'Files',
description: 'All files shared by people in your current relay set',
},
{
kind: WidgetKinds.global.articles,
title: 'Articles',
description: 'All articles shared by people in your current relay set',
},
],
},
{
title: 'nostr.band',
data: [
{
kind: WidgetKinds.nostrBand.trendingAccounts,
title: 'Accounts',
description: 'Trending accounts from the last 24 hours',
},
{
kind: WidgetKinds.nostrBand.trendingNotes,
title: 'Notes',
description: 'Trending notes from the last 24 hours',
},
],
},
{
title: 'Other',
data: [
{
kind: WidgetKinds.local.notification,
title: 'Notification',
description: 'Everything happens around you',
},
{
kind: WidgetKinds.other.learnNostr,
title: 'Learn Nostr',
description: 'All things you need to know about Nostr',
},
],
},
];
export const useWidgets = create<WidgetState>()(
persist(
(set) => ({
widgets: null,
isFetched: false,
fetchWidgets: async (db: LumeStorage) => {
const dbWidgets = await db.getWidgets();
/*
dbWidgets.unshift({
id: '9998',
title: 'Notification',
content: '',
kind: WidgetKinds.local.notification,
});
*/
dbWidgets.unshift({
id: '9999',
title: '',
content: '',
kind: WidgetKinds.local.network,
});
set({ widgets: dbWidgets });
},
setWidget: async (db: LumeStorage, { kind, title, content }: Widget) => {
const widget: Widget = await db.createWidget(kind, title, content);
set((state) => ({ widgets: [...state.widgets, widget] }));
},
removeWidget: async (db: LumeStorage, id: string) => {
await db.removeWidget(id);
set((state) => ({ widgets: state.widgets.filter((widget) => widget.id !== id) }));
},
reorderWidget: (id: string, position: number) => {
set((state) => {
const widgets = [...state.widgets];
const widget = widgets.find((widget) => widget.id === id);
if (!widget) return { widgets };
const idx = widgets.indexOf(widget);
widgets.splice(idx, 1);
widgets.splice(position, 0, widget);
return { widgets };
});
},
setIsFetched: () => {
set({ isFetched: true });
},
}),
{
name: 'widgets',
storage: createJSONStorage(() => sessionStorage),
}
)
);

View File

@ -29,11 +29,12 @@ export function useNostr() {
const sub = async ( const sub = async (
filter: NDKFilter, filter: NDKFilter,
callback: (event: NDKEvent) => void, callback: (event: NDKEvent) => void,
groupable?: boolean groupable?: boolean,
subKey?: string
) => { ) => {
if (!ndk) throw new Error('NDK instance not found'); if (!ndk) throw new Error('NDK instance not found');
const key = JSON.stringify(filter); const key = subKey ?? JSON.stringify(filter);
if (!subManager.get(key)) { if (!subManager.get(key)) {
const subEvent = ndk.subscribe(filter, { const subEvent = ndk.subscribe(filter, {
closeOnEose: false, closeOnEose: false,

View File

@ -0,0 +1,30 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useStorage } from '@libs/storage/provider';
import { Widget } from '@utils/types';
export function useWidget() {
const { db } = useStorage();
const queryClient = useQueryClient();
const addWidget = useMutation({
mutationFn: async (widget: Widget) => {
return await db.createWidget(widget.kind, widget.title, widget.content);
},
onSuccess: (data) => {
queryClient.setQueryData(['widgets'], (old: Widget[]) => [...old, data]);
},
});
const removeWidget = useMutation({
mutationFn: async (id: string) => {
return await db.removeWidget(id);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['widgets'] });
},
});
return { addWidget, removeWidget };
}