feat: post & reply (#5)

This commit is contained in:
Cody Tseng
2024-11-09 22:28:10 +08:00
committed by GitHub
parent 5b0abcf380
commit 53f9f6240f
25 changed files with 483 additions and 98 deletions

View File

@@ -97,7 +97,7 @@ function preprocess(content: string) {
})
const embeddedNotes: string[] = []
const embeddedNoteRegex = /(nostr:note1[a-z0-9]{58}|nostr:nevent1[a-z0-9]+)/g
const embeddedNoteRegex = /nostr:(note1[a-z0-9]{58}|nevent1[a-z0-9]+|naddr1[a-z0-9]+)/g
;(c.match(embeddedNoteRegex) || []).forEach((note) => {
c = c.replace(note, '').trim()
embeddedNotes.push(note)

View File

@@ -53,7 +53,7 @@ export default function LikeButton({
const targetRelayList = await client.fetchRelayList(event.pubkey)
const reaction = createReactionDraftEvent(event)
await publish(reaction, targetRelayList.read)
await publish(reaction, targetRelayList.read.slice(0, 3))
markNoteAsLiked(event.id)
} catch (error) {
console.error('like failed', error)

View File

@@ -4,7 +4,8 @@ import {
DropdownMenuItem,
DropdownMenuTrigger
} from '@renderer/components/ui/dropdown-menu'
import { Ellipsis } from 'lucide-react'
import { getSharableEventId } from '@renderer/lib/event'
import { Code, Copy, Ellipsis } from 'lucide-react'
import { Event } from 'nostr-tools'
import { useState } from 'react'
import RawEventDialog from './RawEventDialog'
@@ -22,7 +23,22 @@ export default function NoteOptions({ event }: { event: Event }) {
/>
</DropdownMenuTrigger>
<DropdownMenuContent collisionPadding={8}>
<DropdownMenuItem onClick={() => setIsRawEventDialogOpen(true)}>
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
navigator.clipboard.writeText('nostr:' + getSharableEventId(event))
}}
>
<Copy />
copy embedded code
</DropdownMenuItem>
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
setIsRawEventDialogOpen(true)
}}
>
<Code />
raw event
</DropdownMenuItem>
</DropdownMenuContent>

View File

@@ -1,17 +1,26 @@
import { useNostr } from '@renderer/providers/NostrProvider'
import { useNoteStats } from '@renderer/providers/NoteStatsProvider'
import { MessageCircle } from 'lucide-react'
import { Event } from 'nostr-tools'
import { useMemo } from 'react'
import PostDialog from '../PostDialog'
import { formatCount } from './utils'
export default function ReplyButton({ event }: { event: Event }) {
const { noteStatsMap } = useNoteStats()
const { pubkey } = useNostr()
const { replyCount } = useMemo(() => noteStatsMap.get(event.id) ?? {}, [noteStatsMap, event.id])
return (
<div className="flex gap-1 items-center text-muted-foreground">
<MessageCircle size={16} />
<div className="text-xs">{formatCount(replyCount)}</div>
</div>
<PostDialog parentEvent={event}>
<button
className="flex gap-1 items-center text-muted-foreground enabled:hover:text-blue-400"
disabled={!pubkey}
onClick={(e) => e.stopPropagation()}
>
<MessageCircle size={16} />
<div className="text-xs">{formatCount(replyCount)}</div>
</button>
</PostDialog>
)
}

View File

@@ -63,7 +63,7 @@ export default function RepostButton({
const targetRelayList = await client.fetchRelayList(event.pubkey)
const repost = createRepostDraftEvent(event)
await publish(repost, targetRelayList.read)
await publish(repost, targetRelayList.read.slice(0, 3))
markNoteAsReposted(event.id)
} catch (error) {
console.error('repost failed', error)
@@ -97,7 +97,7 @@ export default function RepostButton({
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogCancel onClick={(e) => e.stopPropagation()}>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={repost}>Repost</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>

View File

@@ -0,0 +1,47 @@
import { Button } from '@renderer/components/ui/button'
import { Popover, PopoverContent, PopoverTrigger } from '@renderer/components/ui/popover'
import { extractMentions } from '@renderer/lib/event'
import { useEffect, useState } from 'react'
import UserAvatar from '../UserAvatar'
import Username from '../Username'
import { Event } from 'nostr-tools'
export default function Mentions({
content,
parentEvent
}: {
content: string
parentEvent?: Event
}) {
const [pubkeys, setPubkeys] = useState<string[]>([])
useEffect(() => {
extractMentions(content, parentEvent).then(({ pubkeys }) => setPubkeys(pubkeys))
}, [content])
return (
<Popover>
<PopoverTrigger asChild>
<Button
className="px-3"
variant="ghost"
disabled={pubkeys.length === 0}
onClick={(e) => e.stopPropagation()}
>
Mentions {pubkeys.length > 0 && `(${pubkeys.length})`}
</Button>
</PopoverTrigger>
<PopoverContent className="w-48">
<div className="space-y-2">
<div className="text-sm font-semibold">Mentions:</div>
{pubkeys.map((pubkey, index) => (
<div key={`${pubkey}-${index}`} className="flex gap-1 items-center">
<UserAvatar userId={pubkey} size="small" />
<Username userId={pubkey} className="font-semibold text-sm truncate" />
</div>
))}
</div>
</PopoverContent>
</Popover>
)
}

View File

@@ -0,0 +1,21 @@
import { Card } from '@renderer/components/ui/card'
import dayjs from 'dayjs'
import Content from '../Content'
export default function Preview({ content }: { content: string }) {
return (
<Card className="p-3">
<Content
event={{
content,
kind: 1,
tags: [],
created_at: dayjs().unix(),
id: '',
pubkey: '',
sig: ''
}}
/>
</Card>
)
}

View File

@@ -0,0 +1,131 @@
import { Button } from '@renderer/components/ui/button'
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger
} from '@renderer/components/ui/dialog'
import { ScrollArea } from '@renderer/components/ui/scroll-area'
import { Textarea } from '@renderer/components/ui/textarea'
import { useToast } from '@renderer/hooks/use-toast'
import { createShortTextNoteDraftEvent } from '@renderer/lib/draft-event'
import { useNostr } from '@renderer/providers/NostrProvider'
import client from '@renderer/services/client.service'
import { LoaderCircle } from 'lucide-react'
import { Event } from 'nostr-tools'
import { useState } from 'react'
import UserAvatar from '../UserAvatar'
import Mentions from './Metions'
import Preview from './Preview'
export default function PostDialog({
children,
parentEvent
}: {
children: React.ReactNode
parentEvent?: Event
}) {
const { toast } = useToast()
const { pubkey, publish } = useNostr()
const [open, setOpen] = useState(false)
const [content, setContent] = useState('')
const [posting, setPosting] = useState(false)
const handleTextareaChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
setContent(e.target.value)
}
const post = async (e: React.MouseEvent) => {
e.stopPropagation()
if (!content || !pubkey || posting) {
setOpen(false)
return
}
setPosting(true)
try {
const additionalRelayUrls: string[] = []
if (parentEvent) {
const relayList = await client.fetchRelayList(parentEvent.pubkey)
additionalRelayUrls.push(...relayList.read.slice(0, 5))
}
const draftEvent = await createShortTextNoteDraftEvent(content, parentEvent)
await publish(draftEvent, additionalRelayUrls)
setContent('')
setOpen(false)
} catch (error) {
if (error instanceof AggregateError) {
error.errors.forEach((e) =>
toast({
variant: 'destructive',
title: 'Failed to post',
description: e.message
})
)
} else if (error instanceof Error) {
toast({
variant: 'destructive',
title: 'Failed to post',
description: error.message
})
}
console.error(error)
return
} finally {
setPosting(false)
}
toast({
title: 'Post successful',
description: 'Your post has been published'
})
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>{children}</DialogTrigger>
<DialogContent className="p-0" withoutClose>
<ScrollArea className="px-4 h-full max-h-screen">
<div className="space-y-4 px-2 py-6">
<DialogHeader>
<DialogTitle>
{parentEvent ? (
<div className="flex gap-2 items-center max-w-full">
<div className="shrink-0">Reply to</div>
<UserAvatar userId={parentEvent.pubkey} size="tiny" />
<div className="truncate">{parentEvent.content}</div>
</div>
) : (
'New post'
)}
</DialogTitle>
</DialogHeader>
<Textarea
onChange={handleTextareaChange}
value={content}
placeholder="Write something..."
/>
{content && <Preview content={content} />}
<DialogFooter className="items-center">
<Mentions content={content} parentEvent={parentEvent} />
<Button
variant="secondary"
onClick={(e) => {
e.stopPropagation()
setOpen(false)
}}
>
Cancel
</Button>
<Button type="submit" disabled={!pubkey || posting} onClick={post}>
{posting && <LoaderCircle className="animate-spin" />}
Post
</Button>
</DialogFooter>
</div>
</ScrollArea>
</DialogContent>
</Dialog>
)
}

View File

@@ -4,6 +4,7 @@ import Content from '../Content'
import UserAvatar from '../UserAvatar'
import Username from '../Username'
import LikeButton from '../NoteStats/LikeButton'
import PostDialog from '../PostDialog'
export default function ReplyNote({
event,
@@ -22,15 +23,10 @@ export default function ReplyNote({
>
<UserAvatar userId={event.pubkey} size="small" className="shrink-0" />
<div className="w-full overflow-hidden">
<div className="flex items-end gap-2">
<Username
userId={event.pubkey}
className="text-sm font-semibold text-muted-foreground hover:text-foreground truncate"
/>
<div className="text-xs text-muted-foreground shrink-0 -top-[1px] relative">
{formatTimestamp(event.created_at)}
</div>
</div>
<Username
userId={event.pubkey}
className="text-sm font-semibold text-muted-foreground hover:text-foreground truncate"
/>
{parentEvent && (
<div
className="text-xs text-muted-foreground truncate hover:text-foreground cursor-pointer"
@@ -40,6 +36,12 @@ export default function ReplyNote({
</div>
)}
<Content event={event} size="small" />
<div className="flex gap-2 text-xs">
<div className="text-muted-foreground/60">{formatTimestamp(event.created_at)}</div>
<PostDialog parentEvent={event}>
<div className="text-muted-foreground hover:text-primary cursor-pointer">reply</div>
</PostDialog>
</div>
</div>
<LikeButton event={event} variant="reply" />
</div>
@@ -49,7 +51,7 @@ export default function ReplyNote({
function ParentReplyNote({ event }: { event: Event }) {
return (
<div className="flex space-x-1 items-center text-xs rounded-lg w-fit px-2 bg-muted max-w-full">
<div>reply to</div>
<div className="shrink-0">reply to</div>
<UserAvatar userId={event.pubkey} size="tiny" />
<div className="truncate">{event.content}</div>
</div>

View File

@@ -21,7 +21,7 @@ export default function ReplyNoteList({ event, className }: { event: Event; clas
const loadMore = async () => {
setLoading(true)
const relayList = await client.fetchRelayList(event.pubkey)
const events = await client.fetchEvents(relayList.read, {
const events = await client.fetchEvents(relayList.read.slice(0, 5), {
'#e': [event.id],
kinds: [1],
limit: 100,

View File

@@ -10,7 +10,7 @@ export function Titlebar({
return (
<div
className={cn(
'draggable absolute top-0 w-full h-9 z-50 bg-background/80 backdrop-blur-xl flex items-center font-semibold space-x-1 px-1',
'draggable absolute top-0 w-full h-9 z-50 bg-background/80 backdrop-blur-xl flex items-center font-semibold space-x-1 px-2',
className
)}
>

View File

@@ -19,7 +19,7 @@ const buttonVariants = cva(
titlebar: 'non-draggable hover:bg-accent hover:text-accent-foreground'
},
size: {
default: 'h-8 rounded-lg px-2',
default: 'h-8 rounded-lg px-3',
sm: 'h-8 rounded-lg px-2',
lg: 'h-10 px-4 py-2',
icon: 'h-8 w-8 rounded-full',

View File

@@ -1,8 +1,8 @@
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { X } from "lucide-react"
import * as React from 'react'
import * as DialogPrimitive from '@radix-ui/react-dialog'
import { X } from 'lucide-react'
import { cn } from "@renderer/lib/utils"
import { cn } from '@renderer/lib/utils'
const Dialog = DialogPrimitive.Root
@@ -19,9 +19,10 @@ const DialogOverlay = React.forwardRef<
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className
)}
onClick={(e) => e.stopPropagation()}
{...props}
/>
))
@@ -29,55 +30,46 @@ DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & { withoutClose?: boolean }
>(({ className, children, withoutClose, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
className
)}
onClick={(e) => e.stopPropagation()}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
{!withoutClose && (
<DialogPrimitive.Close
className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground"
onClick={(e) => e.stopPropagation()}
>
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className
)}
{...props}
/>
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn('flex flex-col space-y-1.5 text-center sm:text-left', className)} {...props} />
)
DialogHeader.displayName = "DialogHeader"
DialogHeader.displayName = 'DialogHeader'
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
className={cn('flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2', className)}
{...props}
/>
)
DialogFooter.displayName = "DialogFooter"
DialogFooter.displayName = 'DialogFooter'
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
@@ -85,10 +77,7 @@ const DialogTitle = React.forwardRef<
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
className={cn('text-lg font-semibold leading-none tracking-tight', className)}
{...props}
/>
))
@@ -100,7 +89,7 @@ const DialogDescription = React.forwardRef<
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
))
@@ -116,5 +105,5 @@ export {
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
DialogDescription
}

View File

@@ -61,7 +61,7 @@ const DropdownMenuContent = React.forwardRef<
ref={ref}
sideOffset={sideOffset}
className={cn(
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
'z-50 min-w-[8rem] overflow-hidden rounded-lg border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
className
)}
{...props}
@@ -79,7 +79,7 @@ const DropdownMenuItem = React.forwardRef<
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
'relative flex cursor-pointer select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
'relative flex cursor-pointer select-none items-center gap-2 px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 rounded-md',
inset && 'pl-8',
className
)}

View File

@@ -0,0 +1,23 @@
import * as React from 'react'
import { cn } from '@renderer/lib/utils'
export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, ...props }, ref) => {
return (
<textarea
className={cn(
'flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
className
)}
ref={ref}
{...props}
/>
)
}
)
Textarea.displayName = 'Textarea'
export { Textarea }

View File

@@ -9,25 +9,32 @@ export function useFetchEventById(id?: string) {
const fetchEvent = async () => {
if (!id) return
let filter: Filter | undefined
let filter: Filter = {}
if (/^[0-9a-f]{64}$/.test(id)) {
filter = { ids: [id] }
} else if (/^note1[a-z0-9]{58}$/.test(id)) {
const { data } = nip19.decode(id as `note1${string}`)
filter = { ids: [data] }
} else if (id.startsWith('nevent1')) {
const { data } = nip19.decode(id as `nevent1${string}`)
filter = {}
if (data.id) {
filter.ids = [data.id]
}
if (data.author) {
filter.authors = [data.author]
}
if (data.kind) {
filter.kinds = [data.kind]
} else {
const { type, data } = nip19.decode(id)
switch (type) {
case 'note':
filter = { ids: [data] }
break
case 'nevent':
if (data.id) {
filter.ids = [data.id]
}
break
case 'naddr':
filter = {
authors: [data.pubkey],
kinds: [data.kind],
limit: 1
}
if (data.identifier) {
filter['#d'] = [data.identifier]
}
}
}
if (!filter) return
let event: Event | undefined

View File

@@ -41,14 +41,13 @@ function ProfileButton({ pubkey }: { pubkey: string }) {
return (
<DropdownMenu>
<DropdownMenuTrigger className="relative non-draggable">
<Avatar className="w-6 h-6">
<DropdownMenuTrigger className="non-draggable">
<Avatar className="w-6 h-6 hover:opacity-90">
<AvatarImage src={avatar} />
<AvatarFallback>
<img src={defaultAvatar} />
</AvatarFallback>
</Avatar>
<div className="absolute inset-0 hover:bg-black opacity-0 hover:opacity-20 transition-opacity rounded-full" />
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem onClick={() => push(toProfile(pubkey))}>Profile</DropdownMenuItem>

View File

@@ -0,0 +1,17 @@
import PostDialog from '@renderer/components/PostDialog'
import { Button } from '@renderer/components/ui/button'
import { useNostr } from '@renderer/providers/NostrProvider'
import { PencilLine } from 'lucide-react'
export default function PostButton() {
const { pubkey } = useNostr()
if (!pubkey) return null
return (
<PostDialog>
<Button variant="titlebar" size="titlebar">
<PencilLine />
</Button>
</PostDialog>
)
}

View File

@@ -4,6 +4,7 @@ import { ScrollArea } from '@renderer/components/ui/scroll-area'
import { isMacOS } from '@renderer/lib/platform'
import { forwardRef, useImperativeHandle, useRef } from 'react'
import AccountButton from './AccountButton'
import PostButton from './PostButton'
import RefreshButton from './RefreshButton'
import RelaySettingsPopover from './RelaySettingsPopover'
@@ -47,11 +48,12 @@ export type TPrimaryPageLayoutRef = {
export function PrimaryPageTitlebar({ content }: { content?: React.ReactNode }) {
return (
<Titlebar className={`justify-between ${isMacOS() ? 'pl-20' : ''}`}>
<div className="flex gap-1">
<div className="flex gap-2 items-center">
<AccountButton />
<PostButton />
{content}
</div>
<div className="flex gap-1">
<div className="flex gap-2 items-center">
<RefreshButton />
<RelaySettingsPopover />
</div>

View File

@@ -38,11 +38,11 @@ export function SecondaryPageTitlebar({
}): JSX.Element {
return (
<Titlebar className="justify-between">
<div className="flex items-center gap-1 flex-1 w-0">
<div className="flex items-center gap-2 flex-1 w-0">
<BackButton hide={hideBackButton} />
<div className="truncate">{content}</div>
</div>
<div className="flex-shrink-0">
<div className="flex-shrink-0 flex items-center">
<ThemeToggle />
</div>
</Titlebar>

View File

@@ -1,7 +1,7 @@
import { TDraftEvent } from '@common/types'
import dayjs from 'dayjs'
import { Event, kinds } from 'nostr-tools'
import { getEventCoordinate, isReplaceable } from './event'
import { extractHashtags, extractMentions, getEventCoordinate, isReplaceable } from './event'
// https://github.com/nostr-protocol/nips/blob/master/25.md
export function createReactionDraftEvent(event: Event): TDraftEvent {
@@ -36,3 +36,35 @@ export function createRepostDraftEvent(event: Event): TDraftEvent {
created_at: dayjs().unix()
}
}
export async function createShortTextNoteDraftEvent(
content: string,
parentEvent?: Event
): Promise<TDraftEvent> {
const { pubkeys, eventIds, rootEventId, parentEventId } = await extractMentions(
content,
parentEvent
)
const hashtags = extractHashtags(content)
const tags = pubkeys
.map((pubkey) => ['p', pubkey])
.concat(eventIds.map((eventId) => ['q', eventId])) // TODO: ["q", <event-id>, <relay-url>, <pubkey>]
.concat(hashtags.map((hashtag) => ['t', hashtag]))
.concat([['client', 'jumble']])
if (rootEventId) {
tags.push(['e', rootEventId, '', 'root'])
}
if (parentEventId) {
tags.push(['e', parentEventId, '', 'reply'])
}
return {
kind: kinds.ShortTextNote,
content,
tags,
created_at: dayjs().unix()
}
}

View File

@@ -1,4 +1,5 @@
import { Event, kinds } from 'nostr-tools'
import client from '@renderer/services/client.service'
import { Event, kinds, nip19 } from 'nostr-tools'
import { replyETag, rootETag, tagNameEquals } from './tag'
export function isNsfwEvent(event: Event) {
@@ -9,9 +10,7 @@ export function isNsfwEvent(event: Event) {
}
export function isReplyNoteEvent(event: Event) {
return (
event.kind === kinds.ShortTextNote && event.tags.some((tag) => replyETag(tag) || rootETag(tag))
)
return event.kind === kinds.ShortTextNote && event.tags.some(rootETag)
}
export function getParentEventId(event?: Event) {
@@ -30,3 +29,90 @@ export function getEventCoordinate(event: Event) {
const d = event.tags.find(tagNameEquals('d'))?.[1]
return d ? `${event.kind}:${event.pubkey}:${d}` : `${event.kind}:${event.pubkey}`
}
export function getSharableEventId(event: Event) {
if (isReplaceable(event.kind)) {
const identifier = event.tags.find(tagNameEquals('d'))?.[1] ?? ''
return nip19.naddrEncode({ pubkey: event.pubkey, kind: event.kind, identifier })
}
return nip19.neventEncode({ id: event.id, author: event.pubkey, kind: event.kind })
}
export async function extractMentions(content: string, parentEvent?: Event) {
const pubkeySet = new Set<string>()
const eventIdSet = new Set<string>()
let rootEventId: string | undefined
let parentEventId: string | undefined
const matches = content.match(
/nostr:(npub1[a-z0-9]{58}|nprofile1[a-z0-9]+|note1[a-z0-9]{58}|nevent1[a-z0-9]+)/g
)
for (const m of matches || []) {
try {
const id = m.split(':')[1]
const { type, data } = nip19.decode(id)
if (type === 'nprofile') {
pubkeySet.add(data.pubkey)
} else if (type === 'npub') {
pubkeySet.add(data)
} else if (type === 'nevent') {
eventIdSet.add(data.id)
if (data.author) {
pubkeySet.add(data.author)
} else {
const event = await client.fetchEventById(data.id)
if (event) {
pubkeySet.add(event.pubkey)
}
}
} else if (type === 'note') {
const event = await client.fetchEventById(data)
if (event) {
pubkeySet.add(event.pubkey)
}
}
} catch (e) {
console.error(e)
}
}
if (parentEvent) {
pubkeySet.add(parentEvent.pubkey)
parentEvent.tags.forEach((tag) => {
if (tagNameEquals('p')(tag)) {
pubkeySet.add(tag[1])
} else if (rootETag(tag)) {
rootEventId = tag[1]
} else if (tagNameEquals('e')(tag)) {
eventIdSet.add(tag[1])
}
})
if (rootEventId) {
parentEventId = parentEvent.id
} else {
rootEventId = parentEvent.id
}
}
if (rootEventId) eventIdSet.delete(rootEventId)
if (parentEventId) eventIdSet.delete(parentEventId)
return {
pubkeys: Array.from(pubkeySet),
eventIds: Array.from(eventIdSet),
rootEventId,
parentEventId
}
}
export function extractHashtags(content: string) {
const hashtags: string[] = []
const matches = content.match(/#([^\s#]+)/g)
matches?.forEach((m) => {
const hashtag = m.slice(1).toLowerCase()
if (hashtag) {
hashtags.push(hashtag)
}
})
return hashtags
}

View File

@@ -63,7 +63,11 @@ export default function ProfilePage({ pubkey }: { pubkey?: string }) {
</div>
</div>
<Separator className="my-4" />
<NoteList key={pubkey} filter={{ authors: [pubkey] }} relayUrls={relayList.write} />
<NoteList
key={pubkey}
filter={{ authors: [pubkey] }}
relayUrls={relayList.write.slice(0, 5)}
/>
</SecondaryPageLayout>
)
}

View File

@@ -49,7 +49,7 @@ export function NoteStatsProvider({ children }: { children: React.ReactNode }) {
const fetchNoteLikeCount = async (event: Event) => {
const relayList = await client.fetchRelayList(event.pubkey)
const events = await client.fetchEvents(relayList.read, {
const events = await client.fetchEvents(relayList.read.slice(0, 3), {
'#e': [event.id],
kinds: [kinds.Reaction],
limit: 500
@@ -74,7 +74,7 @@ export function NoteStatsProvider({ children }: { children: React.ReactNode }) {
const fetchNoteRepostCount = async (event: Event) => {
const relayList = await client.fetchRelayList(event.pubkey)
const events = await client.fetchEvents(relayList.read, {
const events = await client.fetchEvents(relayList.read.slice(0, 3), {
'#e': [event.id],
kinds: [kinds.Repost],
limit: 100
@@ -95,7 +95,7 @@ export function NoteStatsProvider({ children }: { children: React.ReactNode }) {
if (!pubkey) return false
const relayList = await client.fetchRelayList(pubkey)
const events = await client.fetchEvents(relayList.write, {
const events = await client.fetchEvents(relayList.write.slice(0, 3), {
'#e': [event.id],
authors: [pubkey],
kinds: [kinds.Reaction]
@@ -123,7 +123,7 @@ export function NoteStatsProvider({ children }: { children: React.ReactNode }) {
if (!pubkey) return false
const relayList = await client.fetchRelayList(pubkey)
const events = await client.fetchEvents(relayList.write, {
const events = await client.fetchEvents(relayList.write.slice(0, 3), {
'#e': [event.id],
authors: [pubkey],
kinds: [kinds.Repost]

View File

@@ -237,8 +237,8 @@ class ClientService {
}
})
return {
write: relayList.write.slice(0, 3),
read: relayList.read.slice(0, 3)
write: relayList.write.slice(0, 10),
read: relayList.read.slice(0, 10)
}
})
}