Merge pull request #102 from luminous-devs/feat/v2.0.1

v2.0.1
This commit is contained in:
Ren Amamiya 2023-11-01 15:38:39 +07:00 committed by GitHub
commit dd21633624
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
98 changed files with 3235 additions and 3939 deletions

View File

@ -2,7 +2,7 @@
"name": "lume",
"description": "the communication app",
"private": true,
"version": "2.0.0",
"version": "2.0.1",
"scripts": {
"dev": "vite",
"build": "vite build",
@ -32,22 +32,22 @@
"@radix-ui/react-popover": "^1.0.7",
"@radix-ui/react-toolbar": "^1.0.4",
"@radix-ui/react-tooltip": "^1.0.7",
"@tanstack/react-query": "4.36.1",
"@tauri-apps/api": "2.0.0-alpha.8",
"@tauri-apps/cli": "2.0.0-alpha.15",
"@tauri-apps/plugin-app": "2.0.0-alpha.1",
"@tauri-apps/plugin-clipboard-manager": "2.0.0-alpha.1",
"@tauri-apps/plugin-dialog": "2.0.0-alpha.1",
"@tauri-apps/plugin-fs": "2.0.0-alpha.1",
"@tauri-apps/plugin-http": "2.0.0-alpha.1",
"@tauri-apps/plugin-notification": "2.0.0-alpha.1",
"@tauri-apps/plugin-os": "2.0.0-alpha.2",
"@tauri-apps/plugin-process": "2.0.0-alpha.1",
"@tauri-apps/plugin-shell": "2.0.0-alpha.1",
"@tauri-apps/plugin-sql": "2.0.0-alpha.1",
"@tauri-apps/plugin-updater": "2.0.0-alpha.1",
"@tauri-apps/plugin-upload": "2.0.0-alpha.1",
"@tauri-apps/plugin-window": "2.0.0-alpha.1",
"@tanstack/query-sync-storage-persister": "^5.4.3",
"@tanstack/react-query": "^5.0.5",
"@tanstack/react-query-persist-client": "^5.4.3",
"@tauri-apps/api": "^2.0.0-alpha.9",
"@tauri-apps/cli": "^2.0.0-alpha.16",
"@tauri-apps/plugin-clipboard-manager": "^2.0.0-alpha.2",
"@tauri-apps/plugin-dialog": "^2.0.0-alpha.2",
"@tauri-apps/plugin-fs": "^2.0.0-alpha.2",
"@tauri-apps/plugin-http": "^2.0.0-alpha.2",
"@tauri-apps/plugin-notification": "^2.0.0-alpha.2",
"@tauri-apps/plugin-os": "^2.0.0-alpha.3",
"@tauri-apps/plugin-process": "^2.0.0-alpha.2",
"@tauri-apps/plugin-shell": "^2.0.0-alpha.2",
"@tauri-apps/plugin-sql": "^2.0.0-alpha.2",
"@tauri-apps/plugin-updater": "^2.0.0-alpha.2",
"@tauri-apps/plugin-upload": "^2.0.0-alpha.2",
"@tiptap/extension-character-count": "^2.1.12",
"@tiptap/extension-document": "^2.1.12",
"@tiptap/extension-image": "^2.1.12",
@ -60,12 +60,14 @@
"@tiptap/starter-kit": "^2.1.12",
"@tiptap/suggestion": "^2.1.12",
"dayjs": "^1.11.10",
"destr": "^2.0.1",
"destr": "^2.0.2",
"framer-motion": "^10.16.4",
"html-to-text": "^9.0.5",
"immer": "^10.0.3",
"light-bolt11-decoder": "^3.0.0",
"lru-cache": "^10.0.1",
"media-chrome": "^1.4.4",
"markdown-to-jsx": "^7.3.2",
"media-chrome": "^1.4.5",
"million": "^2.6.4",
"minidenticons": "^4.2.0",
"nostr-fetch": "^0.13.0",
@ -77,48 +79,45 @@
"react-dom": "^18.2.0",
"react-hook-form": "^7.47.0",
"react-hotkeys-hook": "^4.4.1",
"react-markdown": "^8.0.7",
"react-router-dom": "^6.17.0",
"react-string-replace": "^1.1.1",
"reactflow": "^11.9.4",
"remark-gfm": "^3.0.1",
"sonner": "^1.0.3",
"tailwind-scrollbar": "^3.0.5",
"tauri-controls": "^0.2.0",
"tippy.js": "^6.3.7",
"tiptap-markdown": "^0.8.2",
"virtua": "^0.15.0",
"zustand": "^4.4.3"
"virtua": "^0.15.6",
"zustand": "^4.4.4"
},
"devDependencies": {
"@tailwindcss/typography": "^0.5.10",
"@trivago/prettier-plugin-sort-imports": "^4.2.0",
"@trivago/prettier-plugin-sort-imports": "^4.2.1",
"@types/html-to-text": "^9.0.3",
"@types/node": "^20.8.7",
"@types/react": "^18.2.29",
"@types/node": "^20.8.9",
"@types/react": "^18.2.33",
"@types/react-dom": "^18.2.14",
"@types/youtube-player": "^5.5.9",
"@typescript-eslint/eslint-plugin": "^6.8.0",
"@typescript-eslint/parser": "^6.8.0",
"@typescript-eslint/eslint-plugin": "^6.9.0",
"@typescript-eslint/parser": "^6.9.0",
"@vitejs/plugin-react-swc": "^3.4.0",
"autoprefixer": "^10.4.16",
"clsx": "^2.0.0",
"cross-env": "^7.0.3",
"csstype": "^3.1.2",
"encoding": "^0.1.13",
"eslint": "^8.51.0",
"eslint": "^8.52.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-jsx-a11y": "^6.7.1",
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-simple-import-sort": "^10.0.0",
"husky": "^8.0.3",
"lint-staged": "^14.0.1",
"lint-staged": "^15.0.2",
"postcss": "^8.4.31",
"prettier": "^3.0.3",
"prettier-plugin-tailwindcss": "^0.5.6",
"prop-types": "^15.8.1",
"tailwind-merge": "^1.14.0",
"tailwindcss": "^3.3.3",
"tailwindcss": "^3.3.5",
"typescript": "^5.2.2",
"vite": "^4.5.0",
"vite-tsconfig-paths": "^4.2.1"

File diff suppressed because it is too large Load Diff

473
src-tauri/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
[package]
name = "lume"
version = "2.0.0"
version = "2.0.1"
description = "the communication app"
authors = ["Ren Amamiya"]
license = "GPL-3.0"
@ -18,7 +18,6 @@ tauri = { version = "2.0.0-alpha", features = [
"macos-private-api",
"native-tls-vendored",
] }
tauri-plugin-app = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
tauri-plugin-cli = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
tauri-plugin-clipboard-manager = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
tauri-plugin-dialog = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
@ -29,7 +28,6 @@ tauri-plugin-os = { git = "https://github.com/tauri-apps/plugins-workspace", bra
tauri-plugin-process = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
tauri-plugin-shell = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
tauri-plugin-updater = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
tauri-plugin-window = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
tauri-plugin-single-instance = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
tauri-plugin-autostart = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
tauri-plugin-store = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }

View File

@ -0,0 +1,27 @@
-- Add migration script here
CREATE TABLE
ndk_users (
pubkey TEXT NOT NULL PRIMARY KEY,
profile TEXT,
createdAt NUMBER
);
CREATE TABLE
ndk_events (
id TEXT NOT NULL PRIMARY KEY,
pubkey TEXT,
content TEXT,
kind NUMBER,
createdAt NUMBER,
relay TEXT,
event TEXT
);
CREATE TABLE
ndk_eventtags (
id TEXT NOT NULL PRIMARY KEY,
eventId TEXT,
tag TEXT,
value TEXT,
tagValue TEXT
);

View File

@ -114,7 +114,6 @@ fn main() {
.plugin(tauri_plugin_updater::Builder::new().build())?;
Ok(())
})
.plugin(tauri_plugin_app::init())
.plugin(tauri_plugin_clipboard_manager::init())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_fs::init())
@ -125,17 +124,24 @@ fn main() {
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_upload::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.plugin(tauri_plugin_window::init())
.plugin(
tauri_plugin_sql::Builder::default()
.add_migrations(
"sqlite:lume_v2.db",
vec![Migration {
version: 20230418013219,
description: "initial data",
sql: include_str!("../migrations/20230418013219_initial_data.sql"),
kind: MigrationKind::Up,
}],
vec![
Migration {
version: 20230418013219,
description: "initial data",
sql: include_str!("../migrations/20230418013219_initial_data.sql"),
kind: MigrationKind::Up,
},
Migration {
version: 20231028083224,
description: "add ndk cache table",
sql: include_str!("../migrations/20231028083224_add_ndk_cache_table.sql"),
kind: MigrationKind::Up,
},
],
)
.build(),
)

View File

@ -9,7 +9,7 @@
},
"package": {
"productName": "Lume",
"version": "2.0.0"
"version": "2.0.1"
},
"plugins": {
"fs": {

View File

@ -9,9 +9,9 @@ import { User } from '@shared/user';
export function FollowList() {
const { db } = useStorage();
const { ndk } = useNDK();
const { status, data } = useQuery(
['follows'],
async () => {
const { status, data } = useQuery({
queryKey: ['follows'],
queryFn: async () => {
const user = ndk.getUser({ hexpubkey: db.account.pubkey });
const follows = await user.follows();
const followsAsArr = [];
@ -29,16 +29,14 @@ export function FollowList() {
return followsAsArr;
},
{
refetchOnWindowFocus: false,
}
);
refetchOnWindowFocus: false,
});
return (
<div className="relative rounded-xl bg-neutral-100 p-3 text-neutral-800 dark:bg-neutral-900 dark:text-neutral-200">
<h5 className="font-semibold">Your follows</h5>
<div className="mt-2 flex w-full items-center justify-center">
{status === 'loading' ? (
{status === 'pending' ? (
<LoaderIcon className="h-4 w-4 animate-spin text-neutral-900 dark:text-neutral-100" />
) : (
<div className="isolate flex -space-x-2">

View File

@ -17,12 +17,15 @@ import { arrayToNIP02 } from '@utils/transform';
export function OnboardEnrichScreen() {
const { ndk } = useNDK();
const { db } = useStorage();
const { status, data } = useQuery(['trending-profiles-widget'], async () => {
const res = await fetch('https://api.nostr.band/v0/trending/profiles');
if (!res.ok) {
throw new Error('Error');
}
return res.json();
const { status, data } = useQuery({
queryKey: ['trending-profiles-widget'],
queryFn: async () => {
const res = await fetch('https://api.nostr.band/v0/trending/profiles');
if (!res.ok) {
throw new Error('Error');
}
return res.json();
},
});
const [loading, setLoading] = useState(false);
@ -90,7 +93,7 @@ export function OnboardEnrichScreen() {
</h1>
</div>
<div className="flex w-full flex-nowrap items-center gap-4 overflow-x-auto px-4 scrollbar-none">
{status === 'loading' ? (
{status === 'pending' ? (
<div className="flex h-full w-full items-center justify-center">
<LoaderIcon className="h-4 w-4 animate-spin text-neutral-900 dark:text-neutral-100" />
</div>

View File

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

View File

@ -24,15 +24,13 @@ export function OnboardRelaysScreen() {
const { db } = useStorage();
const { ndk } = useNDK();
const { getAllRelaysByUsers } = useNostr();
const { status, data } = useQuery(
['relays'],
async () => {
const { status, data } = useQuery({
queryKey: ['relays'],
queryFn: async () => {
return await getAllRelaysByUsers();
},
{
refetchOnWindowFocus: false,
}
);
refetchOnWindowFocus: false,
});
const toggleRelay = (relay: string) => {
if (relays.has(relay)) {
@ -89,7 +87,7 @@ export function OnboardRelaysScreen() {
</h1>
<div className="flex flex-col gap-4">
<div className="flex h-[420px] w-full flex-col overflow-y-auto rounded-xl bg-neutral-100 dark:bg-neutral-900">
{status === 'loading' ? (
{status === 'pending' ? (
<div className="flex h-full w-full items-center justify-center">
<LoaderIcon className="h-4 w-4 animate-spin text-neutral-900 dark:text-neutral-100" />
</div>

View File

@ -22,8 +22,12 @@ export function ChatScreen() {
const { ndk } = useNDK();
const { pubkey } = useParams();
const { fetchNIP04Messages } = useNostr();
const { status, data } = useQuery(['nip04-dm', pubkey], async () => {
return await fetchNIP04Messages(pubkey);
const { status, data } = useQuery({
queryKey: ['nip04-dm', pubkey],
queryFn: async () => {
return await fetchNIP04Messages(pubkey);
},
refetchOnWindowFocus: false,
});
const renderItem = useCallback(
@ -69,7 +73,7 @@ export function ChatScreen() {
<User pubkey={pubkey} variant="simple" />
</div>
<div className="h-full w-full flex-1 px-3 py-3">
{status === 'loading' ? (
{status === 'pending' ? (
<div className="flex h-full w-full items-center justify-center">
<div className="flex flex-col items-center gap-1.5">
<LoaderIcon className="h-5 w-5 animate-spin text-neutral-900 dark:text-neutral-100" />

View File

@ -19,7 +19,7 @@ export const ChatListItem = memo(function ChatListItem({ event }: { event: NDKEv
const svgURI =
'data:image/svg+xml;utf8,' + encodeURIComponent(minidenticon(event.pubkey, 90, 50));
if (status === 'loading') {
if (status === 'pending') {
return (
<div className="flex items-center gap-2.5 rounded-md px-3">
<div className="h-10 w-10 shrink-0 animate-pulse rounded-lg bg-neutral-400 dark:bg-neutral-600" />

View File

@ -15,11 +15,13 @@ export function MediaUploader({
const uploadMedia = async () => {
setLoading(true);
const image = await upload(null);
if (image.url) {
setState((prev: string) => `${prev}\n${image.url}`);
const image = await upload(['mp4', 'mp3', 'webm', 'mkv', 'avi', 'mov']);
if (image) {
setState((prev: string) => `${prev}\n${image}`);
setLoading(false);
}
setLoading(false);
};
return (

View File

@ -11,18 +11,16 @@ import { useNostr } from '@utils/hooks/useNostr';
export function ChatsScreen() {
const { getAllNIP04Chats } = useNostr();
const { status, data } = useQuery(
['nip04-chats'],
async () => {
const { status, data } = useQuery({
queryKey: ['nip04-chats'],
queryFn: async () => {
return await getAllNIP04Chats();
},
{
refetchOnWindowFocus: false,
refetchOnMount: false,
refetchOnReconnect: false,
staleTime: Infinity,
}
);
refetchOnWindowFocus: false,
refetchOnMount: false,
refetchOnReconnect: false,
staleTime: Infinity,
});
const renderItem = useCallback(
(event: NDKEvent) => {
@ -43,7 +41,7 @@ export function ChatsScreen() {
</h3>
</div>
<div className="flex h-full flex-col gap-1">
{status === 'loading' ? (
{status === 'pending' ? (
<div className="flex h-full w-full items-center justify-center pb-16">
<div className="inline-flex flex-col items-center justify-center gap-2">
<LoaderIcon className="h-5 w-5 animate-spin text-neutral-900 dark:text-neutral-100" />

View File

@ -8,7 +8,6 @@ interface RouteError {
interface DebugInfo {
os: null | string;
version: null | string;
appDir: null | string;
}
@ -18,24 +17,20 @@ export function ErrorScreen() {
const [debugInfo, setDebugInfo] = useState<DebugInfo>({
os: null,
version: null,
appDir: null,
});
useEffect(() => {
async function getInformation() {
const { platform, version } = await import('@tauri-apps/plugin-os');
const { getVersion } = await import('@tauri-apps/plugin-app');
const { appConfigDir } = await import('@tauri-apps/api/path');
const platformName = await platform();
const osVersion = await version();
const appVersion = await getVersion();
const appDir = await appConfigDir();
setDebugInfo({
os: platformName + ' ' + osVersion,
version: appVersion,
appDir: appDir,
});
}
@ -59,9 +54,6 @@ export function ErrorScreen() {
<p className="font-medium text-neutral-600 dark:text-neutral-400">
Current location: {location.pathname}
</p>
<p className="font-medium text-neutral-600 dark:text-neutral-400">
App version: {debugInfo.version}
</p>
<p className="font-medium text-neutral-600 dark:text-neutral-400">
Platform: {debugInfo.os}
</p>

View File

@ -5,7 +5,7 @@ import { useProfile } from '@utils/hooks/useProfile';
export const GroupTitle = memo(function GroupTitle({ pubkey }: { pubkey: string }) {
const { status, user } = useProfile(pubkey);
if (status === 'loading') {
if (status === 'pending') {
return <div className="h-3 w-24 animate-pulse rounded bg-white/10" />;
}

View File

@ -16,8 +16,12 @@ import { useNostr } from '@utils/hooks/useNostr';
export function UserLatestPosts({ pubkey }: { pubkey: string }) {
const { getEventsByPubkey } = useNostr();
const { status, data } = useQuery(['user-posts', pubkey], async () => {
return await getEventsByPubkey(pubkey);
const { status, data } = useQuery({
queryKey: ['user-posts', pubkey],
queryFn: async () => {
return await getEventsByPubkey(pubkey);
},
refetchOnWindowFocus: false,
});
const renderItem = useCallback(
@ -60,7 +64,7 @@ export function UserLatestPosts({ pubkey }: { pubkey: string }) {
Latest post
</h3>
<div>
{status === 'loading' ? (
{status === 'pending' ? (
<div className="px-3">
<div className="inline-flex h-16 w-full items-center justify-center gap-1.5 rounded-lg bg-neutral-300 text-sm font-medium dark:bg-neutral-700">
<LoaderIcon className="h-4 w-4 animate-spin" />

View File

@ -84,7 +84,7 @@ export const UserWithDrawer = memo(function UserWithDrawer({
<Dialog.Portal>
<Dialog.Content className="fixed right-0 top-0 z-50 flex h-full w-[400px] animate-slideRightAndFade items-center justify-center px-4 pb-4 pt-16 transition-all">
<div className="h-full w-full overflow-y-auto rounded-lg border border-neutral-300 bg-neutral-200 py-3 dark:border-neutral-700 dark:bg-neutral-800">
{status === 'loading' ? (
{status === 'pending' ? (
<div>
<p>Loading...</p>
</div>

View File

@ -1,11 +1,13 @@
import { message, open } from '@tauri-apps/plugin-dialog';
import { readBinaryFile } from '@tauri-apps/plugin-fs';
import { message } from '@tauri-apps/plugin-dialog';
import { Editor } from '@tiptap/react';
import { useState } from 'react';
import { MediaIcon } from '@shared/icons';
import { useNostr } from '@utils/hooks/useNostr';
export function MediaUploader({ editor }: { editor: Editor }) {
const { upload } = useNostr();
const [loading, setLoading] = useState(false);
const uploadToNostrBuild = async () => {
@ -13,52 +15,12 @@ export function MediaUploader({ editor }: { editor: Editor }) {
// start loading
setLoading(true);
const selected = await open({
multiple: false,
filters: [
{
name: 'Media',
extensions: [
'png',
'jpeg',
'jpg',
'gif',
'mp4',
'mp3',
'webm',
'mkv',
'avi',
'mov',
],
},
],
});
const image = await upload(['mp4', 'mp3', 'webm', 'mkv', 'avi', 'mov']);
if (!selected) {
setLoading(false);
return;
}
const file = await readBinaryFile(selected.path);
const blob = new Blob([file]);
const data = new FormData();
data.append('fileToUpload', blob);
data.append('submit', 'Upload Image');
const res = await fetch('https://nostr.build/api/v2/upload/files', {
method: 'POST',
body: data,
});
if (res.ok) {
const json = await res.json();
const content = json.data[0];
editor.commands.setImage({ src: content.url });
if (image) {
editor.commands.setImage({ src: image });
editor.commands.createParagraphNear();
// stop loading
setLoading(false);
}
} catch (e) {

View File

@ -6,7 +6,7 @@ import { displayNpub } from '@utils/shortenKey';
export function MentionPopupItem({ pubkey, embed }: { pubkey: string; embed?: string }) {
const { status, user } = useProfile(pubkey, embed);
if (status === 'loading') {
if (status === 'pending') {
return (
<div className="flex items-center gap-2.5 px-2">
<div className="relative h-8 w-8 shrink-0 animate-pulse rounded bg-neutral-400 dark:bg-neutral-600" />

View File

@ -12,11 +12,11 @@ import { User } from '@shared/user';
import { useEvent } from '@utils/hooks/useEvent';
export function ArticleNoteScreen() {
const { id } = useParams();
const navigate = useNavigate();
const replyRef = useRef(null);
const { id } = useParams();
const naddr = id.startsWith('naddr') ? (nip19.decode(id).data as AddressPointer) : null;
const { status, data } = useEvent(id, naddr);
@ -72,7 +72,7 @@ export function ArticleNoteScreen() {
</div>
<div className="relative col-span-6 flex flex-col overflow-y-auto">
<div className="mx-auto w-full max-w-2xl">
{status === 'loading' ? (
{status === 'pending' ? (
<div className="px-3 py-1.5">Loading...</div>
) : (
<div className="flex h-min w-full flex-col px-3">

View File

@ -91,7 +91,7 @@ export function TextNoteScreen() {
</div>
<div className="relative col-span-6 flex flex-col overflow-y-auto">
<div className="mx-auto w-full max-w-2xl">
{status === 'loading' ? (
{status === 'pending' ? (
<div className="px-3 py-1.5">Loading...</div>
) : (
<div className="flex h-min w-full flex-col px-3">

View File

@ -17,9 +17,9 @@ import {
export function RelayEventList({ relayUrl }: { relayUrl: string }) {
const { fetcher } = useNDK();
const { status, data } = useQuery(
['relay-event'],
async () => {
const { status, data } = useQuery({
queryKey: ['relay-event'],
queryFn: async () => {
const url = 'wss://' + relayUrl;
const events = await fetcher.fetchLatestEvents(
[url],
@ -30,8 +30,8 @@ export function RelayEventList({ relayUrl }: { relayUrl: string }) {
);
return events as unknown as NDKEvent[];
},
{ refetchOnWindowFocus: false }
);
refetchOnWindowFocus: false,
});
const renderItem = useCallback(
(event: NDKEvent) => {
@ -70,7 +70,7 @@ export function RelayEventList({ relayUrl }: { relayUrl: string }) {
return (
<div className="h-full">
<div className="mx-auto w-full max-w-[500px]">
{status === 'loading' ? (
{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-white" />
@ -78,7 +78,7 @@ export function RelayEventList({ relayUrl }: { relayUrl: string }) {
</div>
</div>
) : (
<VList className="scrollbar-none h-full">
<VList className="h-full scrollbar-none">
<div className="h-10" />
{data.map((item) => renderItem(item))}
<div className="h-16" />

View File

@ -25,7 +25,10 @@ export function RelayForm() {
const res = await db.createRelay(url);
if (!res) return setError("You're already using this relay");
queryClient.invalidateQueries(['user-relay']);
queryClient.invalidateQueries({
queryKey: ['user-relay'],
});
setError('');
setUrl('');
} else {

View File

@ -17,18 +17,16 @@ export function RelayList() {
const { getAllRelaysByUsers } = useNostr();
const { db } = useStorage();
const { status, data } = useQuery(
['relays'],
async () => {
const { status, data } = useQuery({
queryKey: ['relays'],
queryFn: async () => {
return await getAllRelaysByUsers();
},
{
refetchOnWindowFocus: false,
refetchOnMount: false,
refetchOnReconnect: false,
staleTime: Infinity,
}
);
refetchOnWindowFocus: false,
refetchOnMount: false,
refetchOnReconnect: false,
staleTime: Infinity,
});
const inspectRelay = (relayUrl: string) => {
const url = new URL(relayUrl);
@ -40,12 +38,14 @@ export function RelayList() {
const res = await db.createRelay(url);
if (!res) await message("You're aldready connected to this relay");
queryClient.invalidateQueries(['user-relay']);
queryClient.invalidateQueries({
queryKey: ['user-relay'],
});
};
return (
<div className="col-span-2 border-r border-neutral-100 dark:border-neutral-900">
{status === 'loading' ? (
{status === 'pending' ? (
<div className="flex h-full w-full items-center justify-center pb-10">
<div className="inline-flex flex-col items-center justify-center gap-2">
<LoaderIcon className="h-5 w-5 animate-spin text-neutral-900 dark:text-neutral-100" />

View File

@ -12,22 +12,24 @@ export function UserRelay() {
const { relayUrls } = useNDK();
const { db } = useStorage();
const { status, data } = useQuery(
['user-relay'],
async () => {
const { status, data } = useQuery({
queryKey: ['user-relay'],
queryFn: async () => {
return await db.getExplicitRelayUrls();
},
{ refetchOnWindowFocus: false }
);
refetchOnWindowFocus: false,
});
const removeRelay = async (relayUrl: string) => {
await db.removeRelay(relayUrl);
queryClient.invalidateQueries(['user-relay']);
queryClient.invalidateQueries({
queryKey: ['user-relay'],
});
};
return (
<div className="mt-3 px-3">
{status === 'loading' ? (
{status === 'pending' ? (
<p>Loading...</p>
) : (
<div className="flex flex-col gap-2">

View File

@ -1,17 +1,4 @@
import { getVersion } from '@tauri-apps/plugin-app';
import { useEffect, useState } from 'react';
export function VersionSetting() {
const [version, setVersion] = useState<string>('');
useEffect(() => {
async function checkVersion() {
const appVersion = await getVersion();
setVersion(appVersion);
}
checkVersion();
}, []);
return (
<div className="inline-flex items-center justify-between px-5 py-4">
<div className="flex flex-col gap-1">
@ -21,7 +8,7 @@ export function VersionSetting() {
</span>
</div>
<div className="inline-flex items-center gap-2">
<span className="font-medium text-neutral-300">{version}</span>
<span className="font-medium text-neutral-300">2</span>
</div>
</div>
);

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() {
const { db } = useStorage();
const setWidget = useWidgets((state) => state.setWidget);
const { addWidget } = useWidget();
return (
<div className="flex h-full w-[420px] items-center justify-center border-r border-neutral-100 dark:border-neutral-900">
<div className="relative">
<div className="absolute -top-44 left-1/2 -translate-x-1/2 transform">
<HandArrowDownIcon className="text-neutral-100 dark:text-neutral-900" />
</div>
<WidgetWrapper>
<div className="relative flex h-full w-full flex-col items-center justify-center">
<button
type="button"
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"
>
@ -25,6 +22,6 @@ export function ToggleWidgetList() {
<p className="text-sm font-semibold leading-none">Add widget</p>
</button>
</div>
</div>
</WidgetWrapper>
);
}

View File

@ -1,7 +1,5 @@
import { useCallback } from 'react';
import { useStorage } from '@libs/storage/provider';
import {
ArticleIcon,
BellIcon,
@ -13,21 +11,19 @@ import {
TrendingIcon,
} from '@shared/icons';
import { TitleBar } from '@shared/titleBar';
import { WidgetWrapper } from '@shared/widgets';
import { DefaultWidgets, WidgetKinds, useWidgets } from '@stores/widgets';
import { DefaultWidgets, WidgetKinds } from '@stores/constants';
import { useWidget } from '@utils/hooks/useWidget';
import { Widget, WidgetGroup, WidgetGroupItem } from '@utils/types';
export function WidgetList({ params }: { params: Widget }) {
const { db } = useStorage();
const [setWidget, removeWidget] = useWidgets((state) => [
state.setWidget,
state.removeWidget,
]);
const { addWidget, removeWidget } = useWidget();
const openWidget = (widget: WidgetGroupItem) => {
setWidget(db, { kind: widget.kind, title: widget.title, content: '' });
removeWidget(db, params.id);
const open = (item: WidgetGroupItem) => {
addWidget.mutate({ kind: item.kind, title: item.title, content: '' });
removeWidget.mutate(params.id);
};
const renderIcon = useCallback(
@ -71,54 +67,49 @@ export function WidgetList({ params }: { params: Widget }) {
[DefaultWidgets]
);
const renderItem = useCallback(
(row: WidgetGroup, index: number) => {
return (
<div key={index} className="flex flex-col gap-2">
<h3 className="text-sm font-semibold text-neutral-500 dark:text-neutral-300">
{row.title}
</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">
{row.data.map((item, index) => (
<button
onClick={() => openWidget(item)}
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">
<img
src={item.icon}
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>
const renderItem = useCallback((row: WidgetGroup, index: number) => {
return (
<div key={index} className="flex flex-col gap-2">
<h3 className="text-sm font-semibold">{row.title}</h3>
<div className="flex flex-col divide-y divide-neutral-200 overflow-hidden rounded-xl bg-neutral-100 dark:divide-neutral-800 dark:bg-neutral-900">
{row.data.map((item, index) => (
<button
onClick={() => open(item)}
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-lg">
<img
src={item.icon}
alt={item.title}
className="h-10 w-10 object-cover"
/>
</div>
</button>
))}
</div>
) : (
<div className="inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg 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-600 dark:text-neutral-400">
{item.description}
</p>
</div>
</button>
))}
</div>
);
},
[DefaultWidgets]
);
</div>
);
}, []);
return (
<div className="h-full w-[420px] border-r border-neutral-100 dark:border-neutral-900">
<WidgetWrapper>
<TitleBar id={params.id} title="Add widget" />
<div className="h-full overflow-y-auto pb-20 scrollbar-none">
<div className="flex-1 overflow-y-auto pb-10 scrollbar-none">
<div className="flex flex-col gap-6 px-3">
{DefaultWidgets.map((row: WidgetGroup, index: number) =>
renderItem(row, index)
@ -127,10 +118,10 @@ export function WidgetList({ params }: { params: Widget }) {
<button
type="button"
disabled
className="inline-flex h-14 w-full items-center justify-center gap-2.5 rounded-xl bg-neutral-100 text-sm font-medium text-neutral-900 dark:bg-neutral-900 dark:text-neutral-100"
className="inline-flex h-14 w-full items-center justify-center gap-2.5 rounded-xl bg-neutral-50 text-sm font-medium text-neutral-900 dark:bg-neutral-950 dark:text-neutral-100"
>
Build your own widget{' '}
<div className="-rotate-3 transform-gpu rounded-md border border-neutral-300 bg-neutral-200 px-1.5 py-1 dark:border-neutral-700 dark:bg-neutral-800">
<div className="-rotate-3 transform-gpu rounded-md border border-neutral-200 bg-neutral-100 px-1.5 py-1 dark:border-neutral-800 dark:bg-neutral-900">
<span className="bg-gradient-to-r from-blue-400 via-red-400 to-orange-500 bg-clip-text text-xs text-transparent dark:from-blue-200 dark:via-red-200 dark:to-orange-300">
Coming soon
</span>
@ -139,6 +130,6 @@ export function WidgetList({ params }: { params: Widget }) {
</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 { ToggleWidgetList } from '@app/space/components/toggle';
@ -11,99 +12,134 @@ import {
GlobalArticlesWidget,
GlobalFilesWidget,
GlobalHashtagWidget,
LearnNostrWidget,
LocalArticlesWidget,
LocalFeedsWidget,
LocalFilesWidget,
LocalFollowsWidget,
LocalNetworkWidget,
LocalNotificationWidget,
LocalThreadWidget,
LocalUserWidget,
NewsfeedWidget,
NotificationWidget,
TrendingAccountsWidget,
TrendingNotesWidget,
XfeedsWidget,
XhashtagWidget,
} from '@shared/widgets';
import { WidgetKinds, useWidgets } from '@stores/widgets';
import { WidgetKinds } from '@stores/constants';
import { Widget } from '@utils/types';
export function SpaceScreen() {
const ref = useRef<VListHandle>(null);
const [selectedIndex, setSelectedIndex] = useState(-1);
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) => [
state.widgets,
state.fetchWidgets,
]);
const renderItem = useCallback(
(widget: Widget) => {
if (!widget) return;
switch (widget.kind) {
case WidgetKinds.local.network:
return <LocalNetworkWidget 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;
}
return [...defaultWidgets, ...dbWidgets];
},
[widgets]
);
refetchOnMount: false,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
staleTime: Infinity,
});
useEffect(() => {
fetchWidgets(db);
const renderItem = useCallback((widget: Widget) => {
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 (
<VList
className="h-full w-full flex-nowrap overflow-x-auto !overflow-y-hidden scrollbar-none focus:outline-none"
horizontal
ref={vlistRef}
ref={ref}
initialItemSize={420}
aria-current="step"
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 ? (
<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))
)}
{data.map((widget) => renderItem(widget))}
<ToggleWidgetList />
</VList>
);

View File

@ -210,7 +210,9 @@ export function EditProfileModal() {
if (publishedRelays) {
// invalid cache
queryClient.invalidateQueries(['user', db.account.pubkey]);
queryClient.invalidateQueries({
queryKey: ['user', db.account.pubkey]
});
// reset form
reset();
// reset state

View File

@ -5,15 +5,19 @@ import { LoaderIcon } from '@shared/icons';
import { compactNumber } from '@utils/number';
export function UserStats({ pubkey }: { pubkey: string }) {
const { status, data } = useQuery(['user-metadata', pubkey], async () => {
const res = await fetch(`https://api.nostr.band/v0/stats/profile/${pubkey}`);
if (!res.ok) {
throw new Error('Error');
}
return await res.json();
const { status, data } = useQuery({
queryKey: ['user-metadata', pubkey],
...async () => {
const res = await fetch(`https://api.nostr.band/v0/stats/profile/${pubkey}`);
if (!res.ok) {
throw new Error('Error');
}
return await res.json();
},
});
if (status === 'loading') {
if (status === 'pending') {
return (
<div className="flex w-full items-center justify-center">
<LoaderIcon className="h-5 w-5 animate-spin text-neutral-900 dark:text-neutral-100" />

View File

@ -19,14 +19,18 @@ import {
export function UserScreen() {
const { pubkey } = useParams();
const { ndk } = useNDK();
const { status, data } = useQuery(['user-feed', pubkey], async () => {
const events = await ndk.fetchEvents({
kinds: [NDKKind.Text, NDKKind.Repost, NDKKind.Article],
authors: [pubkey],
limit: 50,
});
const sorted = [...events].sort((a, b) => b.created_at - a.created_at);
return sorted;
const { status, data } = useQuery({
queryKey: ['user-feed', pubkey],
queryFn: async () => {
const events = await ndk.fetchEvents({
kinds: [NDKKind.Text, NDKKind.Repost, NDKKind.Article],
authors: [pubkey],
limit: 50,
});
const sorted = [...events].sort((a, b) => b.created_at - a.created_at);
return sorted;
},
refetchOnWindowFocus: false,
});
// render event match event kind
@ -73,7 +77,7 @@ export function UserScreen() {
Latest posts
</h3>
<div className="mx-auto flex h-full max-w-[500px] flex-col justify-between gap-1.5 pb-4 pt-1.5">
{status === 'loading' ? (
{status === 'pending' ? (
<div>Loading...</div>
) : data.length === 0 ? (
<div className="px-3 py-1.5">

View File

@ -5,60 +5,30 @@ import type {
NDKFilter,
NDKSubscription,
NDKUserProfile,
NostrEvent,
} from '@nostr-dev-kit/ndk';
import _debug from 'debug';
import { LRUCache } from 'lru-cache';
import { matchFilter } from 'nostr-tools';
import { LRUCache } from 'typescript-lru-cache';
import { createDatabase, db } from './db';
import { LumeStorage } from '@libs/storage/instance';
export { db } from './db';
interface NDKCacheAdapterDexieOptions {
/**
* The name of the database to use
*/
dbName?: string;
/**
* Debug instance to use for logging
*/
debug?: debug.IDebugger;
/**
* The number of seconds to store events in Dexie (IndexedDB) before they expire
* Defaults to 3600 seconds (1 hour)
*/
expirationTime?: number;
/**
* Number of profiles to keep in an LRU cache
*/
profileCacheSize?: number | 'disabled';
}
export default class NDKCacheAdapterDexie implements NDKCacheAdapter {
public debug: debug.Debugger;
private expirationTime;
readonly locking;
export default class NDKCacheAdapterTauri implements NDKCacheAdapter {
public db: LumeStorage;
public profiles?: LRUCache<Hexpubkey, NDKUserProfile>;
private dirtyProfiles: Set<Hexpubkey> = new Set();
readonly locking: boolean;
constructor(opts: NDKCacheAdapterDexieOptions = {}) {
createDatabase(opts.dbName || 'ndk');
this.debug = opts.debug || _debug('ndk:dexie-adapter');
constructor(db: LumeStorage) {
this.db = db;
this.locking = true;
this.expirationTime = opts.expirationTime || 3600;
if (opts.profileCacheSize !== 'disabled') {
this.profiles = new LRUCache({
maxSize: opts.profileCacheSize || 100000,
});
this.profiles = new LRUCache({
max: 100000,
});
setInterval(() => {
this.dumpProfiles();
}, 1000 * 10);
}
setInterval(() => {
this.dumpProfiles();
}, 1000 * 10);
}
public async query(subscription: NDKSubscription): Promise<void> {
@ -73,9 +43,9 @@ export default class NDKCacheAdapterDexie implements NDKCacheAdapter {
let profile = this.profiles.get(pubkey);
if (!profile) {
const user = await db.users.get({ pubkey });
const user = await this.db.getCacheUser(pubkey);
if (user) {
profile = user.profile;
profile = user.profile as NDKUserProfile;
this.profiles.set(pubkey, profile);
}
}
@ -126,7 +96,7 @@ export default class NDKCacheAdapterDexie implements NDKCacheAdapter {
if (event.isParamReplaceable()) {
const replaceableId = `${event.kind}:${event.pubkey}:${event.tagId()}`;
const existingEvent = await db.events.where({ id: replaceableId }).first();
const existingEvent = await this.db.getCacheEvent(replaceableId);
if (
existingEvent &&
event.created_at &&
@ -137,7 +107,7 @@ export default class NDKCacheAdapterDexie implements NDKCacheAdapter {
}
if (addEvent) {
db.events.put({
this.db.setCacheEvent({
id: event.tagId(),
pubkey: event.pubkey,
content: event.content,
@ -153,7 +123,7 @@ export default class NDKCacheAdapterDexie implements NDKCacheAdapter {
event.tags.forEach((tag) => {
if (tag[0].length !== 1) return;
db.eventTags.put({
this.db.setCacheEventTag({
id: `${event.id}:${tag[0]}:${tag[1]}`,
eventId: event.id,
tag: tag[0],
@ -182,9 +152,9 @@ export default class NDKCacheAdapterDexie implements NDKCacheAdapter {
if (hasAllKeys && filter.authors) {
for (const pubkey of filter.authors) {
const events = await db.events.where({ pubkey }).toArray();
const events = await this.db.getCacheEventsByPubkey(pubkey);
for (const event of events) {
let rawEvent;
let rawEvent: NostrEvent;
try {
rawEvent = JSON.parse(event.event);
} catch (e) {
@ -218,9 +188,9 @@ export default class NDKCacheAdapterDexie implements NDKCacheAdapter {
if (hasAllKeys && filter.kinds) {
for (const kind of filter.kinds) {
const events = await db.events.where({ kind }).toArray();
const events = await this.db.getCacheEventsByKind(kind);
for (const event of events) {
let rawEvent;
let rawEvent: NostrEvent;
try {
rawEvent = JSON.parse(event.event);
} catch (e) {
@ -252,10 +222,10 @@ export default class NDKCacheAdapterDexie implements NDKCacheAdapter {
if (hasAllKeys && filter.ids) {
for (const id of filter.ids) {
const event = await db.events.where({ id }).first();
const event = await this.db.getCacheEvent(id);
if (!event) continue;
let rawEvent;
let rawEvent: NostrEvent;
try {
rawEvent = JSON.parse(event.event);
} catch (e) {
@ -295,10 +265,10 @@ export default class NDKCacheAdapterDexie implements NDKCacheAdapter {
for (const author of filter.authors) {
for (const dTag of filter['#d']) {
const replaceableId = `${kind}:${author}:${dTag}`;
const event = await db.events.where({ id: replaceableId }).first();
const event = await this.db.getCacheEvent(replaceableId);
if (!event) continue;
let rawEvent;
let rawEvent: NostrEvent;
try {
rawEvent = JSON.parse(event.event);
} catch (e) {
@ -335,10 +305,10 @@ export default class NDKCacheAdapterDexie implements NDKCacheAdapter {
if (filter.kinds && filter.authors) {
for (const kind of filter.kinds) {
for (const author of filter.authors) {
const events = await db.events.where({ kind, pubkey: author }).toArray();
const events = await this.db.getCacheEventsByKindAndAuthor(kind, author);
for (const event of events) {
let rawEvent;
let rawEvent: NostrEvent;
try {
rawEvent = JSON.parse(event.event);
} catch (e) {
@ -400,12 +370,12 @@ export default class NDKCacheAdapterDexie implements NDKCacheAdapter {
}
for (const value of values) {
const eventTags = await db.eventTags.where({ tagValue: tag + value }).toArray();
const eventTags = await this.db.getCacheEventTagsByTagValue(tag + value);
if (!eventTags.length) continue;
const eventIds = eventTags.map((t) => t.eventId);
const events = await db.events.where('id').anyOf(eventIds).toArray();
const events = await this.db.getCacheEvents(eventIds);
for (const event of events) {
let rawEvent;
try {
@ -441,13 +411,13 @@ export default class NDKCacheAdapterDexie implements NDKCacheAdapter {
profiles.push({
pubkey,
profile,
profile: JSON.stringify(profile),
createdAt: Date.now(),
});
}
if (profiles.length) {
await db.users.bulkPut(profiles);
await this.db.setCacheProfiles(profiles);
}
this.dirtyProfiles.clear();

View File

@ -1,11 +1,11 @@
import NDK, { NDKNip46Signer, NDKPrivateKeySigner } from '@nostr-dev-kit/ndk';
import NDKCacheAdapterDexie from '@nostr-dev-kit/ndk-cache-dexie';
import { ndkAdapter } from '@nostr-fetch/adapter-ndk';
import { message } from '@tauri-apps/plugin-dialog';
import { fetch } from '@tauri-apps/plugin-http';
import { NostrFetcher } from 'nostr-fetch';
import { useEffect, useMemo, useState } from 'react';
import NDKCacheAdapterTauri from '@libs/ndk/cache';
import { useStorage } from '@libs/storage/provider';
export const NDKInstance = () => {
@ -77,7 +77,7 @@ export const NDKInstance = () => {
const outboxSetting = await db.getSettingValue('outbox');
const explicitRelayUrls = await getExplicitRelays();
const dexieAdapter = new NDKCacheAdapterDexie({ dbName: 'lume_ndkcache' });
const dexieAdapter = new NDKCacheAdapterTauri(db);
const instance = new NDK({
explicitRelayUrls,
cacheAdapter: dexieAdapter,

View File

@ -1,12 +1,20 @@
import { NDKEvent } from '@nostr-dev-kit/ndk';
import { invoke } from '@tauri-apps/api';
import { invoke } from '@tauri-apps/api/primitives';
import { Platform } from '@tauri-apps/plugin-os';
import Database from '@tauri-apps/plugin-sql';
import { FULL_RELAYS } from '@stores/constants';
import { rawEvent } from '@utils/transform';
import { Account, DBEvent, Relays, Widget } from '@utils/types';
import type {
Account,
DBEvent,
NDKCacheEvent,
NDKCacheEventTag,
NDKCacheUser,
Relays,
Widget,
} from '@utils/types';
export class LumeStorage {
public db: Database;
@ -37,6 +45,115 @@ export class LumeStorage {
return await invoke('secure_remove', { key });
}
public async getCacheUser(pubkey: string) {
const results: Array<NDKCacheUser> = await this.db.select(
'SELECT * FROM ndk_users WHERE pubkey = $1 ORDER BY pubkey DESC LIMIT 1;',
[pubkey]
);
if (results.length < 1) return null;
if (typeof results[0].profile === 'string')
results[0].profile = JSON.parse(results[0].profile);
return results[0];
}
public async getCacheEvent(id: string) {
const results: Array<NDKCacheEvent> = await this.db.select(
'SELECT * FROM ndk_events WHERE id = $1 ORDER BY id DESC LIMIT 1;',
[id]
);
if (results.length < 1) return null;
return results[0];
}
public async getCacheEvents(ids: string[]) {
const idsArr = `'${ids.join("','")}'`;
const results: Array<NDKCacheEvent> = await this.db.select(
`SELECT * FROM ndk_events WHERE id IN (${idsArr}) ORDER BY id;`
);
if (results.length < 1) return [];
return results;
}
public async getCacheEventsByPubkey(pubkey: string) {
const results: Array<NDKCacheEvent> = await this.db.select(
'SELECT * FROM ndk_events WHERE pubkey = $1 ORDER BY id;',
[pubkey]
);
if (results.length < 1) return [];
return results;
}
public async getCacheEventsByKind(kind: number) {
const results: Array<NDKCacheEvent> = await this.db.select(
'SELECT * FROM ndk_events WHERE kind = $1 ORDER BY id;',
[kind]
);
if (results.length < 1) return [];
return results;
}
public async getCacheEventsByKindAndAuthor(kind: number, pubkey: string) {
const results: Array<NDKCacheEvent> = await this.db.select(
'SELECT * FROM ndk_events WHERE kind = $1 AND pubkey = $2 ORDER BY id;',
[kind, pubkey]
);
if (results.length < 1) return [];
return results;
}
public async getCacheEventTagsByTagValue(tagValue: string) {
const results: Array<NDKCacheEventTag> = await this.db.select(
'SELECT * FROM ndk_eventtags WHERE tagValue = $1 ORDER BY id;',
[tagValue]
);
if (results.length < 1) return [];
return results;
}
public async setCacheEvent({
id,
pubkey,
content,
kind,
createdAt,
relay,
event,
}: NDKCacheEvent) {
return await this.db.execute(
'INSERT OR IGNORE INTO ndk_events (id, pubkey, content, kind, createdAt, relay, event) VALUES ($1, $2, $3, $4, $5, $6, $7);',
[id, pubkey, content, kind, createdAt, relay, event]
);
}
public async setCacheEventTag({ id, eventId, tag, value, tagValue }: NDKCacheEventTag) {
return await this.db.execute(
'INSERT OR IGNORE INTO ndk_eventtags (id, eventId, tag, value, tagValue) VALUES ($1, $2, $3, $4, $5);',
[id, eventId, tag, value, tagValue]
);
}
public async setCacheProfiles(profiles: Array<NDKCacheUser>) {
return await Promise.all(
profiles.map(
async (profile) =>
await this.db.execute(
'INSERT OR IGNORE INTO ndk_users (pubkey, profile, createdAt) VALUES ($1, $2, $3);',
[profile.pubkey, profile.profile, profile.createdAt]
)
)
);
}
public async checkAccount() {
const result: Array<{ total: string }> = await this.db.select(
'SELECT COUNT(*) AS "total" FROM accounts;'
@ -137,7 +254,8 @@ export class LumeStorage {
}
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) {

View File

@ -1,4 +1,6 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister';
import { QueryClient } from '@tanstack/react-query';
import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client';
import { createRoot } from 'react-dom/client';
import { Toaster } from 'sonner';
@ -7,18 +9,28 @@ import { StorageProvider } from '@libs/storage/provider';
import App from './app';
const queryClient = new QueryClient();
const queryClient = new QueryClient({
defaultOptions: {
queries: {
gcTime: 1000 * 60 * 60 * 24, // 24 hours
},
},
});
const persister = createSyncStoragePersister({
storage: window.localStorage,
});
const container = document.getElementById('root');
const root = createRoot(container);
root.render(
<QueryClientProvider client={queryClient}>
<PersistQueryClientProvider client={queryClient} persistOptions={{ persister }}>
<StorageProvider>
<NDKProvider>
<Toaster position="top-center" closeButton />
<App />
</NDKProvider>
</StorageProvider>
</QueryClientProvider>
</PersistQueryClientProvider>
);

View File

@ -1,100 +1,23 @@
import { NDKFilter, NDKKind } from '@nostr-dev-kit/ndk';
import * as Avatar from '@radix-ui/react-avatar';
import { minidenticon } from 'minidenticons';
import { useEffect } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { Link } from 'react-router-dom';
import { useNDK } from '@libs/ndk/provider';
import { useStorage } from '@libs/storage/provider';
import { AccountMoreActions } from '@shared/accounts/more';
import { NetworkStatusIndicator } from '@shared/networkStatusIndicator';
import { useActivities } from '@stores/activities';
import { useNostr } from '@utils/hooks/useNostr';
import { useProfile } from '@utils/hooks/useProfile';
import { sendNativeNotification } from '@utils/notification';
export function ActiveAccount() {
const { db } = useStorage();
const { ndk } = useNDK();
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 =
'data:image/svg+xml;utf8,' +
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 === 'loading') {
if (status === 'pending') {
return (
<div className="aspect-square h-auto w-full animate-pulse rounded-lg bg-neutral-300 dark:bg-neutral-700" />
);

View File

@ -1,14 +1,16 @@
import { message, open } from '@tauri-apps/plugin-dialog';
import { readBinaryFile } from '@tauri-apps/plugin-fs';
import { message } from '@tauri-apps/plugin-dialog';
import { Dispatch, SetStateAction, useState } from 'react';
import { LoaderIcon, PlusIcon } from '@shared/icons';
import { useNostr } from '@utils/hooks/useNostr';
export function AvatarUploader({
setPicture,
}: {
setPicture: Dispatch<SetStateAction<string>>;
}) {
const { upload } = useNostr();
const [loading, setLoading] = useState(false);
const uploadAvatar = async () => {
@ -16,42 +18,14 @@ export function AvatarUploader({
// start loading
setLoading(true);
const selected = await open({
multiple: false,
filters: [
{
name: 'Image',
extensions: ['png', 'jpeg', 'jpg', 'gif'],
},
],
});
const image = await upload();
if (!selected) {
setLoading(false);
return;
}
const file = await readBinaryFile(selected.path);
const blob = new Blob([file]);
const data = new FormData();
data.append('fileToUpload', blob);
data.append('submit', 'Upload Image');
const res = await fetch('https://nostr.build/api/v2/upload/files', {
method: 'POST',
body: data,
});
if (res.ok) {
const json = await res.json();
const content = json.data[0];
setPicture(content.url);
// stop loading
if (image) {
setPicture(image);
setLoading(false);
}
return;
} catch (e) {
// stop loading
setLoading(false);

View File

@ -1,14 +1,16 @@
import { message, open } from '@tauri-apps/plugin-dialog';
import { readBinaryFile } from '@tauri-apps/plugin-fs';
import { message } from '@tauri-apps/plugin-dialog';
import { Dispatch, SetStateAction, useState } from 'react';
import { LoaderIcon, PlusIcon } from '@shared/icons';
import { useNostr } from '@utils/hooks/useNostr';
export function BannerUploader({
setBanner,
}: {
setBanner: Dispatch<SetStateAction<string>>;
}) {
const { upload } = useNostr();
const [loading, setLoading] = useState(false);
const uploadBanner = async () => {
@ -16,42 +18,14 @@ export function BannerUploader({
// start loading
setLoading(true);
const selected = await open({
multiple: false,
filters: [
{
name: 'Image',
extensions: ['png', 'jpeg', 'jpg', 'gif'],
},
],
});
const image = await upload();
if (!selected) {
setLoading(false);
return;
}
const file = await readBinaryFile(selected.path);
const blob = new Blob([file]);
const data = new FormData();
data.append('fileToUpload', blob);
data.append('submit', 'Upload Image');
const res = await fetch('https://nostr.build/api/v2/upload/files', {
method: 'POST',
body: data,
});
if (res.ok) {
const json = await res.json();
const content = json.data[0];
setBanner(content.url);
// stop loading
if (image) {
setBanner(image);
setLoading(false);
}
return;
} catch (e) {
// stop loading
setLoading(false);

View File

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

View File

@ -20,9 +20,9 @@ export const NIP05 = memo(function NIP05({
nip05: string;
className?: string;
}) {
const { status, data } = useQuery(
['nip05', nip05],
async () => {
const { status, data } = useQuery({
queryKey: ['nip05', nip05],
queryFn: async () => {
try {
const localPath = nip05.split('@')[0];
const service = nip05.split('@')[1];
@ -47,15 +47,13 @@ export const NIP05 = memo(function NIP05({
throw new Error(`Failed to verify NIP-05, error: ${e}`);
}
},
{
refetchOnMount: false,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
staleTime: Infinity,
}
);
refetchOnMount: false,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
staleTime: Infinity,
});
if (status === 'loading') {
if (status === 'pending') {
<div className="h-3 w-20 animate-pulse rounded bg-white/10" />;
}

View File

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

View File

@ -1,7 +1,7 @@
import { webln } from '@getalby/sdk';
import { SendPaymentResponse } from '@getalby/sdk/dist/types';
import * as Dialog from '@radix-ui/react-dialog';
import { invoke } from '@tauri-apps/api';
import { invoke } from '@tauri-apps/api/primitives';
import { message } from '@tauri-apps/plugin-dialog';
import { QRCodeSVG } from 'qrcode.react';
import { useEffect, useRef, useState } from 'react';

View File

@ -30,7 +30,7 @@ export function ChildNote({ id, root }: { id: string; root?: string }) {
}
};
if (status === 'loading') {
if (status === 'pending') {
return (
<>
<div className="absolute bottom-0 left-[18px] h-[calc(100%-3.4rem)] w-0.5 bg-gradient-to-t from-black/20 to-black/10 dark:from-white/20 dark:to-white/10" />

View File

@ -2,8 +2,6 @@ import { NDKEvent } from '@nostr-dev-kit/ndk';
import { memo, useMemo } from 'react';
import { Link } from 'react-router-dom';
import { Image } from '@shared/image';
export function ArticleNote(props: { event?: NDKEvent }) {
const metadata = useMemo(() => {
const title = props.event.tags.find((tag) => tag[0] === 'title')?.[1];
@ -28,28 +26,30 @@ export function ArticleNote(props: { event?: NDKEvent }) {
}, [props.event.id]);
return (
<Link to={`/notes/article/${props.event.id}`} preventScrollReset={true}>
<div className="my-2 overflow-hidden rounded-lg">
{metadata.image && (
<Image
src={metadata.image}
alt={metadata.title}
className="h-44 w-full rounded-t-lg object-cover"
/>
)}
<div className="flex flex-col gap-1 rounded-b-lg bg-neutral-200 px-3 py-3 dark:bg-neutral-800">
<h5 className="line-clamp-1 font-semibold text-neutral-900 dark:text-neutral-100">
{metadata.title}
</h5>
{metadata.summary ? (
<p className="line-clamp-3 break-all text-sm text-neutral-600 dark:text-neutral-400">
{metadata.summary}
</p>
) : null}
<span className="mt-2.5 text-sm text-neutral-500 dark:text-neutral-400">
{metadata.publishedAt.toString()}
</span>
</div>
<Link
to={`/notes/article/${props.event.id}`}
preventScrollReset={true}
className="mt-2 flex w-full flex-col rounded-lg border border-neutral-300 bg-neutral-200 dark:border-neutral-700 dark:bg-neutral-800"
>
{metadata.image && (
<img
src={metadata.image}
alt={metadata.title}
className="h-44 w-full rounded-t-lg object-cover"
/>
)}
<div className="flex flex-col gap-1 rounded-b-lg bg-neutral-200 px-3 py-3 dark:bg-neutral-800">
<h5 className="line-clamp-1 font-semibold text-neutral-900 dark:text-neutral-100">
{metadata.title}
</h5>
{metadata.summary ? (
<p className="line-clamp-3 break-all text-sm text-neutral-600 dark:text-neutral-400">
{metadata.summary}
</p>
) : null}
<span className="mt-2.5 text-sm text-neutral-600 dark:text-neutral-400">
{metadata.publishedAt.toString()}
</span>
</div>
</Link>
);

View File

@ -1,67 +1,38 @@
import { NDKEvent } from '@nostr-dev-kit/ndk';
import ReactMarkdown from 'react-markdown';
import { Link } from 'react-router-dom';
import remarkGfm from 'remark-gfm';
import Markdown from 'markdown-to-jsx';
import { Boost, Hashtag, Invoice, MentionUser } from '@shared/notes';
export function ArticleDetailNote({ event }: { event: NDKEvent }) {
/*const metadata = useMemo(() => {
const title = event.tags.find((tag) => tag[0] === 'title')?.[1];
const image = event.tags.find((tag) => tag[0] === 'image')?.[1];
const summary = event.tags.find((tag) => tag[0] === 'summary')?.[1];
let publishedAt: Date | string | number = event.tags.find(
(tag) => tag[0] === 'published_at'
)?.[1];
if (publishedAt) {
publishedAt = new Date(parseInt(publishedAt)).toLocaleDateString('en-US');
} else {
publishedAt = new Date(event.created_at * 1000).toLocaleDateString('en-US');
}
return {
title,
image,
publishedAt,
summary,
};
}, [event.id]);*/
return (
<ReactMarkdown
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"
remarkPlugins={[remarkGfm]}
components={{
a: ({ href }) => {
const cleanURL = new URL(href);
cleanURL.search = '';
return (
<Link to={href} target="_blank" className="w-max break-all hover:!underline">
{cleanURL.hostname + cleanURL.pathname}
</Link>
);
},
del: ({ children }) => {
const key = children[0] as string;
if (typeof key !== 'string') return;
if (key.startsWith('pub') && key.length > 50 && key.length < 100) {
return <MentionUser pubkey={key.replace('pub-', '')} />;
}
if (key.startsWith('tag')) {
return <Hashtag tag={key.replace('tag-', '')} />;
}
if (key.startsWith('boost')) {
return <Boost boost={key.replace('boost-', '')} />;
}
if (key.startsWith('lnbc')) {
return <Invoice invoice={key.replace('lnbc-', '')} />;
}
<Markdown
options={{
overrides: {
Hashtag: {
component: Hashtag,
},
Boost: {
component: Boost,
},
MentionUser: {
component: MentionUser,
},
Invoice: {
component: Invoice,
},
a: {
props: {
target: '_blank',
},
},
},
slugify: (str) => str,
forceBlock: true,
enforceAtxHeadings: true,
}}
linkTarget={'_blank'}
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"
>
{event.content}
</ReactMarkdown>
</Markdown>
);
}

View File

@ -1,17 +1,19 @@
import { NDKEvent } from '@nostr-dev-kit/ndk';
import { downloadDir } from '@tauri-apps/api/path';
import { download } from '@tauri-apps/plugin-upload';
import {
MediaControlBar,
MediaController,
MediaMuteButton,
MediaPlayButton,
MediaSeekBackwardButton,
MediaSeekForwardButton,
MediaTimeDisplay,
MediaTimeRange,
MediaVolumeRange,
} from 'media-chrome/dist/react';
import { memo } from 'react';
import { Link } from 'react-router-dom';
import { DownloadIcon } from '@shared/icons';
import { LinkPreview } from '@shared/notes';
import { fileType } from '@utils/nip94';
@ -19,56 +21,58 @@ export function FileNote(props: { event?: NDKEvent }) {
const url = props.event.tags.find((el) => el[0] === 'url')[1];
const type = fileType(url);
const downloadImage = async (url: string) => {
const downloadDirPath = await downloadDir();
const filename = url.substring(url.lastIndexOf('/') + 1);
return await download(url, downloadDirPath + `/${filename}`);
};
if (type === 'image') {
return (
<div className="mb-2 mt-3">
<div key={url} className="group relative mt-2">
<img
src={url}
alt={props.event.content}
className="h-auto w-full rounded-lg object-cover"
loading="lazy"
decoding="async"
style={{ contentVisibility: 'auto' }}
alt={url}
className="h-auto w-full rounded-lg border border-neutral-300 object-cover dark:border-neutral-700"
/>
<button
type="button"
onClick={() => downloadImage(url)}
className="absolute right-2 top-2 hidden h-10 w-10 items-center justify-center rounded-lg bg-black/50 backdrop-blur-xl group-hover:inline-flex hover:bg-blue-500"
>
<DownloadIcon className="h-5 w-5 text-white" />
</button>
</div>
);
}
if (type === 'video') {
return (
<div className="mb-2 mt-3">
<MediaController key={url} className="aspect-video overflow-hidden rounded-lg">
<video
slot="media"
src={url}
poster={`https://thumbnail.video/api/get?url=${url}&seconds=1`}
preload="none"
muted
crossOrigin=""
/>
<MediaControlBar>
<MediaPlayButton></MediaPlayButton>
<MediaSeekBackwardButton></MediaSeekBackwardButton>
<MediaSeekForwardButton></MediaSeekForwardButton>
<MediaTimeRange></MediaTimeRange>
<MediaTimeDisplay showDuration></MediaTimeDisplay>
<MediaMuteButton></MediaMuteButton>
<MediaVolumeRange></MediaVolumeRange>
</MediaControlBar>
</MediaController>
</div>
<MediaController
key={url}
className="mt-2 aspect-video w-full overflow-hidden rounded-lg"
>
<video
slot="media"
src={url}
poster={`https://thumbnail.video/api/get?url=${url}&seconds=1`}
preload="none"
muted
/>
<MediaControlBar>
<MediaPlayButton></MediaPlayButton>
<MediaTimeRange></MediaTimeRange>
<MediaTimeDisplay showDuration></MediaTimeDisplay>
<MediaMuteButton></MediaMuteButton>
<MediaVolumeRange></MediaVolumeRange>
</MediaControlBar>
</MediaController>
);
}
return (
<div className="mb-2">
<Link
to={url}
target="_blank"
className="break-all font-normal text-blue-500 hover:text-blue-600"
>
{url}
</Link>
<div className="mt-2">
<LinkPreview urls={[url]} />
</div>
);
}

View File

@ -2,7 +2,6 @@ import { NDKEvent, NDKKind } from '@nostr-dev-kit/ndk';
import { useQuery } from '@tanstack/react-query';
import { nip19 } from 'nostr-tools';
import { memo, useCallback } from 'react';
import { twMerge } from 'tailwind-merge';
import { useNDK } from '@libs/ndk/provider';
@ -17,20 +16,14 @@ import {
} from '@shared/notes';
import { User } from '@shared/user';
export function Repost({
event,
lighter = false,
}: {
event: NDKEvent;
lighter?: boolean;
}) {
export function Repost({ event }: { event: NDKEvent }) {
const embedEvent: null | NDKEvent =
event.content.length > 0 ? JSON.parse(event.content) : null;
const { ndk } = useNDK();
const { status, isError, data } = useQuery(
['repost', event.id],
async () => {
const { status, isError, data } = useQuery({
queryKey: ['repost', event.id],
queryFn: async () => {
const id = event.tags.find((el) => el[0] === 'e')[1];
if (!id) throw new Error('wrong id');
@ -39,11 +32,9 @@ export function Repost({
return ndkEvent;
},
{
enabled: embedEvent === null,
refetchOnWindowFocus: false,
}
);
enabled: embedEvent === null,
refetchOnWindowFocus: false,
});
const renderKind = useCallback((repostEvent: NDKEvent) => {
switch (repostEvent.kind) {
@ -61,12 +52,7 @@ export function Repost({
if (embedEvent) {
return (
<div className="h-min w-full px-3 pb-3">
<div
className={twMerge(
'relative flex flex-col gap-1 overflow-hidden rounded-xl px-3 py-3',
!lighter ? 'bg-neutral-100 dark:bg-neutral-900' : 'bg-transparent'
)}
>
<div className="relative flex flex-col gap-1 overflow-hidden rounded-xl bg-neutral-100 px-3 py-3 dark:bg-neutral-900">
<User pubkey={event.pubkey} time={event.created_at} variant="repost" />
<div className="relative flex flex-col">
<User
@ -87,7 +73,7 @@ export function Repost({
);
}
if (status === 'loading') {
if (status === 'pending') {
return (
<div className="h-min w-full px-3 pb-3">
<div className="relative overflow-hidden rounded-xl border border-neutral-300 bg-neutral-200 p-3 dark:border-neutral-700 dark:bg-neutral-800">
@ -104,12 +90,7 @@ export function Repost({
return (
<div className="h-min w-full px-3 pb-3">
<div
className={twMerge(
'relative overflow-hidden rounded-xl px-3 py-3',
!lighter ? 'bg-neutral-100 dark:bg-neutral-900' : 'bg-transparent'
)}
>
<div className="relative overflow-hidden rounded-xl bg-neutral-100 px-3 py-3 dark:bg-neutral-900">
<div className="relative flex flex-col">
<div className="relative z-10 flex items-start gap-3">
<div className="inline-flex h-10 w-10 shrink-0 items-end justify-center rounded-lg bg-black"></div>
@ -135,12 +116,7 @@ export function Repost({
return (
<div className="h-min w-full px-3 pb-3">
<div
className={twMerge(
'relative flex flex-col gap-1 overflow-hidden rounded-xl px-3 py-3',
!lighter ? 'bg-neutral-100 dark:bg-neutral-900' : 'bg-transparent'
)}
>
<div className="relative flex flex-col gap-1 overflow-hidden rounded-xl bg-neutral-100 px-3 py-3 dark:bg-neutral-900">
<User pubkey={event.pubkey} time={event.created_at} variant="repost" />
<div className="relative flex flex-col">
<User pubkey={data.pubkey} time={data.created_at} eventId={data.id} />

View File

@ -1,7 +1,5 @@
import Markdown from 'markdown-to-jsx';
import { memo } from 'react';
import ReactMarkdown from 'react-markdown';
import { Link } from 'react-router-dom';
import remarkGfm from 'remark-gfm';
import {
Boost,
@ -16,68 +14,54 @@ import {
import { parser } from '@utils/parser';
export function TextNote(props: { content?: string }) {
const richContent = parser(props.content) ?? null;
export function TextNote(props: { content?: string; truncate?: boolean }) {
const richContent = parser(props.content);
if (!richContent) {
if (props.truncate) {
return (
<div>
<ReactMarkdown
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"
remarkPlugins={[remarkGfm]}
disallowedElements={['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'pre', 'code']}
unwrapDisallowed={true}
linkTarget={'_blank'}
>
{props.content}
</ReactMarkdown>
<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 (
<div>
<ReactMarkdown
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"
remarkPlugins={[remarkGfm]}
components={{
a: ({ href }) => {
const cleanURL = new URL(href);
cleanURL.search = '';
return (
<Link to={href} target="_blank" className="w-max break-all hover:underline">
{cleanURL.hostname + cleanURL.pathname}
</Link>
);
},
del: ({ children }) => {
const key = children[0] as string;
if (typeof key !== 'string') return;
if (key.startsWith('pub') && key.length > 50 && key.length < 100) {
return <MentionUser pubkey={key.replace('pub-', '')} />;
}
if (key.startsWith('tag')) {
return <Hashtag tag={key.replace('tag-', '')} />;
}
if (key.startsWith('boost')) {
return <Boost boost={key.replace('boost-', '')} />;
}
if (key.startsWith('lnbc')) {
return <Invoice invoice={key.replace('lnbc-', '')} />;
}
<div className="flex w-full flex-col items-start gap-2">
<Markdown
options={{
overrides: {
Hashtag: {
component: Hashtag,
},
Boost: {
component: Boost,
},
MentionUser: {
component: MentionUser,
},
Invoice: {
component: Invoice,
},
a: {
props: {
target: '_blank',
},
},
},
slugify: (str) => str,
forceBlock: true,
enforceAtxHeadings: true,
}}
disallowedElements={['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'pre', 'code']}
unwrapDisallowed={true}
linkTarget={'_blank'}
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}
</ReactMarkdown>
{richContent.images.length > 0 && <ImagePreview urls={richContent.images} />}
{richContent.videos.length > 0 && <VideoPreview urls={richContent.videos} />}
{richContent.links.length > 0 && <LinkPreview urls={richContent.links} />}
{richContent.notes.length > 0 &&
richContent.notes.map((note: string) => <MentionNote key={note} id={note} />)}
</Markdown>
{richContent.images.length ? <ImagePreview urls={richContent.images} /> : null}
{richContent.videos.length ? <VideoPreview urls={richContent.videos} /> : null}
{richContent.links.length ? <LinkPreview urls={richContent.links} /> : null}
{richContent.notes.map((note: string) => (
<MentionNote key={note} id={note} />
))}
</div>
);
}

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 }) {
const { db } = useStorage();
const setWidget = useWidgets((state) => state.setWidget);
const { addWidget } = useWidget();
return (
<span
role="button"
tabIndex={0}
<button
type="button"
onClick={() =>
setWidget(db, {
kind: WidgetKinds.global.hashtag,
title: tag,
content: tag.replace('#', ''),
})
}
onKeyDown={() =>
setWidget(db, {
addWidget.mutate({
kind: WidgetKinds.global.hashtag,
title: tag,
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"
>
{tag}
</span>
</button>
);
}

View File

@ -3,8 +3,8 @@ import { memo } from 'react';
export const Invoice = memo(function Invoice({ invoice }: { invoice: string }) {
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" />
</span>
</div>
);
});

View File

@ -2,8 +2,6 @@ import { NDKEvent, NDKKind } from '@nostr-dev-kit/ndk';
import { nip19 } from 'nostr-tools';
import { memo } from 'react';
import { useStorage } from '@libs/storage/provider';
import {
ArticleNote,
FileNote,
@ -14,20 +12,23 @@ import {
} from '@shared/notes';
import { User } from '@shared/user';
import { WidgetKinds, useWidgets } from '@stores/widgets';
import { WidgetKinds } from '@stores/constants';
import { useEvent } from '@utils/hooks/useEvent';
import { useWidget } from '@utils/hooks/useWidget';
export const MentionNote = memo(function MentionNote({ id }: { id: string }) {
const { db } = useStorage();
const { status, data } = useEvent(id);
const setWidget = useWidgets((state) => state.setWidget);
const { addWidget } = useWidget();
const openThread = (event, thread: string) => {
const selection = window.getSelection();
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 {
event.stopPropagation();
}
@ -46,9 +47,9 @@ export const MentionNote = memo(function MentionNote({ id }: { id: string }) {
}
};
if (status === 'loading') {
if (status === 'pending') {
return (
<div className="mt-3 cursor-default rounded-lg border border-neutral-300 bg-neutral-200 p-3 dark:border-neutral-700 dark:bg-neutral-800">
<div className="w-full cursor-default rounded-lg border border-neutral-300 bg-neutral-200 p-3 dark:border-neutral-700 dark:bg-neutral-800">
<NoteSkeleton />
</div>
);
@ -57,7 +58,7 @@ export const MentionNote = memo(function MentionNote({ id }: { id: string }) {
if (status === 'error') {
const noteLink = `https://njump.me/${nip19.noteEncode(id)}`;
return (
<div className="mt-3 rounded-lg bg-neutral-200 px-3 py-3 dark:bg-neutral-800">
<div className="w-full rounded-lg bg-neutral-200 px-3 py-3 dark:bg-neutral-800">
<div className="flex items-center gap-2">
<div className="inline-flex h-6 w-6 items-end justify-center rounded bg-black pb-1">
<img src="/lume.png" alt="lume" className="h-auto w-1/3" />
@ -74,15 +75,14 @@ export const MentionNote = memo(function MentionNote({ id }: { id: string }) {
}
return (
// eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/interactive-supports-focus
<div
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"
onClick={(e) => openThread(e, id)}
className="w-full 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" />
<div className="mt-1">{renderKind(data)}</div>
<div className="mt-1 text-left">{renderKind(data)}</div>
</div>
);
});

View File

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

View File

@ -3,23 +3,17 @@ import { useQuery } from '@tanstack/react-query';
import { decode } from 'light-bolt11-decoder';
import { useNDK } from '@libs/ndk/provider';
import { useStorage } from '@libs/storage/provider';
import { LoaderIcon } from '@shared/icons';
import { User } from '@shared/user';
import { WidgetKinds, useWidgets } from '@stores/widgets';
import { compactNumber } from '@utils/number';
export function NoteMetadata({ id }: { id: string }) {
const setWidget = useWidgets((state) => state.setWidget);
const { db } = useStorage();
const { ndk } = useNDK();
const { status, data } = useQuery(
['note-metadata', id],
async () => {
const { status, data } = useQuery({
queryKey: ['note-metadata', id],
queryFn: async () => {
let replies = 0;
let zap = 0;
const users = [];
@ -53,14 +47,12 @@ export function NoteMetadata({ id }: { id: string }) {
return { replies, users, zap };
},
{
enabled: !!ndk,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
}
);
enabled: !!ndk,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
});
if (status === 'loading') {
if (status === 'pending') {
return (
<div className="relative z-10 flex items-center gap-3 pb-3">
<div className="mt-2 h-6 w-11 shrink-0"></div>
@ -91,17 +83,7 @@ export function NoteMetadata({ id }: { id: string }) {
</div>
</div>
<div className="mt-2 inline-flex h-6 items-center gap-2">
<button
type="button"
onClick={() =>
setWidget(db, {
kind: WidgetKinds.local.thread,
title: 'Thread',
content: id,
})
}
className="text-neutral-600 dark:text-neutral-400"
>
<button type="button" className="text-neutral-600 dark:text-neutral-400">
<span className="font-semibold text-white">{data.replies}</span> replies
</button>
<span className="text-neutral-600 dark:text-neutral-400">·</span>

View File

@ -11,7 +11,7 @@ export function ImagePreview({ urls }: { urls: string[] }) {
};
return (
<div className="my-2 flex flex-col gap-2">
<div className="flex w-full flex-col gap-2">
{urls.map((url) => (
<div key={url} className="group relative">
<img

View File

@ -2,69 +2,60 @@ import { Link } from 'react-router-dom';
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[] }) {
const { status, data, error } = useOpenGraph(urls[0]);
const { status, data } = useOpenGraph(urls[0]);
const domain = new URL(urls[0]);
return (
<div className="my-2">
{status === 'loading' ? (
<div className="flex flex-col bg-neutral-200 dark:bg-neutral-800">
<div className="h-44 w-full animate-pulse bg-neutral-400 dark:bg-neutral-600" />
<div className="flex flex-col gap-2 px-3 py-3">
<div className="h-3 w-2/3 animate-pulse rounded bg-neutral-400 dark:bg-neutral-600" />
<div className="h-3 w-3/4 animate-pulse rounded bg-neutral-400 dark:bg-neutral-600" />
<span className="mt-2.5 text-sm leading-none text-neutral-600 dark:text-neutral-400">
{domain.hostname}
</span>
</div>
if (status === 'pending') {
return (
<div className="flex w-full flex-col bg-neutral-200 dark:bg-neutral-800">
<div className="h-44 w-full animate-pulse bg-neutral-400 dark:bg-neutral-600" />
<div className="flex flex-col gap-2 px-3 py-3">
<div className="h-3 w-2/3 animate-pulse rounded bg-neutral-400 dark:bg-neutral-600" />
<div className="h-3 w-3/4 animate-pulse rounded bg-neutral-400 dark:bg-neutral-600" />
<span className="mt-2.5 text-sm leading-none text-neutral-600 dark:text-neutral-400">
{domain.hostname}
</span>
</div>
) : (
<Link
to={urls[0]}
target="_blank"
rel="noreferrer"
className="flex flex-col rounded-lg border border-neutral-300 bg-neutral-200 dark:border-neutral-700 dark:bg-neutral-800"
>
{error ? (
<div className="flex flex-col gap-2 px-3 py-3">
<p className="text-sm text-neutral-600 dark:text-neutral-400">
Can&apos;t fetch open graph, click to open webpage
</p>
<span className="text-sm leading-none text-neutral-900 dark:text-neutral-100">
{domain.hostname}
</span>
</div>
) : (
<>
{data.image && (
<img
src={data.image}
alt={urls[0]}
className="h-44 w-full rounded-t-lg bg-white object-cover"
/>
)}
<div className="flex flex-col px-3 py-3">
<div className="flex flex-col gap-1">
{data.title && (
<h5 className="line-clamp-1 text-base font-semibold text-neutral-900 dark:text-neutral-100">
{data.title}
</h5>
)}
{data.description && (
<p className="mb-2.5 line-clamp-3 break-all text-sm text-neutral-700 dark:text-neutral-400">
{data.description}
</p>
)}
</div>
<span className="break-all text-sm text-neutral-600 dark:text-neutral-400">
{domain.hostname}
</span>
</div>
</>
</div>
);
}
return (
<Link
to={urls[0]}
target="_blank"
rel="noreferrer"
className="flex w-full flex-col rounded-lg border border-neutral-300 bg-neutral-200 dark:border-neutral-700 dark:bg-neutral-800"
>
{isImage(data.image) ? (
<img
src={data.image}
alt={urls[0]}
className="h-44 w-full rounded-t-lg bg-white object-cover"
/>
) : null}
<div className="flex flex-col items-start px-3 py-3">
<div className="flex flex-col items-start gap-1 text-left">
{data.title && (
<h5 className="line-clamp-1 text-base font-semibold text-neutral-900 dark:text-neutral-100">
{data.title}
</h5>
)}
</Link>
)}
</div>
{data.description ? (
<p className="mb-2.5 line-clamp-3 break-all text-sm text-neutral-700 dark:text-neutral-400">
{data.description}
</p>
) : null}
</div>
<span className="break-all text-sm text-neutral-600 dark:text-neutral-400">
{domain.hostname}
</span>
</div>
</Link>
);
}

View File

@ -11,7 +11,7 @@ import { memo } from 'react';
export const VideoPreview = memo(function VideoPreview({ urls }: { urls: string[] }) {
return (
<div className="my-2 flex flex-col gap-2">
<div className="flex w-full flex-col gap-2">
{urls.map((url) => (
<MediaController key={url} className="aspect-video overflow-hidden rounded-lg">
<video

View File

@ -2,17 +2,17 @@ export function NoteSkeleton() {
return (
<div className="flex h-min flex-col">
<div className="flex items-start gap-3">
<div className="relative h-10 w-10 shrink-0 overflow-hidden rounded-lg bg-neutral-400 dark:bg-neutral-600" />
<div className="relative h-10 w-10 shrink-0 animate-pulse overflow-hidden rounded-lg bg-neutral-400 dark:bg-neutral-600" />
<div className="h-6 w-full">
<div className="h-3 w-24 animate-pulse rounded bg-neutral-300 dark:bg-neutral-700" />
<div className="h-4 w-24 animate-pulse rounded bg-neutral-300 dark:bg-neutral-700" />
</div>
</div>
<div className="-mt-5 flex animate-pulse gap-3">
<div className="-mt-4 flex gap-3">
<div className="w-10 shrink-0" />
<div className="flex flex-col gap-1">
<div className="h-3 w-full rounded bg-neutral-400 dark:bg-neutral-600" />
<div className="h-3 w-2/3 rounded bg-neutral-400 dark:bg-neutral-600" />
<div className="h-3 w-1/2 rounded bg-neutral-400 dark:bg-neutral-600" />
<div className="flex w-full flex-col gap-1">
<div className="h-3 w-2/3 animate-pulse rounded bg-neutral-300 dark:bg-neutral-700" />
<div className="h-3 w-2/3 animate-pulse rounded bg-neutral-300 dark:bg-neutral-700" />
<div className="h-3 w-1/2 animate-pulse rounded bg-neutral-300 dark:bg-neutral-700" />
</div>
</div>
</div>

View File

@ -10,9 +10,9 @@ import { compactNumber } from '@utils/number';
export function NoteStats({ id }: { id: string }) {
const { ndk } = useNDK();
const { status, data } = useQuery(
['note-stats', id],
async () => {
const { status, data } = useQuery({
queryKey: ['note-stats', id],
queryFn: async () => {
let reactions = 0;
let reposts = 0;
let zaps = 0;
@ -48,10 +48,11 @@ export function NoteStats({ id }: { id: string }) {
return { reposts, reactions, zaps };
},
{ refetchOnWindowFocus: false, refetchOnReconnect: false }
);
refetchOnWindowFocus: false,
refetchOnReconnect: false,
});
if (status === 'loading') {
if (status === 'pending') {
return (
<div className="flex h-11 items-center">
<LoaderIcon className="h-4 w-4 animate-spin text-white" />

View File

@ -1,6 +1,5 @@
import { NDKEvent } from '@nostr-dev-kit/ndk';
import { ReactElement, cloneElement } from 'react';
import { twMerge } from 'tailwind-merge';
import { ReactElement, cloneElement, useMemo } from 'react';
import { ChildNote, NoteActions } from '@shared/notes';
import { User } from '@shared/user';
@ -8,25 +7,22 @@ import { User } from '@shared/user';
export function NoteWrapper({
event,
children,
root,
reply,
lighter = false,
}: {
event: NDKEvent;
children: ReactElement;
repost?: boolean;
root?: string;
reply?: string;
lighter?: boolean;
}) {
const root = useMemo(() => {
if (event.tags?.[0]?.[0] === 'e' && !event.tags?.[0]?.[3]) {
return event.tags[0][1];
}
return event.tags.find((el) => el[3] === 'root')?.[1];
}, [event]);
const reply = useMemo(() => event.tags.find((el) => el[3] === 'reply')?.[1], []);
return (
<div className="h-min w-full px-3 pb-3">
<div
className={twMerge(
'relative overflow-hidden rounded-xl px-3 py-4',
!lighter ? 'bg-neutral-100 dark:bg-neutral-900' : 'bg-transparent'
)}
>
<div className="relative overflow-hidden rounded-xl bg-neutral-100 px-3 py-4 dark:bg-neutral-900">
<div className="relative">{root && <ChildNote id={root} />}</div>
<div className="relative">{reply && <ChildNote id={reply} root={root} />}</div>
<div className="relative flex flex-col">

View File

@ -1,7 +1,5 @@
import { NDKEvent, NDKKind } from '@nostr-dev-kit/ndk';
import { useStorage } from '@libs/storage/provider';
import {
ArticleNote,
FileNote,
@ -11,33 +9,37 @@ import {
} from '@shared/notes';
import { User } from '@shared/user';
import { WidgetKinds, useWidgets } from '@stores/widgets';
import { WidgetKinds } from '@stores/constants';
import { formatCreatedAt } from '@utils/createdAt';
import { useEvent } from '@utils/hooks/useEvent';
import { useWidget } from '@utils/hooks/useWidget';
export function NotifyNote({ event }: { event: NDKEvent }) {
const createdAt = formatCreatedAt(event.created_at, false);
const rootEventId = event.tags.find((el) => el[0] === 'e')?.[1];
const { db } = useStorage();
const { status, data } = useEvent(rootEventId);
const setWidget = useWidgets((state) => state.setWidget);
const { addWidget } = useWidget();
const openThread = (event, thread: string) => {
const selection = window.getSelection();
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 {
event.stopPropagation();
}
};
const renderKind = (event: NDKEvent) => {
if (!event) return null;
switch (event.kind) {
case NDKKind.Text:
return <TextNote content={event.content} />;
return <TextNote content={event.content} truncate />;
case NDKKind.Article:
return <ArticleNote event={event} />;
case 1063:
@ -62,7 +64,7 @@ export function NotifyNote({ event }: { event: NDKEvent }) {
}
};
if (status === 'loading') {
if (status === 'pending') {
return (
<div className="h-min w-full px-3 pb-3">
<div className="relative overflow-hidden rounded-xl bg-white/10 px-3 py-3 backdrop-blur-xl">
@ -88,13 +90,13 @@ export function NotifyNote({ event }: { event: NDKEvent }) {
{event.kind === 1 ? <TextNote content={event.content} /> : null}
</div>
<div
onClick={(e) => openThread(e, data.id)}
onKeyDown={(e) => openThread(e, data.id)}
onClick={(e) => openThread(e, data?.id)}
onKeyDown={(e) => openThread(e, data?.id)}
role="button"
tabIndex={0}
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>
</div>

View File

@ -3,44 +3,64 @@ import { useStorage } from '@libs/storage/provider';
import { CancelIcon } from '@shared/icons';
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,
isLive,
}: {
id?: string;
title?: string;
isLive?: boolean;
}) {
const { db } = useStorage();
const remove = useWidgets((state) => state.removeWidget);
const { removeWidget } = useWidget();
return (
<div className="flex h-11 w-full shrink-0 items-center justify-between overflow-hidden px-3">
<div className="w-6" />
{id === '9999' ? (
<div className="isolate flex -space-x-2">
{db.account.circles
?.slice(0, 10)
.map((item) => <User key={item} pubkey={item} variant="ministacked" />)}
{db.account.circles?.length > 10 ? (
<div className="inline-flex h-6 w-6 items-center justify-center rounded-full bg-neutral-200 text-neutral-900 ring-1 ring-neutral-300 dark:bg-neutral-800 dark:text-neutral-100 dark:ring-neutral-700">
<span className="text-xs font-medium">
+{db.account.circles?.length - 10}
</span>
</div>
) : null}
</div>
) : (
<h3 className="text-sm font-semibold text-neutral-900 dark:text-neutral-100">
{title}
</h3>
)}
{id !== '9999' ? (
<button
type="button"
onClick={() => remove(db, 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"
>
<CancelIcon className="h-3 w-3" />
</button>
) : (
<div className="w-6" />
)}
<div className="grid h-11 w-full shrink-0 grid-cols-3 items-center px-3">
<div className="col-span-1 flex justify-start">
{isLive ? (
<div className="flex items-center gap-1.5">
<span className="relative flex h-2 w-2">
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-teal-400 opacity-75"></span>
<span className="relative inline-flex h-2 w-2 rounded-full bg-teal-500"></span>
</span>
<p className="text-xs font-medium text-teal-500">Live</p>
</div>
) : null}
</div>
<div className="col-span-1 flex justify-center">
{id === '9999' ? (
<div className="isolate flex -space-x-2">
{db.account.circles
?.slice(0, 8)
.map((item) => <User key={item} pubkey={item} variant="ministacked" />)}
{db.account.circles?.length > 8 ? (
<div className="inline-flex h-6 w-6 items-center justify-center rounded-full bg-neutral-300 text-neutral-900 ring-1 ring-white dark:bg-neutral-700 dark:text-neutral-100 dark:ring-black">
<span className="text-[8px] font-medium">
+{db.account.circles?.length - 8}
</span>
</div>
) : null}
</div>
) : (
<h3 className="text-sm font-semibold text-neutral-900 dark:text-neutral-100">
{title}
</h3>
)}
</div>
<div className="col-span-1 flex justify-end">
{id !== '9999' ? (
<button
type="button"
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"
>
<CancelIcon className="h-3 w-3" />
</button>
) : null}
</div>
</div>
);
}

View File

@ -2,9 +2,7 @@ import * as Avatar from '@radix-ui/react-avatar';
import * as HoverCard from '@radix-ui/react-hover-card';
import { minidenticon } from 'minidenticons';
import { memo } from 'react';
import ReactMarkdown from 'react-markdown';
import { Link } from 'react-router-dom';
import remarkGfm from 'remark-gfm';
import { RepostIcon, WorldIcon } from '@shared/icons';
import { NIP05 } from '@shared/nip05';
@ -45,39 +43,16 @@ export const User = memo(function User({
const svgURI =
'data:image/svg+xml;utf8,' + encodeURIComponent(minidenticon(pubkey, 90, 50));
if (status === 'loading') {
if (variant === 'avatar') {
if (variant === 'mention') {
if (status === 'pending') {
return (
<div className="h-12 w-12 animate-pulse overflow-hidden rounded-lg bg-neutral-300 dark:bg-neutral-700" />
);
}
if (variant === 'mention' || variant === 'notify') {
return (
<div className="relative flex items-center gap-3">
<div className="relative z-10 h-6 w-6 shrink-0 animate-pulse overflow-hidden rounded bg-neutral-300 dark:bg-neutral-700" />
<div className="flex items-center gap-2">
<div className="h-6 w-6 shrink-0 animate-pulse rounded bg-neutral-300 dark:bg-neutral-700" />
<div className="h-3.5 w-36 animate-pulse rounded bg-neutral-300 dark:bg-neutral-700" />
</div>
);
}
if (variant === 'stacked') {
return (
<div className="h-8 w-8 animate-pulse rounded-full bg-neutral-300 dark:bg-neutral-700" />
);
}
return (
<div className="flex items-start gap-3">
<div className="h-10 w-10 shrink-0 animate-pulse rounded-lg bg-neutral-300 dark:bg-neutral-700" />
<div className="h-6 w-full">
<div className="h-3 w-24 animate-pulse rounded bg-neutral-300 dark:bg-neutral-700" />
</div>
</div>
);
}
if (variant === 'mention') {
return (
<div className="flex items-center gap-2">
<Avatar.Root className="shrink-0">
@ -112,6 +87,15 @@ export const User = memo(function User({
}
if (variant === 'notify') {
if (status === 'pending') {
return (
<div className="flex items-center gap-2">
<div className="h-8 w-8 shrink-0 animate-pulse rounded bg-neutral-300 dark:bg-neutral-700" />
<div className="h-3.5 w-36 animate-pulse rounded bg-neutral-300 dark:bg-neutral-700" />
</div>
);
}
return (
<div className="flex items-center gap-2">
<Avatar.Root className="shrink-0">
@ -142,6 +126,19 @@ export const User = memo(function User({
}
if (variant === 'large') {
if (status === 'pending') {
return (
<div className="flex items-center gap-2.5">
<div className="h-14 w-14 shrink-0 animate-pulse rounded-lg bg-neutral-300 dark:bg-neutral-700" />
<div>
<div className="h-3.5 w-36 animate-pulse rounded bg-neutral-300 dark:bg-neutral-700" />
<div className="h-4 w-24 animate-pulse rounded bg-neutral-300 dark:bg-neutral-700" />
<div className="h-4 w-24 animate-pulse rounded bg-neutral-300 dark:bg-neutral-700" />
</div>
</div>
);
}
return (
<div className="flex h-full w-full flex-col gap-2.5">
<Avatar.Root className="shrink-0">
@ -166,15 +163,9 @@ export const User = memo(function User({
<p className="max-w-[15rem] truncate text-lg font-semibold text-neutral-900 dark:text-neutral-100">
{user?.name || user?.display_name || user?.displayName}
</p>
<ReactMarkdown
remarkPlugins={[remarkGfm]}
className="markdown-simple line-clamp-6 whitespace-pre-line break-all"
disallowedElements={['h1', 'h2', 'h3', 'h4', 'h5', 'h6']}
unwrapDisallowed={true}
linkTarget={'_blank'}
>
<p 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">
{user?.about || user?.bio || 'No bio'}
</ReactMarkdown>
</p>
</div>
<div className="flex flex-col gap-2">
{user?.website ? (
@ -194,6 +185,18 @@ export const User = memo(function User({
}
if (variant === 'simple') {
if (status === 'pending') {
return (
<div className="flex items-center gap-2.5">
<div className="h-11 w-11 shrink-0 animate-pulse rounded-lg bg-neutral-300 dark:bg-neutral-700" />
<div className="flex w-full flex-col items-start gap-1">
<div className="h-4 w-36 animate-pulse rounded bg-neutral-300 dark:bg-neutral-700" />
<div className="h-4 w-24 animate-pulse rounded bg-neutral-300 dark:bg-neutral-700" />
</div>
</div>
);
}
return (
<div className="flex items-center gap-2.5">
<Avatar.Root className="shrink-0">
@ -226,6 +229,12 @@ export const User = memo(function User({
}
if (variant === 'avatar') {
if (status === 'pending') {
return (
<div className="h-12 w-12 animate-pulse rounded-lg bg-neutral-300 dark:bg-neutral-700" />
);
}
return (
<Avatar.Root>
<Avatar.Image
@ -248,6 +257,12 @@ export const User = memo(function User({
}
if (variant === 'miniavatar') {
if (status === 'pending') {
return (
<div className="h-10 w-10 animate-pulse rounded-lg bg-neutral-300 dark:bg-neutral-700" />
);
}
return (
<Avatar.Root>
<Avatar.Image
@ -270,6 +285,12 @@ export const User = memo(function User({
}
if (variant === 'stacked') {
if (status === 'pending') {
return (
<div className="inline-block h-8 w-8 animate-pulse rounded-full bg-neutral-300 ring-1 ring-neutral-200 dark:bg-neutral-700 dark:ring-neutral-800" />
);
}
return (
<Avatar.Root>
<Avatar.Image
@ -292,6 +313,12 @@ export const User = memo(function User({
}
if (variant === 'ministacked') {
if (status === 'pending') {
return (
<div className="inline-block h-6 w-6 animate-pulse rounded-full bg-neutral-300 ring-1 ring-white dark:ring-black" />
);
}
return (
<Avatar.Root>
<Avatar.Image
@ -314,6 +341,20 @@ export const User = memo(function User({
}
if (variant === 'repost') {
if (status === 'pending') {
return (
<div className="flex gap-3">
<div className="inline-flex h-10 w-10 items-center justify-center">
<RepostIcon className="h-5 w-5 text-blue-500" />
</div>
<div className="inline-flex items-center gap-2">
<div className="h-6 w-6 animate-pulse rounded bg-neutral-300 dark:bg-neutral-700" />
<div className="h-4 w-24 animate-pulse rounded bg-neutral-300 dark:bg-neutral-700" />
</div>
</div>
);
}
return (
<div className="flex gap-3">
<div className="inline-flex h-10 w-10 items-center justify-center">
@ -352,6 +393,18 @@ export const User = memo(function User({
}
if (variant === 'thread') {
if (status === 'pending') {
return (
<div className="flex items-center gap-3">
<div className="h-10 w-10 shrink-0 animate-pulse rounded-lg bg-neutral-300 dark:bg-neutral-700" />
<div className="flex flex-1 flex-col">
<div className="h-4 w-36 animate-pulse rounded bg-neutral-300 dark:bg-neutral-700" />
<div className="h-4 w-24 animate-pulse rounded bg-neutral-300 dark:bg-neutral-700" />
</div>
</div>
);
}
return (
<div className="flex items-center gap-3">
<Avatar.Root className="h-10 w-10 shrink-0">
@ -385,6 +438,17 @@ export const User = memo(function User({
);
}
if (status === 'pending') {
return (
<div className="flex items-start gap-3">
<div className="h-10 w-10 shrink-0 animate-pulse rounded-lg bg-neutral-300 dark:bg-neutral-700" />
<div className="h-6 flex-1">
<div className="h-4 w-36 animate-pulse rounded bg-neutral-300 dark:bg-neutral-700" />
</div>
</div>
);
}
return (
<HoverCard.Root>
<div className="relative z-10 flex items-start gap-3">

View File

@ -1,77 +0,0 @@
import { useQueryClient } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import { useStorage } from '@libs/storage/provider';
import { useWidgets } from '@stores/widgets';
import { useNostr } from '@utils/hooks/useNostr';
export function EventLoader({ firstTime }: { firstTime: boolean }) {
const { db } = useStorage();
const { getAllEventsSinceLastLogin } = useNostr();
const [progress, setProgress] = useState(0);
const queryClient = useQueryClient();
const setIsFetched = useWidgets((state) => state.setIsFetched);
useEffect(() => {
async function getEvents() {
const events = await getAllEventsSinceLastLogin();
console.log('total new events has found: ', events.data.length);
const promises = await Promise.all(
events.data.map(async (event) => await db.createEvent(event))
);
if (promises) {
setProgress(100);
setIsFetched();
// invalidate queries
queryClient.invalidateQueries(['local-network-widget']);
await db.updateLastLogin();
}
}
// only start download if progress === 0
if (progress === 0) getEvents();
// auto increase progress after 2 secs
setInterval(() => setProgress((prev) => (prev += 5)), 2000);
}, []);
return (
<div className="mb-3 px-3">
<div className="h-max w-full rounded-lg bg-neutral-100 p-3 dark:bg-neutral-900">
<div className="flex flex-col items-center gap-3">
{firstTime ? (
<div>
<span className="text-4xl">👋</span>
<h3 className="mt-2 font-semibold leading-tight text-neutral-900 dark:text-neutral-100">
Hello, this is the first time you&apos;re using Lume
</h3>
<p className="text-sm text-neutral-600 dark:text-neutral-500">
Lume is downloading all events since the last 24 hours. It will auto
refresh when it done, please be patient
</p>
</div>
) : (
<div className="text-center">
<h3 className="font-semibold leading-tight text-neutral-500 dark:text-neutral-300">
Downloading all events while you&apos;re away...
</h3>
</div>
)}
<div className="flex h-1.5 w-full overflow-hidden rounded-full bg-neutral-200 dark:bg-neutral-800">
<div
className="flex flex-col justify-center overflow-hidden bg-blue-500 transition-all duration-1000 ease-smooth"
role="progressbar"
style={{ width: `${progress}%` }}
/>
</div>
</div>
</div>
</div>
);
}

View File

@ -1,58 +1,70 @@
import { NDKEvent, NDKKind } from '@nostr-dev-kit/ndk';
import { useQuery } from '@tanstack/react-query';
import { useCallback } from 'react';
import { useInfiniteQuery } from '@tanstack/react-query';
import { useMemo } from 'react';
import { VList } from 'virtua';
import { useNDK } from '@libs/ndk/provider';
import { LoaderIcon } from '@shared/icons';
import { ArrowRightCircleIcon, LoaderIcon } from '@shared/icons';
import { ArticleNote, NoteWrapper } from '@shared/notes';
import { TitleBar } from '@shared/titleBar';
import { WidgetWrapper } from '@shared/widgets';
import { FETCH_LIMIT } from '@stores/constants';
import { Widget } from '@utils/types';
export function GlobalArticlesWidget({ params }: { params: Widget }) {
const { ndk } = useNDK();
const { status, data } = useQuery(
['global-articles'],
async () => {
const events = await ndk.fetchEvents({
kinds: [NDKKind.Article],
limit: 200,
});
const sortedEvents = [...events].sort((x, y) => y.created_at - x.created_at);
return sortedEvents;
},
{ refetchOnWindowFocus: false }
);
const { ndk, relayUrls, fetcher } = useNDK();
const { status, data, hasNextPage, isFetchingNextPage, fetchNextPage } =
useInfiniteQuery({
queryKey: ['global-articles'],
initialPageParam: 0,
queryFn: async ({
signal,
pageParam,
}: {
signal: AbortSignal;
pageParam: number;
}) => {
const events = await fetcher.fetchLatestEvents(
relayUrls,
{
kinds: [NDKKind.Article],
},
FETCH_LIMIT,
{ asOf: pageParam === 0 ? undefined : pageParam, abortSignal: signal }
);
// render event match event kind
const renderItem = useCallback(
(event: NDKEvent) => {
return (
<NoteWrapper key={event.id} event={event}>
<ArticleNote />
</NoteWrapper>
);
},
const ndkEvents = events.map((event) => {
return new NDKEvent(ndk, event);
});
return ndkEvents.sort((a, b) => b.created_at - a.created_at);
},
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]
);
return (
<WidgetWrapper>
<TitleBar id={params.id} title={params.title} />
<div className="flex-1">
{status === 'loading' ? (
<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 article...
</p>
</div>
<VList className="flex-1">
{status === 'pending' ? (
<div className="flex h-full w-full items-center justify-center">
<LoaderIcon className="h-5 w-5 animate-spin" />
</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 flex-col items-center gap-4">
<img src="/ghost.png" alt="empty feeds" className="h-16 w-16" />
@ -67,12 +79,32 @@ export function GlobalArticlesWidget({ params }: { params: Widget }) {
</div>
</div>
) : (
<VList className="h-full" style={{ contentVisibility: 'auto' }}>
{data.map((item) => renderItem(item))}
<div className="h-14" />
</VList>
allEvents.map((item) => (
<NoteWrapper key={item.id} event={item}>
<ArticleNote />
</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>
);
}

View File

@ -1,66 +1,76 @@
import { NDKEvent } from '@nostr-dev-kit/ndk';
import { useQuery } from '@tanstack/react-query';
import { useCallback } from 'react';
import { useInfiniteQuery } from '@tanstack/react-query';
import { useMemo } from 'react';
import { VList } from 'virtua';
import { useNDK } from '@libs/ndk/provider';
import { LoaderIcon } from '@shared/icons';
import { ArrowRightCircleIcon, LoaderIcon } from '@shared/icons';
import { FileNote, NoteWrapper } from '@shared/notes';
import { TitleBar } from '@shared/titleBar';
import { WidgetWrapper } from '@shared/widgets';
import { nHoursAgo } from '@utils/date';
import { FETCH_LIMIT } from '@stores/constants';
import { Widget } from '@utils/types';
export function GlobalFilesWidget({ params }: { params: Widget }) {
const { ndk } = useNDK();
const { status, data } = useQuery(
['global-file-sharing'],
async () => {
const events = await ndk.fetchEvents({
// @ts-expect-error, NDK not support file metadata yet
kinds: [1063],
since: nHoursAgo(24),
});
const sortedEvents = [...events].sort((x, y) => y.created_at - x.created_at);
return sortedEvents;
},
{ refetchOnWindowFocus: false }
);
const { ndk, relayUrls, fetcher } = useNDK();
const { status, data, hasNextPage, isFetchingNextPage, fetchNextPage } =
useInfiniteQuery({
queryKey: ['global-files'],
initialPageParam: 0,
queryFn: async ({
signal,
pageParam,
}: {
signal: AbortSignal;
pageParam: number;
}) => {
const events = await fetcher.fetchLatestEvents(
relayUrls,
{
kinds: [1063],
},
FETCH_LIMIT,
{ asOf: pageParam === 0 ? undefined : pageParam, abortSignal: signal }
);
// render event match event kind
const renderItem = useCallback(
(event: NDKEvent) => {
return (
<NoteWrapper key={event.id} event={event}>
<FileNote />
</NoteWrapper>
);
},
const ndkEvents = events.map((event) => {
return new NDKEvent(ndk, event);
});
return ndkEvents.sort((a, b) => b.created_at - a.created_at);
},
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]
);
return (
<WidgetWrapper>
<TitleBar id={params.id} title={params.title} />
<div className="flex-1">
{status === 'loading' ? (
<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 file sharing event...
</p>
</div>
<VList className="flex-1">
{status === 'pending' ? (
<div className="flex h-full w-full items-center justify-center">
<LoaderIcon className="h-5 w-5 animate-spin" />
</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 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 file sharing events.
Oops, it looks like there are no files.
</h3>
<p className="text-neutral-500 dark:text-neutral-400">
You can close this widget
@ -69,12 +79,32 @@ export function GlobalFilesWidget({ params }: { params: Widget }) {
</div>
</div>
) : (
<VList className="h-full" style={{ contentVisibility: 'auto' }}>
{data.map((item) => renderItem(item))}
<div className="h-14" />
</VList>
allEvents.map((item) => (
<NoteWrapper key={item.id} event={item}>
<FileNote />
</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>
);
}

View File

@ -1,11 +1,11 @@
import { NDKEvent, NDKKind } from '@nostr-dev-kit/ndk';
import { useQuery } from '@tanstack/react-query';
import { useCallback } from 'react';
import { useInfiniteQuery } from '@tanstack/react-query';
import { useCallback, useMemo } from 'react';
import { VList } from 'virtua';
import { useNDK } from '@libs/ndk/provider';
import { LoaderIcon } from '@shared/icons';
import { ArrowRightCircleIcon, LoaderIcon } from '@shared/icons';
import {
ArticleNote,
FileNote,
@ -17,74 +17,94 @@ import {
import { TitleBar } from '@shared/titleBar';
import { WidgetWrapper } from '@shared/widgets';
import { nHoursAgo } from '@utils/date';
import { FETCH_LIMIT } from '@stores/constants';
import { Widget } from '@utils/types';
export function GlobalHashtagWidget({ params }: { params: Widget }) {
const { ndk } = useNDK();
const { status, data } = useQuery(
['hashtag-' + params.title],
async () => {
const events = await ndk.fetchEvents({
kinds: [NDKKind.Text, NDKKind.Repost, NDKKind.Article],
'#t': [params.content],
since: nHoursAgo(24),
});
const sortedEvents = [...events].sort((x, y) => y.created_at - x.created_at);
return sortedEvents;
},
{ refetchOnWindowFocus: false }
const { ndk, relayUrls, fetcher } = useNDK();
const { status, data, hasNextPage, isFetchingNextPage, fetchNextPage } =
useInfiniteQuery({
queryKey: ['hashtag-' + params.title],
initialPageParam: 0,
queryFn: async ({
signal,
pageParam,
}: {
signal: AbortSignal;
pageParam: number;
}) => {
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 }
);
const ndkEvents = events.map((event) => {
return new NDKEvent(ndk, event);
});
return ndkEvents.sort((a, b) => b.created_at - a.created_at);
},
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]
);
// 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>
);
}
},
[data]
);
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 (
<WidgetWrapper>
<TitleBar id={params.id} title={params.title} />
<div className="flex-1">
{status === 'loading' ? (
<VList 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 event related to the hashtag {params.title}...
</p>
</div>
<LoaderIcon className="h-5 w-5 animate-spin" />
</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 flex-col items-center gap-4">
<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}.
</h3>
<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>
</div>
</div>
</div>
) : (
<VList className="h-full" style={{ contentVisibility: 'auto' }}>
{data.map((item) => renderItem(item))}
<div className="h-16" />
</VList>
allEvents.map((item) => renderItem(item))
)}
</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>
);
}

View File

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

View File

@ -1,8 +1,9 @@
import { NDKEvent, NDKKind } from '@nostr-dev-kit/ndk';
import { useInfiniteQuery } from '@tanstack/react-query';
import { useCallback, useMemo } from 'react';
import { useMemo } from 'react';
import { VList } from 'virtua';
import { useNDK } from '@libs/ndk/provider';
import { useStorage } from '@libs/storage/provider';
import { ArrowRightCircleIcon, LoaderIcon } from '@shared/icons';
@ -10,51 +11,63 @@ import { ArticleNote, NoteWrapper } from '@shared/notes';
import { TitleBar } from '@shared/titleBar';
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 }) {
const { db } = useStorage();
const { ndk, relayUrls, fetcher } = useNDK();
const { status, data, hasNextPage, isFetchingNextPage, fetchNextPage } =
useInfiniteQuery({
queryKey: ['local-articles'],
queryFn: async ({ pageParam = 0 }) => {
return await db.getAllEventsByKinds([NDKKind.Article], 20, pageParam);
initialPageParam: 0,
queryFn: async ({
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(
() => (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);
return (
<NoteWrapper key={event.id} event={event}>
<ArticleNote />
</NoteWrapper>
);
},
const allEvents = useMemo(
() => (data ? data.pages.flatMap((page) => page) : []),
[data]
);
return (
<WidgetWrapper>
<TitleBar id={params.id} title={params.title} />
<div className="flex-1">
{status === 'loading' ? (
<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 article...
</p>
</div>
<VList className="flex-1">
{status === 'pending' ? (
<div className="flex h-full w-full items-center justify-center">
<LoaderIcon className="h-5 w-5 animate-spin" />
</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 flex-col items-center gap-4">
<img src="/ghost.png" alt="empty feeds" className="h-16 w-16" />
@ -69,38 +82,32 @@ export function LocalArticlesWidget({ params }: { params: Widget }) {
</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>
allEvents.map((item) => (
<NoteWrapper key={item.id} event={item}>
<ArticleNote />
</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>
);
}

View File

@ -3,140 +3,132 @@ import { useInfiniteQuery } from '@tanstack/react-query';
import { useCallback, useMemo } from 'react';
import { VList } from 'virtua';
import { useStorage } from '@libs/storage/provider';
import { useNDK } from '@libs/ndk/provider';
import { ArrowRightCircleIcon, LoaderIcon } from '@shared/icons';
import {
ArticleNote,
FileNote,
MemoizedArticleNote,
MemoizedFileNote,
MemoizedRepost,
MemoizedTextNote,
NoteSkeleton,
NoteWrapper,
Repost,
TextNote,
UnknownNote,
} from '@shared/notes';
import { TitleBar } from '@shared/titleBar';
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 }) {
const { db } = useStorage();
const { relayUrls, ndk, fetcher } = useNDK();
const { status, data, hasNextPage, isFetchingNextPage, fetchNextPage } =
useInfiniteQuery({
queryKey: ['group-feeds-' + params.id],
queryFn: async ({ pageParam = 0 }) => {
const authors = JSON.parse(params.content);
return await db.getAllEventsByAuthors(authors, 20, pageParam);
initialPageParam: 0,
queryFn: async ({
signal,
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(
() => (data ? data.pages.flatMap((d: { data: DBEvent[] }) => d.data) : []),
const allEvents = useMemo(
() => (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);
switch (event.kind) {
case NDKKind.Text:
return (
<NoteWrapper
key={dbEvent.id + dbEvent.root_id + dbEvent.reply_id}
event={event}
root={dbEvent.root_id}
reply={dbEvent.reply_id}
>
<TextNote />
</NoteWrapper>
);
case NDKKind.Repost:
return <Repost key={dbEvent.id} event={event} />;
case 1063:
return (
<NoteWrapper key={dbEvent.id} event={event}>
<FileNote />
</NoteWrapper>
);
case NDKKind.Article:
return (
<NoteWrapper key={dbEvent.id} event={event}>
<ArticleNote />
</NoteWrapper>
);
default:
return (
<NoteWrapper key={dbEvent.id} event={event}>
<UnknownNote />
</NoteWrapper>
);
}
},
[dbEvents]
);
const renderItem = useCallback((event: NDKEvent) => {
switch (event.kind) {
case NDKKind.Text:
return (
<NoteWrapper key={event.id} event={event}>
<MemoizedTextNote />
</NoteWrapper>
);
case NDKKind.Repost:
return <MemoizedRepost key={event.id} event={event} />;
case 1063:
return (
<NoteWrapper key={event.id} event={event}>
<MemoizedFileNote />
</NoteWrapper>
);
case NDKKind.Article:
return (
<NoteWrapper key={event.id} event={event}>
<MemoizedArticleNote />
</NoteWrapper>
);
default:
return (
<NoteWrapper key={event.id} event={event}>
<UnknownNote />
</NoteWrapper>
);
}
}, []);
return (
<WidgetWrapper>
<TitleBar id={params.id} title={params.title} />
<div className="flex-1">
{status === 'loading' ? (
<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 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>
<VList className="flex-1">
{status === 'pending' ? (
<div className="px-3 py-1.5">
<div className="rounded-xl bg-neutral-100 px-3 py-3 dark:bg-neutral-900">
<NoteSkeleton />
</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>
allEvents.map((item) => renderItem(item))
)}
</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>
);
}

View File

@ -1,8 +1,9 @@
import { NDKEvent } from '@nostr-dev-kit/ndk';
import { useInfiniteQuery } from '@tanstack/react-query';
import { useCallback, useMemo } from 'react';
import { useMemo } from 'react';
import { VList } from 'virtua';
import { useNDK } from '@libs/ndk/provider';
import { useStorage } from '@libs/storage/provider';
import { ArrowRightCircleIcon, LoaderIcon } from '@shared/icons';
@ -10,57 +11,69 @@ import { FileNote, NoteWrapper } from '@shared/notes';
import { TitleBar } from '@shared/titleBar';
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 }) {
const { db } = useStorage();
const { ndk, relayUrls, fetcher } = useNDK();
const { status, data, hasNextPage, isFetchingNextPage, fetchNextPage } =
useInfiniteQuery({
queryKey: ['local-file-sharing'],
queryFn: async ({ pageParam = 0 }) => {
return await db.getAllEventsByKinds([1063], 20, pageParam);
queryKey: ['local-files'],
initialPageParam: 0,
queryFn: async ({
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(
() => (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);
return (
<NoteWrapper key={event.id} event={event}>
<FileNote />
</NoteWrapper>
);
},
const allEvents = useMemo(
() => (data ? data.pages.flatMap((page) => page) : []),
[data]
);
return (
<WidgetWrapper>
<TitleBar id={params.id} title={params.title} />
<div className="flex-1">
{status === 'loading' ? (
<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 file sharing event...
</p>
</div>
<VList className="flex-1">
{status === 'pending' ? (
<div className="flex h-full w-full items-center justify-center">
<LoaderIcon className="h-5 w-5 animate-spin" />
</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 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 file sharing events.
Oops, it looks like there are no files.
</h3>
<p className="text-neutral-500 dark:text-neutral-400">
You can close this widget
@ -69,38 +82,32 @@ export function LocalFilesWidget({ params }: { params: Widget }) {
</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>
allEvents.map((item) => (
<NoteWrapper key={item.id} event={item}>
<FileNote />
</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>
);
}

View File

@ -1,141 +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],
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}
root={dbEvent.root_id}
reply={dbEvent.reply_id}
>
<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 === 'loading' ? (
<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

@ -1,183 +0,0 @@
import { NDKEvent, NDKFilter, NDKKind } from '@nostr-dev-kit/ndk';
import { useInfiniteQuery } from '@tanstack/react-query';
import { useCallback, useEffect, useMemo } from 'react';
import { VList } from 'virtua';
import { useStorage } from '@libs/storage/provider';
import { ArrowRightCircleIcon, ArrowRightIcon, LoaderIcon } from '@shared/icons';
import {
MemoizedArticleNote,
MemoizedFileNote,
MemoizedRepost,
MemoizedTextNote,
NoteWrapper,
UnknownNote,
} from '@shared/notes';
import { NoteSkeleton } from '@shared/notes/skeleton';
import { TitleBar } from '@shared/titleBar';
import { EventLoader, WidgetWrapper } from '@shared/widgets';
import { WidgetKinds, useWidgets } from '@stores/widgets';
import { useNostr } from '@utils/hooks/useNostr';
import { DBEvent } from '@utils/types';
export function LocalNetworkWidget() {
const { sub } = useNostr();
const { db } = useStorage();
const { status, data, hasNextPage, isFetchingNextPage, fetchNextPage } =
useInfiniteQuery({
queryKey: ['local-network-widget'],
queryFn: async ({ pageParam = 0 }) => {
return await db.getAllEvents(20, pageParam);
},
getNextPageParam: (lastPage) => lastPage.nextCursor,
});
const setWidget = useWidgets((state) => state.setWidget);
const isFetched = useWidgets((state) => state.isFetched);
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}
root={dbEvent.root_id}
reply={dbEvent.reply_id}
>
<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]
);
const openTrendingWidgets = async () => {
setWidget(db, {
kind: WidgetKinds.nostrBand.trendingAccounts,
title: 'Trending Accounts',
content: '',
});
};
// subscribe for new event
// sub will be managed by lru-cache
useEffect(() => {
if (db.account && db.account.circles.length > 0 && dbEvents.length > 0) {
const filter: NDKFilter = {
kinds: [NDKKind.Text, NDKKind.Repost],
authors: db.account.circles,
since: Math.floor(Date.now() / 1000),
};
sub(filter, async (event) => {
await db.createEvent(event);
});
}
}, [data]);
if (db.account.circles.length < 1) {
return (
<WidgetWrapper>
<div className="flex h-full w-full items-center justify-center">
<div className="px-8 text-center">
<p className="mb-2 text-3xl">👋</p>
<h1 className="text-lg font-semibold">You have not follow anyone yet</h1>
<h5 className="text-sm text-neutral-600 dark:text-neutral-400">
If you are new to Nostr, you can click button below to open trending users
and start follow some of theme
</h5>
<button
type="button"
onClick={() => openTrendingWidgets()}
className="mt-4 inline-flex h-9 w-max items-center justify-center gap-2 rounded-lg bg-blue-500 px-3 font-semibold text-white hover:bg-blue-600"
>
Open trending
<ArrowRightIcon className="h-4 w-4" />
</button>
</div>
</div>
</WidgetWrapper>
);
}
return (
<WidgetWrapper>
<TitleBar id="9999" />
<div className="flex-1">
{status === 'loading' ? (
<div className="px-3 py-1.5">
<div className="rounded-xl bg-neutral-100 px-3 py-3 dark:bg-neutral-900">
<NoteSkeleton />
</div>
</div>
) : dbEvents.length === 0 ? (
<EventLoader firstTime={true} />
) : (
<VList className="h-full" style={{ contentVisibility: 'auto' }}>
{!isFetched ? <EventLoader firstTime={false} /> : null}
{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" />
</>
) : hasNextPage ? (
<>
<ArrowRightCircleIcon className="h-5 w-5" />
<span>Load more</span>
</>
) : (
<>
<ArrowRightCircleIcon className="h-5 w-5" />
<span>Nothing more to load</span>
</>
)}
</button>
) : null}
</div>
<div className="h-14" />
</VList>
)}
</div>
</WidgetWrapper>
);
}

View File

@ -1,72 +0,0 @@
import { NDKEvent } from '@nostr-dev-kit/ndk';
import { useCallback, useEffect } from 'react';
import { VList } from 'virtua';
import { useStorage } from '@libs/storage/provider';
import { LoaderIcon } from '@shared/icons';
import { NotifyNote } from '@shared/notification/notifyNote';
import { TitleBar } from '@shared/titleBar';
import { WidgetWrapper } from '@shared/widgets';
import { useActivities } from '@stores/activities';
import { useNostr } from '@utils/hooks/useNostr';
import { Widget } from '@utils/types';
export function LocalNotificationWidget({ params }: { params: Widget }) {
const { db } = useStorage();
const { getAllActivities } = useNostr();
const [activities, setActivities] = useActivities((state) => [
state.activities,
state.setActivities,
]);
const renderEvent = useCallback(
(event: NDKEvent) => {
if (event.pubkey === db.account.pubkey) return null;
return <NotifyNote key={event.id} event={event} />;
},
[activities]
);
useEffect(() => {
async function getActivities() {
const events = await getAllActivities(48);
setActivities(events);
}
getActivities();
}, []);
return (
<WidgetWrapper>
<TitleBar id={params.id} title={params.title} />
<div className="flex-1">
{!activities ? (
<div className="flex h-full w-full items-center justify-center">
<div className="flex flex-col items-center gap-1.5">
<LoaderIcon className="h-5 w-5 animate-spin text-neutral-900 dark:text-neutral-100" />
<p className="text-sm font-medium text-neutral-600 dark:text-neutral-400">
Loading...
</p>
</div>
</div>
) : activities.length < 1 ? (
<div className="flex h-full w-full flex-col items-center justify-center">
<p className="mb-1 text-4xl">🎉</p>
<p className="text-center font-medium text-neutral-600 dark:text-neutral-400">
Hmm! Nothing new yet.
</p>
</div>
) : (
<VList className="h-full" style={{ contentVisibility: 'auto' }}>
{activities.map((event) => renderEvent(event))}
<div className="h-14" />
</VList>
)}
</div>
</WidgetWrapper>
);
}

View File

@ -43,7 +43,7 @@ export function LocalThreadWidget({ params }: { params: Widget }) {
<WidgetWrapper>
<TitleBar id={params.id} title={params.title} />
<WVList className="flex-1 overflow-y-auto px-3">
{status === 'loading' ? (
{status === 'pending' ? (
<div className="flex h-16 items-center justify-center rounded-xl bg-neutral-100 px-3 py-3 dark:bg-neutral-900">
<LoaderIcon className="h-5 w-5 animate-spin" />
</div>

View File

@ -23,25 +23,39 @@ import { Widget } from '@utils/types';
export function LocalUserWidget({ params }: { params: Widget }) {
const { ndk } = useNDK();
const { status, data } = useQuery(
['user-posts', params.content],
async () => {
const { status, data } = useQuery({
queryKey: ['user-posts', params.content],
queryFn: async () => {
const rootIds = new Set();
const dedupQueue = new Set();
const events = await ndk.fetchEvents({
// @ts-expect-error, NDK not support file metadata yet
kinds: [NDKKind.Text, NDKKind.Repost, 1063, NDKKind.Article],
authors: [params.content],
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,
refetchOnMount: false,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
}
);
staleTime: Infinity,
refetchOnMount: false,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
});
// render event match event kind
const renderItem = useCallback(
@ -90,7 +104,7 @@ export function LocalUserWidget({ params }: { params: Widget }) {
Latest posts
</h3>
<div className="flex h-full w-full flex-col justify-between gap-1.5 pb-10">
{status === 'loading' ? (
{status === 'pending' ? (
<div className="px-3 py-1.5">
<div className="rounded-xl bg-neutral-100 px-3 py-3 dark:bg-neutral-900">
<NoteSkeleton />

View File

@ -0,0 +1,176 @@
import { NDKEvent, NDKFilter, NDKKind } from '@nostr-dev-kit/ndk';
import { useInfiniteQuery, useQueryClient } from '@tanstack/react-query';
import { useCallback, useEffect, useMemo } from 'react';
import { VList } from 'virtua';
import { useNDK } from '@libs/ndk/provider';
import { useStorage } from '@libs/storage/provider';
import { ArrowRightCircleIcon, LoaderIcon } from '@shared/icons';
import {
MemoizedArticleNote,
MemoizedFileNote,
MemoizedRepost,
MemoizedTextNote,
NoteSkeleton,
NoteWrapper,
UnknownNote,
} from '@shared/notes';
import { TitleBar } from '@shared/titleBar';
import { WidgetWrapper } from '@shared/widgets';
import { useNostr } from '@utils/hooks/useNostr';
export function NewsfeedWidget() {
const queryClient = useQueryClient();
const { db } = useStorage();
const { sub } = useNostr();
const { relayUrls, ndk, fetcher } = useNDK();
const { status, data, hasNextPage, isFetchingNextPage, fetchNextPage } =
useInfiniteQuery({
queryKey: ['newsfeed'],
initialPageParam: 0,
queryFn: async ({
signal,
pageParam,
}: {
signal: AbortSignal;
pageParam: number;
}) => {
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,
},
50,
{ asOf: pageParam === 0 ? undefined : pageParam, abortSignal: signal }
);
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);
},
getNextPageParam: (lastPage) => {
const lastEvent = lastPage.at(-1);
if (!lastEvent) return;
return lastEvent.created_at - 1;
},
});
const allEvents = useMemo(
() => (data ? data.pages.flatMap((page) => page) : []),
[data]
);
const renderItem = useCallback((event: NDKEvent) => {
switch (event.kind) {
case NDKKind.Text:
return (
<NoteWrapper key={event.id} event={event}>
<MemoizedTextNote />
</NoteWrapper>
);
case NDKKind.Repost:
return <MemoizedRepost key={event.id} event={event} />;
case 1063:
return (
<NoteWrapper key={event.id} event={event}>
<MemoizedFileNote />
</NoteWrapper>
);
case NDKKind.Article:
return (
<NoteWrapper key={event.id} event={event}>
<MemoizedArticleNote />
</NoteWrapper>
);
default:
return (
<NoteWrapper key={event.id} event={event}>
<UnknownNote />
</NoteWrapper>
);
}
}, []);
useEffect(() => {
if (status === 'success' && db.account && db.account.circles.length > 0) {
queryClient.fetchQuery({ queryKey: ['notification'] });
const filter: NDKFilter = {
kinds: [NDKKind.Text, NDKKind.Repost],
authors: db.account.circles,
since: Math.floor(Date.now() / 1000),
};
sub(
filter,
async (event) => {
queryClient.setQueryData(
['newsfeed'],
(prev: { pageParams: number; pages: Array<NDKEvent[]> }) => ({
...prev,
pages: [[event], ...prev.pages],
})
);
},
false,
'newsfeed'
);
}
}, [status]);
return (
<WidgetWrapper>
<TitleBar id="9999" isLive />
<VList className="flex-1">
{status === 'pending' ? (
<div className="px-3 py-1.5">
<div className="rounded-xl bg-neutral-100 px-3 py-3 dark:bg-neutral-900">
<NoteSkeleton />
</div>
</div>
) : (
allEvents.map((item) => renderItem(item))
)}
<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>
);
}

View File

@ -13,9 +13,9 @@ interface Response {
}
export function TrendingAccountsWidget({ params }: { params: Widget }) {
const { status, data } = useQuery(
['trending-profiles-widget'],
async () => {
const { status, data } = useQuery({
queryKey: ['trending-profiles-widget'],
queryFn: async () => {
const res = await fetch('https://api.nostr.band/v0/trending/profiles');
if (!res.ok) {
throw new Error('Error');
@ -24,19 +24,17 @@ export function TrendingAccountsWidget({ params }: { params: Widget }) {
if (!json.profiles) return [];
return json.profiles;
},
{
refetchOnMount: false,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
staleTime: Infinity,
}
);
refetchOnMount: false,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
staleTime: Infinity,
});
return (
<WidgetWrapper>
<TitleBar id={params.id} title="Trending Accounts" />
<div className="flex-1">
{status === 'loading' ? (
{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" />

View File

@ -14,9 +14,9 @@ interface Response {
}
export function TrendingNotesWidget({ params }: { params: Widget }) {
const { status, data } = useQuery(
['trending-notes-widget'],
async () => {
const { status, data } = useQuery({
queryKey: ['trending-notes-widget'],
queryFn: async () => {
const res = await fetch('https://api.nostr.band/v0/trending/notes');
if (!res.ok) {
throw new Error('failed to fecht trending notes');
@ -25,19 +25,17 @@ export function TrendingNotesWidget({ params }: { params: Widget }) {
if (!json.notes) return null;
return json.notes;
},
{
refetchOnMount: false,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
staleTime: Infinity,
}
);
refetchOnMount: false,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
staleTime: Infinity,
});
return (
<WidgetWrapper>
<TitleBar id={params.id} title="Trending Notes" />
<div className="flex-1">
{status === 'loading' ? (
{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" />

View File

@ -3,6 +3,7 @@ import { useQuery } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import { useNDK } from '@libs/ndk/provider';
import { useStorage } from '@libs/storage/provider';
import { FollowIcon, UnfollowIcon } from '@shared/icons';
@ -18,20 +19,18 @@ export interface Profile {
export function NostrBandUserProfile({ data }: { data: Profile }) {
const { db } = useStorage();
const { ndk } = useStorage();
const { status, data: userStats } = useQuery(
['user-stats', data.pubkey],
async () => {
const { ndk } = useNDK();
const { status, data: userStats } = useQuery({
queryKey: ['user-stats', data.pubkey],
queryFn: async () => {
const res = await fetch(`https://api.nostr.band/v0/stats/profile/${data.pubkey}`);
return res.json();
},
{
refetchOnMount: false,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
staleTime: Infinity,
}
);
refetchOnMount: false,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
staleTime: Infinity,
});
const embedProfile = data.profile ? JSON.parse(data.profile.content) : null;
const profile = embedProfile;
@ -137,7 +136,7 @@ export function NostrBandUserProfile({ data }: { data: Profile }) {
</p>
</div>
<div className="mt-8">
{status === 'loading' ? (
{status === 'pending' ? (
<p>Loading...</p>
) : (
<div className="flex w-full items-center gap-8">

View File

@ -0,0 +1,177 @@
import { NDKEvent, NDKKind } from '@nostr-dev-kit/ndk';
import { useInfiniteQuery, useQueryClient } from '@tanstack/react-query';
import { useCallback, useEffect, useMemo } from 'react';
import { VList } from 'virtua';
import { useNDK } from '@libs/ndk/provider';
import { useStorage } from '@libs/storage/provider';
import { ArrowRightCircleIcon, LoaderIcon } from '@shared/icons';
import { NoteSkeleton } from '@shared/notes';
import { NotifyNote } from '@shared/notification/notifyNote';
import { TitleBar } from '@shared/titleBar';
import { WidgetWrapper } from '@shared/widgets';
import { useNostr } from '@utils/hooks/useNostr';
import { sendNativeNotification } from '@utils/notification';
export function NotificationWidget() {
const queryClient = useQueryClient();
const { db } = useStorage();
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 ndkEvents = events.map((event) => {
return new NDKEvent(ndk, event);
});
return ndkEvents.sort((a, b) => b.created_at - a.created_at);
},
getNextPageParam: (lastPage) => {
const lastEvent = lastPage.at(-1);
if (!lastEvent) return;
return lastEvent.created_at - 1;
},
enabled: false,
});
const allEvents = useMemo(
() => (data ? data.pages.flatMap((page) => page) : []),
[data]
);
const renderEvent = useCallback((event: NDKEvent) => {
if (event.pubkey === db.account.pubkey) return null;
return <NotifyNote key={event.id} event={event} />;
}, []);
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'],
(prev: { pageParams: number; pages: Array<NDKEvent[]> }) => ({
...prev,
pages: [[event], ...prev.pages],
})
);
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 (
<WidgetWrapper>
<TitleBar id="9998" title="Notification" isLive />
<VList className="flex-1">
{status === 'pending' ? (
<div className="px-3 py-1.5">
<div className="rounded-xl bg-neutral-100 px-3 py-3 dark:bg-neutral-900">
<NoteSkeleton />
</div>
</div>
) : allEvents.length < 1 ? (
<div className="flex h-full w-full flex-col items-center justify-center">
<p className="mb-1 text-4xl">🎉</p>
<p className="text-center font-medium text-neutral-600 dark:text-neutral-400">
Hmm! Nothing new yet.
</p>
</div>
) : (
allEvents.map((event) => renderEvent(event))
)}
<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>
);
}

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 { 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';
export function XfeedsWidget({ params }: { params: Widget }) {
const { db } = useStorage();
const { addWidget, removeWidget } = useWidget();
const [setWidget, removeWidget] = useWidgets((state) => [
state.setWidget,
state.removeWidget,
]);
const [title, setTitle] = useState<string>('');
const [groups, setGroups] = useState<Array<string>>([]);
@ -28,17 +26,17 @@ export function XfeedsWidget({ params }: { params: Widget }) {
};
const cancel = () => {
removeWidget(db, params.id);
removeWidget.mutate(params.id);
};
const submit = async () => {
setWidget(db, {
addWidget.mutate({
kind: WidgetKinds.local.feeds,
title: title || 'Group',
content: JSON.stringify(groups),
});
// remove temp widget
removeWidget(db, params.id);
removeWidget.mutate(params.id);
};
return (

View File

@ -1,11 +1,10 @@
import { Resolver, useForm } from 'react-hook-form';
import { useStorage } from '@libs/storage/provider';
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';
type FormValues = {
@ -27,12 +26,7 @@ const resolver: Resolver<FormValues> = async (values) => {
};
export function XhashtagWidget({ params }: { params: Widget }) {
const [setWidget, removeWidget] = useWidgets((state) => [
state.setWidget,
state.removeWidget,
]);
const { db } = useStorage();
const { addWidget, removeWidget } = useWidget();
const {
register,
setError,
@ -41,18 +35,18 @@ export function XhashtagWidget({ params }: { params: Widget }) {
} = useForm<FormValues>({ resolver });
const cancel = () => {
removeWidget(db, params.id);
removeWidget.mutate(params.id);
};
const onSubmit = async (data: FormValues) => {
try {
setWidget(db, {
addWidget.mutate({
kind: WidgetKinds.global.hashtag,
title: data.hashtag,
content: data.hashtag.replace('#', ''),
});
// remove temp widget
removeWidget(db, params.id);
removeWidget.mutate(params.id);
} catch (e) {
setError('hashtag', {
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 = [
'wss://relay.damus.io',
'wss://relay.primal.net',
@ -5,3 +7,104 @@ export const FULL_RELAYS = [
'wss://relay.nostr.band/all',
'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: 'Local',
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,181 +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

@ -3,18 +3,16 @@ import { useQuery } from '@tanstack/react-query';
import { AddressPointer } from 'nostr-tools/lib/types/nip19';
import { useNDK } from '@libs/ndk/provider';
import { useStorage } from '@libs/storage/provider';
export function useEvent(
id: undefined | string,
naddr?: undefined | AddressPointer,
embed?: undefined | string
) {
const { db } = useStorage();
const { ndk } = useNDK();
const { status, data } = useQuery(
['event', id],
async () => {
const { status, data } = useQuery({
queryKey: ['event', id],
queryFn: async () => {
// return event refer from naddr
if (naddr) {
const rEvents = await ndk.fetchEvents({
@ -33,23 +31,17 @@ export function useEvent(
return event;
}
// get event from db
const dbEvent = await db.getEventByID(id);
if (dbEvent) return dbEvent;
// get event from relay if event in db not present
// get event from relay
const event = await ndk.fetchEvent(id);
if (!event) return Promise.reject(new Error('event not found'));
await db.createEvent(event);
return event;
},
{
enabled: !!ndk,
refetchOnWindowFocus: false,
}
);
refetchOnWindowFocus: false,
refetchOnMount: false,
refetchOnReconnect: false,
staleTime: Infinity,
});
return { status, data };
}

View File

@ -1,4 +1,7 @@
import { NDKEvent, NDKFilter, NDKKind, NDKSubscription } from '@nostr-dev-kit/ndk';
import { open } from '@tauri-apps/plugin-dialog';
import { readBinaryFile } from '@tauri-apps/plugin-fs';
import { fetch } from '@tauri-apps/plugin-http';
import { LRUCache } from 'lru-cache';
import { NostrEventExt } from 'nostr-fetch';
import { useMemo } from 'react';
@ -26,11 +29,12 @@ export function useNostr() {
const sub = async (
filter: NDKFilter,
callback: (event: NDKEvent) => void,
groupable?: boolean
groupable?: boolean,
subKey?: string
) => {
if (!ndk) throw new Error('NDK instance not found');
const key = JSON.stringify(filter);
const key = subKey ?? JSON.stringify(filter);
if (!subManager.get(key)) {
const subEvent = ndk.subscribe(filter, {
closeOnEose: false,
@ -183,10 +187,9 @@ export function useNostr() {
{ since: since }
)) as unknown as NDKEvent[];
return { status: 'ok', message: 'fetch completed', data: events };
return events;
} catch (e) {
console.error('prefetch events failed, error: ', e);
return { status: 'failed', message: e };
}
};
@ -239,6 +242,41 @@ export function useNostr() {
return res;
};
const upload = async (ext: string[] = []) => {
const defaultExts = ['png', 'jpeg', 'jpg', 'gif'].concat(ext);
const selected = await open({
multiple: false,
filters: [
{
name: 'Image',
extensions: defaultExts,
},
],
});
if (!selected) return null;
const file = await readBinaryFile(selected.path);
const blob = new Blob([file]);
const data = new FormData();
data.append('fileToUpload', blob);
data.append('submit', 'Upload Image');
const res = await fetch('https://nostr.build/api/v2/upload/files', {
method: 'POST',
body: data,
});
if (!res.ok) return null;
const json = await res.json();
const content = json.data[0];
return content.url as string;
};
return {
sub,
getAllNIP04Chats,
@ -250,5 +288,6 @@ export function useNostr() {
fetchNIP04Messages,
fetchAllReplies,
createZap,
upload,
};
}

View File

@ -1,25 +1,23 @@
import { useQuery } from '@tanstack/react-query';
import { invoke } from '@tauri-apps/api';
import { invoke } from '@tauri-apps/api/primitives';
import { Opengraph } from '@utils/types';
export function useOpenGraph(url: string) {
const { status, data, error } = useQuery(
['opg', url],
async () => {
const { status, data, error } = useQuery({
queryKey: ['opg', url],
queryFn: async () => {
const res: Opengraph = await invoke('opengraph', { url });
if (!res) {
throw new Error('fetch preview failed');
}
return res;
},
{
staleTime: Infinity,
refetchOnWindowFocus: false,
refetchOnMount: false,
refetchOnReconnect: false,
}
);
staleTime: Infinity,
refetchOnWindowFocus: false,
refetchOnMount: false,
refetchOnReconnect: false,
});
return {
status,

View File

@ -9,27 +9,24 @@ export function useProfile(pubkey: string, embed?: string) {
status,
data: user,
error,
} = useQuery(
['user', pubkey],
async () => {
} = useQuery({
queryKey: ['user', pubkey],
queryFn: async () => {
if (embed) {
const profile: NDKUserProfile = JSON.parse(embed);
return profile;
}
const cleanPubkey = pubkey.replace('-', '');
const cleanPubkey = pubkey.replace(/[^a-zA-Z0-9]/g, '');
const user = ndk.getUser({ hexpubkey: cleanPubkey });
return await user.fetchProfile();
},
{
enabled: !!ndk,
staleTime: Infinity,
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
retry: 2,
}
);
staleTime: Infinity,
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
});
return { status, user, error };
}

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 };
}

View File

@ -1,5 +1,5 @@
export function fileType(url: string) {
if (url.match(/\.(jpg|jpeg|gif|png|webp|avif)$/)) {
if (url.match(/\.(jpg|jpeg|gif|png|webp|avif|tiff)$/)) {
return 'image';
}

View File

@ -1,5 +1,9 @@
import { nip19 } from 'nostr-tools';
import { AddressPointer, EventPointer, ProfilePointer } from 'nostr-tools/lib/nip19';
import {
AddressPointer,
EventPointer,
ProfilePointer,
} from 'nostr-tools/lib/types/nip19';
import { RichContent } from '@utils/types';
@ -19,74 +23,95 @@ function isURL(string: string) {
}
}
export function parser(eventContent: string) {
if (!eventContent) return '';
export function parser(content: string) {
const richContent: RichContent = {
parsed: null,
images: [],
videos: [],
links: [],
notes: [],
};
try {
const content: RichContent = {
parsed: null,
images: [],
videos: [],
links: [],
notes: [],
};
const parse = eventContent.split(/\s/gm).map((word) => {
const parsed = content
.trim()
.split(/(\s+)/)
.map((word) => {
// url
if (isURL(word)) {
const url = new URL(word);
url.search = '';
if (url.pathname.match(/\.(jpg|jpeg|gif|png|webp|avif)$/)) {
if (url.pathname.match(/\.(jpg|jpeg|gif|png|webp|avif|tiff)$/)) {
// image url
content.images.push(word);
richContent.images.push(word);
// remove url from original content
return word.replace(word, '');
}
if (url.pathname.match(/\.(mp4|mov|webm|wmv|flv|mts|avi|ogv|mkv|mp3|m3u8)$/)) {
// video
content.videos.push(word);
// video url
richContent.videos.push(word);
// remove url from original content
return word.replace(word, '');
}
content.links.push(url.toString());
// normal url
if (richContent.links.length < 1) {
richContent.links.push(url.toString());
}
}
// hashtag
if (word.startsWith('#') && word.length > 1) {
return word.replace(word, `~tag-${word}~`);
return word.replace(word, `<Hashtag tag='${word}' />`);
}
// boost
if (word.startsWith('$prism') && word.length > 1) {
return word.replace(word, `~boost-${word}~`);
return word.replace(word, `<Boost boost='${word}' />`);
}
// nostr account references (depreciated)
if (word.startsWith('@npub1')) {
const npub = word.replace('@', '').replace(/[^a-zA-Z0-9 ]/g, '');
return word.replace(word, `~pub-${nip19.decode(npub).data}~`);
return word.replace(
word,
`<MentionUser pubkey='${nip19.decode(npub).data as string}' />`
);
}
// nostr account references
if (word.startsWith('nostr:npub1') || word.startsWith('npub1')) {
const npub = word.replace('nostr:', '').replace(/[^a-zA-Z0-9 ]/g, '');
return word.replace(word, `~pub-${nip19.decode(npub).data}~`);
return word.replace(
word,
`<MentionUser pubkey='${nip19.decode(npub).data as string}' />`
);
}
// nostr profile references
if (word.startsWith('nostr:nprofile1') || word.startsWith('nprofile1')) {
const nprofile = word.replace('nostr:', '').replace(/[^a-zA-Z0-9 ]/g, '');
const decoded = nip19.decode(nprofile).data as ProfilePointer;
return word.replace(word, `~pub-${decoded.pubkey}~`);
return word.replace(word, `<MentionUser pubkey='${decoded.pubkey}' />`);
}
// nostr account references
// nostr address references
if (word.startsWith('nostr:naddr1') || word.startsWith('naddr1')) {
const naddr = word.replace('nostr:', '').replace(/[^a-zA-Z0-9 ]/g, '');
const decoded = nip19.decode(naddr).data as AddressPointer;
return word.replace(word, `<MentionUser pubkey='${decoded.pubkey}' />`);
}
// lightning invoice
if (word.startsWith('lnbc') && word.length > 60) {
return word.replace(word, `<Invoice invoice='${word}' />`);
}
// nostr note references
if (word.startsWith('nostr:note1') || word.startsWith('note1')) {
const note = word.replace('nostr:', '').replace(/[^a-zA-Z0-9 ]/g, '');
content.notes.push(nip19.decode(note).data as string);
richContent.notes.push(nip19.decode(note).data as string);
return word.replace(word, '');
}
@ -94,31 +119,14 @@ export function parser(eventContent: string) {
if (word.startsWith('nostr:nevent1') || word.startsWith('nevent1')) {
const nevent = word.replace('nostr:', '').replace(/[^a-zA-Z0-9 ]/g, '');
const decoded = nip19.decode(nevent).data as EventPointer;
content.notes.push(decoded.id);
richContent.notes.push(decoded.id);
return word.replace(word, '');
}
// nostr address references
if (word.startsWith('nostr:naddr1') || word.startsWith('naddr1')) {
const naddr = word.replace('nostr:', '').replace(/[^a-zA-Z0-9 ]/g, '');
const decoded = nip19.decode(naddr).data as AddressPointer;
return word.replace(word, `~pub-${decoded.pubkey}~`);
}
// lightning invoice
if (word.startsWith('lnbc') && word.length > 60) {
return word.replace(word, `~lnbc-${word}~`);
}
// normal word
return word;
});
// update content with parsed version
content.parsed = parse.join(' ');
return content;
} catch (e) {
console.error('cannot parse content, error: ', e);
}
// update content with parsed version
richContent.parsed = parsed.join(' ').trim();
return richContent;
}

24
src/utils/types.d.ts vendored
View File

@ -114,3 +114,27 @@ export interface Resources {
title: string;
data: Array<Resource>;
}
export interface NDKCacheUser {
pubkey: string;
profile: string | NDKUserProfile;
createdAt: number;
}
export interface NDKCacheEvent {
id: string;
pubkey: string;
content: string;
kind: number;
createdAt: number;
relay: string;
event: string;
}
export interface NDKCacheEventTag {
id: string;
eventId: string;
tag: string;
value: string;
tagValue: string;
}

View File

@ -1,10 +1,14 @@
import react from '@vitejs/plugin-react-swc';
//import million from 'million/compiler';
import million from 'million/compiler';
import { defineConfig } from 'vite';
import viteTsconfigPaths from 'vite-tsconfig-paths';
export default defineConfig({
plugins: [/*million.vite({ auto: true, mute: true }),*/ react(), viteTsconfigPaths()],
plugins: [
million.vite({ optimize: false, auto: true, mute: true }),
react(),
viteTsconfigPaths(),
],
envPrefix: ['VITE_', 'TAURI_'],
build: {
target: process.env.TAURI_PLATFORM === 'windows' ? 'chrome105' : 'safari13',