Create page: search users #259

Merged
m merged 3 commits from issue-56 into staging 2024-11-21 10:18:33 +00:00
3 changed files with 329 additions and 54 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 186 KiB

View File

@ -1,10 +1,17 @@
import styles from './style.module.scss' import styles from './style.module.scss'
import { Button, FormHelperText, TextField, Tooltip } from '@mui/material' import {
Box,
Button,
CircularProgress,
FormHelperText,
TextField,
Tooltip
} from '@mui/material'
import type { Identifier, XYCoord } from 'dnd-core' import type { Identifier, XYCoord } from 'dnd-core'
import saveAs from 'file-saver' import saveAs from 'file-saver'
import JSZip from 'jszip' import JSZip from 'jszip'
import { Event, kinds } from 'nostr-tools' import { Event, kinds } from 'nostr-tools'
import { useEffect, useRef, useState } from 'react' import { useCallback, useEffect, useRef, useState } from 'react'
import { DndProvider, useDrag, useDrop } from 'react-dnd' import { DndProvider, useDrag, useDrop } from 'react-dnd'
import { MultiBackend } from 'react-dnd-multi-backend' import { MultiBackend } from 'react-dnd-multi-backend'
import { HTML5toTouch } from 'rdndmb-html5-to-touch' import { HTML5toTouch } from 'rdndmb-html5-to-touch'
@ -13,16 +20,20 @@ import { useLocation, useNavigate } from 'react-router-dom'
import { toast } from 'react-toastify' import { toast } from 'react-toastify'
import { LoadingSpinner } from '../../components/LoadingSpinner' import { LoadingSpinner } from '../../components/LoadingSpinner'
import { UserAvatar } from '../../components/UserAvatar' import { UserAvatar } from '../../components/UserAvatar'
import { MetadataController, NostrController } from '../../controllers' import {
MetadataController,
NostrController,
RelayController
} from '../../controllers'
import { appPrivateRoutes } from '../../routes' import { appPrivateRoutes } from '../../routes'
import { import {
CreateSignatureEventContent, CreateSignatureEventContent,
KeyboardCode,
Meta, Meta,
ProfileMetadata, ProfileMetadata,
SignedEvent, SignedEvent,
User, User,
UserRole, UserRole
KeyboardCode
} from '../../types' } from '../../types'
import { import {
encryptArrayBuffer, encryptArrayBuffer,
@ -58,13 +69,19 @@ import {
faGripLines, faGripLines,
faPen, faPen,
faPlus, faPlus,
faSearch,
faToolbox, faToolbox,
faTrash, faTrash,
faUpload faUpload
} from '@fortawesome/free-solid-svg-icons' } from '@fortawesome/free-solid-svg-icons'
import { getSigitFile, SigitFile } from '../../utils/file.ts' import { getSigitFile, SigitFile } from '../../utils/file.ts'
import _ from 'lodash'
import { generateTimestamp } from '../../utils/opentimestamps.ts' import { generateTimestamp } from '../../utils/opentimestamps.ts'
import { Autocomplete } from '@mui/lab'
import _, { truncate } from 'lodash'
import * as React from 'react'
import { AvatarIconButton } from '../../components/UserAvatarIconButton'
type FoundUser = Event & { npub: string }
export const CreatePage = () => { export const CreatePage = () => {
const navigate = useNavigate() const navigate = useNavigate()
@ -87,23 +104,16 @@ export const CreatePage = () => {
} }
const [userInput, setUserInput] = useState('') const [userInput, setUserInput] = useState('')
const handleInputKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => { const [userSearchInput, setUserSearchInput] = useState('')
if (
event.code === KeyboardCode.Enter || const [userRole] = useState<UserRole>(UserRole.signer)
event.code === KeyboardCode.NumpadEnter
) {
event.preventDefault()
handleAddUser()
}
}
const [userRole, setUserRole] = useState<UserRole>(UserRole.signer)
const [error, setError] = useState<string>() const [error, setError] = useState<string>()
const [users, setUsers] = useState<User[]>([]) const [users, setUsers] = useState<User[]>([])
const signers = users.filter((u) => u.role === UserRole.signer) const signers = users.filter((u) => u.role === UserRole.signer)
const viewers = users.filter((u) => u.role === UserRole.viewer) const viewers = users.filter((u) => u.role === UserRole.viewer)
const usersPubkey = useAppSelector((state) => state.auth.usersPubkey) const usersPubkey = useAppSelector((state) => state.auth.usersPubkey)!
const nostrController = NostrController.getInstance() const nostrController = NostrController.getInstance()
@ -112,10 +122,129 @@ export const CreatePage = () => {
) )
const [drawnFiles, setDrawnFiles] = useState<SigitFile[]>([]) const [drawnFiles, setDrawnFiles] = useState<SigitFile[]>([])
const [parsingPdf, setIsParsing] = useState<boolean>(false) const [parsingPdf, setIsParsing] = useState<boolean>(false)
const searchFieldRef = useRef<HTMLInputElement>(null)
const [selectedTool, setSelectedTool] = useState<DrawTool>()
const [foundUsers, setFoundUsers] = useState<FoundUser[]>([])
const [searchUsersLoading, setSearchUsersLoading] = useState<boolean>(false)
const [pastedUserNpubOrNip05, setPastedUserNpubOrNip05] = useState<
string | undefined
>()
/**
* Fired when user select
*/
const handleSearchUserChange = useCallback(
(_event: React.SyntheticEvent, value: string | FoundUser | null) => {
if (typeof value === 'object') {
const ndkEvent = value as FoundUser
if (ndkEvent?.pubkey) {
setUserInput(hexToNpub(ndkEvent.pubkey))
}
}
},
[setUserInput]
)
const handleSearchUsers = async (searchValue?: string) => {
const searchString = searchValue || userSearchInput || undefined
if (!searchString) return
setSearchUsersLoading(true)
const relayController = RelayController.getInstance()
const metadataController = MetadataController.getInstance()
const relaySet = await metadataController.findRelayListMetadata(usersPubkey)
const searchTerm = searchString.trim()
relayController
.fetchEvents(
{
kinds: [0],
search: searchTerm
},
[...relaySet.write]
)
.then((events) => {
console.log('events', events)
const fineFilteredEvents: FoundUser[] = events
.filter((event) => {
const lowercaseContent = event.content.toLowerCase()
return (
lowercaseContent.includes(
`"name":"${searchTerm.toLowerCase()}"`
) ||
lowercaseContent.includes(
`"display_name":"${searchTerm.toLowerCase()}"`
) ||
lowercaseContent.includes(
`"username":"${searchTerm.toLowerCase()}"`
) ||
lowercaseContent.includes(`"nip05":"${searchTerm.toLowerCase()}"`)
)
})
.reduce((uniqueEvents: FoundUser[], event: Event) => {
if (!uniqueEvents.some((e: Event) => e.pubkey === event.pubkey)) {
uniqueEvents.push({
...event,
npub: hexToNpub(event.pubkey)
})
}
return uniqueEvents
}, [])
console.log('fineFilteredEvents', fineFilteredEvents)
setFoundUsers(fineFilteredEvents)
})
.catch((error) => {
console.error(error)
})
.finally(() => {
setSearchUsersLoading(false)
})
}
useEffect(() => {
setTimeout(() => {
if (foundUsers.length) {
if (searchFieldRef.current) {
searchFieldRef.current.blur()
searchFieldRef.current.focus()
}
}
})
}, [foundUsers])
const handleInputKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
if (
event.code === KeyboardCode.Enter ||
event.code === KeyboardCode.NumpadEnter
) {
event.preventDefault()
// If pasted user npub of nip05 is present, we just add the user to the counterparts list
if (pastedUserNpubOrNip05) {
setUserInput(pastedUserNpubOrNip05)
setPastedUserNpubOrNip05(undefined)
} else {
// Otherwize if search already provided some results, user must manually click the search button
if (!foundUsers.length) {
handleSearchUsers()
}
}
}
}
useEffect(() => { useEffect(() => {
if (selectedFiles) { if (selectedFiles) {
/** /**
* Reads the binary files and converts to internal file type * Reads the binary files and converts to an internal file type
* and sets to a state (adds images if it's a PDF) * and sets to a state (adds images if it's a PDF)
*/ */
const parsePages = async () => { const parsePages = async () => {
@ -135,8 +264,6 @@ export const CreatePage = () => {
} }
}, [selectedFiles]) }, [selectedFiles])
const [selectedTool, setSelectedTool] = useState<DrawTool>()
/** /**
* Changes the drawing tool * Changes the drawing tool
* @param drawTool to draw with * @param drawTool to draw with
@ -209,7 +336,7 @@ export const CreatePage = () => {
} }
}, [usersPubkey]) }, [usersPubkey])
const handleAddUser = async () => { const handleAddUser = useCallback(async () => {
setError(undefined) setError(undefined)
const addUser = (pubkey: string) => { const addUser = (pubkey: string) => {
@ -251,6 +378,8 @@ export const CreatePage = () => {
const input = userInput.toLowerCase() const input = userInput.toLowerCase()
setUserSearchInput('')
if (input.startsWith('npub')) { if (input.startsWith('npub')) {
return handleAddNpubUser(input) return handleAddNpubUser(input)
} }
@ -300,7 +429,20 @@ export const CreatePage = () => {
} }
return return
} }
} }, [
userInput,
userRole,
setError,
setUsers,
setUserSearchInput,
setIsLoading,
setLoadingSpinnerDesc,
setUserInput
])
useEffect(() => {
if (userInput?.length > 0) handleAddUser()
}, [handleAddUser, userInput])
const handleUserRoleChange = (role: UserRole, pubkey: string) => { const handleUserRoleChange = (role: UserRole, pubkey: string) => {
setUsers((prevUsers) => setUsers((prevUsers) =>
@ -789,6 +931,61 @@ export const CreatePage = () => {
} }
} }
/**
* Handles the user search textfield change
* If it's not valid npub or nip05, search will be automatically triggered
*/
const handleSearchAutocompleteTextfieldChange = async (
e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
) => {
const value = e.target.value
const disarmAddOnEnter = () => {
setPastedUserNpubOrNip05(undefined)
}
// Seems like it's npub format
if (value.startsWith('npub')) {
// We will try to convert npub to hex and if it's successfull that means
// npub is valid
const validHexPubkey = npubToHex(value)
if (validHexPubkey) {
// Arm the manual user npub add after enter is hit, we don't want to trigger search
setPastedUserNpubOrNip05(value)
} else {
disarmAddOnEnter()
}
} else if (value.includes('@')) {
// Seems like it's nip05 format
const { pubkey } = await queryNip05(value).catch((err) => {
console.error(err)
return { pubkey: null }
})
if (pubkey) {
// Arm the manual user npub add after enter is hit, we don't want to trigger search
setPastedUserNpubOrNip05(hexToNpub(pubkey))
} else {
disarmAddOnEnter()
}
} else {
// Disarm the add user on enter hit, and trigger search after 1 second
disarmAddOnEnter()
}
setUserSearchInput(value)
}
const parseContent = (event: Event) => {
try {
return JSON.parse(event.content)
} catch (e) {
return undefined
console.error(e)
}
}
return ( return (
<> <>
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />} {isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
@ -852,35 +1049,100 @@ export const CreatePage = () => {
moveSigner={moveSigner} moveSigner={moveSigner}
/> />
</div> </div>
<div className={styles.addCounterpart}> <div className={styles.addCounterpart}>
<div className={styles.inputWrapper}> <div className={styles.inputWrapper}>
<Autocomplete
sx={{ width: 300 }}
options={foundUsers}
onChange={handleSearchUserChange}
inputValue={userSearchInput}
disableClearable
openOnFocus
autoHighlight
freeSolo
filterOptions={(x) => x}
getOptionLabel={(option) => {
let label: string = (option as FoundUser).npub
const contentJson = parseContent(option as FoundUser)
if (contentJson?.name) {
label = contentJson.name
} else {
label = option as string
}
return label
}}
renderOption={(props, option) => {
const { ...optionProps } = props
const contentJson = parseContent(option)
return (
<Box
component="li"
sx={{ '& > img': { mr: 2, flexShrink: 0 } }}
{...optionProps}
key={option.pubkey}
>
<AvatarIconButton
src={contentJson.picture}
hexKey={option.pubkey}
color="inherit"
sx={{
padding: '0 10px 0 0'
}}
/>
<div>
{contentJson.name}{' '}
{usersPubkey === option.pubkey ? (
<span
style={{
color: '#4c82a3',
fontWeight: 'bold'
}}
>
Me
</span>
) : (
''
)}{' '}
({truncate(option.npub, { length: 16 })})
</div>
</Box>
)
}}
renderInput={(params) => (
<TextField <TextField
fullWidth {...params}
placeholder="Add counterpart" key={params.id}
value={userInput} inputRef={searchFieldRef}
onChange={(e) => setUserInput(e.target.value)} label="Add/Search counterpart"
onKeyDown={handleInputKeyDown} onKeyDown={handleInputKeyDown}
error={!!error} onChange={handleSearchAutocompleteTextfieldChange}
/>
)}
/> />
</div> </div>
{!pastedUserNpubOrNip05 ? (
<Button <Button
onClick={() => disabled={!userSearchInput || searchUsersLoading}
setUserRole( onClick={() => handleSearchUsers()}
userRole === UserRole.signer
? UserRole.viewer
: UserRole.signer
)
}
variant="contained" variant="contained"
aria-label="Toggle User Role" aria-label="Add"
className={styles.counterpartToggleButton} className={styles.counterpartToggleButton}
> >
<FontAwesomeIcon {searchUsersLoading ? (
icon={userRole === UserRole.signer ? faPen : faEye} <CircularProgress size={14} />
/> ) : (
<FontAwesomeIcon icon={faSearch} />
)}
</Button> </Button>
) : (
<Button <Button
disabled={!userInput}
onClick={handleAddUser} onClick={handleAddUser}
variant="contained" variant="contained"
aria-label="Add" aria-label="Add"
@ -888,6 +1150,7 @@ export const CreatePage = () => {
> >
<FontAwesomeIcon icon={faPlus} /> <FontAwesomeIcon icon={faPlus} />
</Button> </Button>
)}
</div> </div>
<div className={`${styles.paperGroup} ${styles.toolbox}`}> <div className={`${styles.paperGroup} ${styles.toolbox}`}>

View File

@ -2,6 +2,18 @@ import { TimeoutError } from '../types/errors/TimeoutError.ts'
import { CurrentUserFile } from '../types/file.ts' import { CurrentUserFile } from '../types/file.ts'
import { SigitFile } from './file.ts' import { SigitFile } from './file.ts'
export const debounceCustom = <T extends (...args: never[]) => void>(
fn: T,
delay: number
): ((...args: Parameters<T>) => void) => {
let timerId: ReturnType<typeof setTimeout>
return (...args: Parameters<T>) => {
clearTimeout(timerId)
timerId = setTimeout(() => fn(...args), delay)
}
}
export const compareObjects = ( export const compareObjects = (
obj1: object | null | undefined, obj1: object | null | undefined,
obj2: object | null | undefined obj2: object | null | undefined