Create page: search users #259

Merged
m merged 3 commits from issue-56 into staging 2024-11-21 10:18:33 +00:00
Showing only changes of commit 6c7cac2336 - Show all commits

View File

@ -28,12 +28,12 @@ import {
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,
@ -52,8 +52,7 @@ import {
updateUsersAppData, updateUsersAppData,
uploadToFileStorage, uploadToFileStorage,
DEFAULT_TOOLBOX, DEFAULT_TOOLBOX,
settleAllFullfilfedPromises, settleAllFullfilfedPromises
debounceCustom
} from '../../utils' } from '../../utils'
import { Container } from '../../components/Container' import { Container } from '../../components/Container'
import fileListStyles from '../../components/FileList/style.module.scss' import fileListStyles from '../../components/FileList/style.module.scss'
@ -79,12 +78,10 @@ import { getSigitFile, SigitFile } from '../../utils/file.ts'
import { generateTimestamp } from '../../utils/opentimestamps.ts' import { generateTimestamp } from '../../utils/opentimestamps.ts'
import { Autocomplete } from '@mui/lab' import { Autocomplete } from '@mui/lab'
import _, { truncate } from 'lodash' import _, { truncate } from 'lodash'
import nostrDefaultImage from '../../assets/images/nostr-logo.png'
import * as React from 'react' import * as React from 'react'
import { AvatarIconButton } from '../../components/UserAvatarIconButton'
interface FoundUsers extends Event { type FoundUser = Event & { npub: string }
npub: string
}
export const CreatePage = () => { export const CreatePage = () => {
const navigate = useNavigate() const navigate = useNavigate()
@ -126,20 +123,27 @@ 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 [selectedTool, setSelectedTool] = useState<DrawTool>()
const [foundUsers, setFoundUsers] = useState<FoundUsers[]>([]) const [foundUsers, setFoundUsers] = useState<FoundUser[]>([])
const [searchUsersLoading, setSearchUsersLoading] = useState<boolean>(false) const [searchUsersLoading, setSearchUsersLoading] = useState<boolean>(false)
const [pastedUserNpubOrNip05, setPastedUserNpubOrNip05] = useState<
string | undefined
>()
/** /**
* Fired when user select * Fired when user select
*/ */
const handleSearchUserChange = useCallback( const handleSearchUserChange = useCallback(
(_event: React.SyntheticEvent, value: string | FoundUsers | null) => { (_event: React.SyntheticEvent, value: string | FoundUser | null) => {
if (typeof value === 'object') { if (typeof value === 'object') {
const ndkEvent = value as FoundUsers const ndkEvent = value as FoundUser
if (ndkEvent?.pubkey) {
setUserInput(hexToNpub(ndkEvent.pubkey)) setUserInput(hexToNpub(ndkEvent.pubkey))
} }
}
}, },
[setUserInput] [setUserInput]
) )
@ -166,13 +170,36 @@ export const CreatePage = () => {
[...relaySet.write] [...relaySet.write]
) )
.then((events) => { .then((events) => {
const fineFilteredEvents = events console.log('events', events)
.filter((event) => event.content.includes(`"name":"${searchTerm}`))
.map((event) => ({ 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, ...event,
npub: hexToNpub(event.pubkey) npub: hexToNpub(event.pubkey)
})) })
}
return uniqueEvents
}, [])
console.log('fineFilteredEvents', fineFilteredEvents)
setFoundUsers(fineFilteredEvents) setFoundUsers(fineFilteredEvents)
}) })
.catch((error) => { .catch((error) => {
@ -183,13 +210,16 @@ export const CreatePage = () => {
}) })
} }
// eslint-disable-next-line react-hooks/exhaustive-deps useEffect(() => {
const debouncedHandleSearchUsers = useCallback( setTimeout(() => {
debounceCustom((value: string) => { if (foundUsers.length) {
if (foundUsers.length === 0) handleSearchUsers(value) if (searchFieldRef.current) {
}, 1000), searchFieldRef.current.blur()
[] searchFieldRef.current.focus()
) }
}
})
}, [foundUsers])
const handleInputKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => { const handleInputKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
if ( if (
@ -197,7 +227,17 @@ export const CreatePage = () => {
event.code === KeyboardCode.NumpadEnter event.code === KeyboardCode.NumpadEnter
) { ) {
event.preventDefault() event.preventDefault()
handleAddUser()
// 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()
}
}
} }
} }
@ -296,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) => {
@ -338,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)
} }
@ -387,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) =>
@ -876,10 +931,57 @@ 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) => { const parseContent = (event: Event) => {
try { try {
return JSON.parse(event.content) return JSON.parse(event.content)
} catch (e) { } catch (e) {
return undefined
console.error(e) console.error(e)
} }
} }
@ -951,18 +1053,25 @@ export const CreatePage = () => {
<div className={styles.addCounterpart}> <div className={styles.addCounterpart}>
<div className={styles.inputWrapper}> <div className={styles.inputWrapper}>
<Autocomplete <Autocomplete
id="country-select-demo"
sx={{ width: 300 }} sx={{ width: 300 }}
options={foundUsers} options={foundUsers}
onChange={handleSearchUserChange} onChange={handleSearchUserChange}
inputValue={userSearchInput}
disableClearable
openOnFocus
autoHighlight autoHighlight
freeSolo freeSolo
filterOptions={(x) => x} filterOptions={(x) => x}
getOptionLabel={(option) => { getOptionLabel={(option) => {
let label = (option as FoundUsers).npub let label: string = (option as FoundUser).npub
const contentJson = parseContent(option as FoundUsers) const contentJson = parseContent(option as FoundUser)
if (contentJson?.name) {
label = contentJson.name label = contentJson.name
} else {
label = option as string
}
return label return label
}} }}
@ -978,17 +1087,31 @@ export const CreatePage = () => {
{...optionProps} {...optionProps}
key={option.pubkey} key={option.pubkey}
> >
<img <AvatarIconButton
loading="lazy" src={contentJson.picture}
width="60" hexKey={option.pubkey}
src={contentJson.picture || nostrDefaultImage} color="inherit"
onError={({ currentTarget }) => sx={{
(currentTarget.src = nostrDefaultImage) padding: '0 10px 0 0'
} }}
alt=""
/> />
{contentJson.name} (
{truncate(option.npub, { length: 16 })}) <div>
{contentJson.name}{' '}
{usersPubkey === option.pubkey ? (
<span
style={{
color: '#4c82a3',
fontWeight: 'bold'
}}
>
Me
</span>
) : (
''
)}{' '}
({truncate(option.npub, { length: 16 })})
</div>
</Box> </Box>
) )
}} }}
@ -996,43 +1119,12 @@ export const CreatePage = () => {
<TextField <TextField
{...params} {...params}
key={params.id} key={params.id}
label="Search counterparts" inputRef={searchFieldRef}
value={userSearchInput} label="Add/Search counterpart"
// onChange={(e) => setUserSearchInput(e.target.value)}
onChange={(e) => {
const value = e.target.value
setUserSearchInput(value)
debouncedHandleSearchUsers(value)
}}
/>
)}
/>
</div>
<Button
disabled={!userSearchInput || searchUsersLoading}
onClick={() => handleSearchUsers()}
variant="contained"
aria-label="Add"
className={styles.counterpartToggleButton}
>
{searchUsersLoading ? (
<CircularProgress size={14} />
) : (
<FontAwesomeIcon icon={faSearch} />
)}
</Button>
</div>
<div className={styles.addCounterpart}>
<div className={styles.inputWrapper}>
<TextField
fullWidth
placeholder="Add counterpart"
value={userInput}
onChange={(e) => setUserInput(e.target.value)}
onKeyDown={handleInputKeyDown} onKeyDown={handleInputKeyDown}
disabled={searchUsersLoading} onChange={handleSearchAutocompleteTextfieldChange}
error={!!error} />
)}
/> />
</div> </div>
<Button <Button
@ -1051,8 +1143,23 @@ export const CreatePage = () => {
icon={userRole === UserRole.signer ? faPen : faEye} icon={userRole === UserRole.signer ? faPen : faEye}
/> />
</Button> </Button>
{!pastedUserNpubOrNip05 ? (
<Button
disabled={!userSearchInput || searchUsersLoading}
onClick={() => handleSearchUsers()}
variant="contained"
aria-label="Add"
className={styles.counterpartToggleButton}
>
{searchUsersLoading ? (
<CircularProgress size={14} />
) : (
<FontAwesomeIcon icon={faSearch} />
)}
</Button>
) : (
<Button <Button
disabled={!userInput}
onClick={handleAddUser} onClick={handleAddUser}
variant="contained" variant="contained"
aria-label="Add" aria-label="Add"
@ -1060,6 +1167,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}`}>