Skip to content

Commit

Permalink
web-client: improved event reply; fixes related to form
Browse files Browse the repository at this point in the history
  • Loading branch information
franzos committed Aug 27, 2023
1 parent 9e136ed commit 1ead16d
Show file tree
Hide file tree
Showing 8 changed files with 191 additions and 65 deletions.
108 changes: 85 additions & 23 deletions client-web/src/components/create-event-form.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useState } from "react";
import { useEffect, useRef, useState } from "react";
import {
Box,
FormControl,
Expand All @@ -14,7 +14,6 @@ import {
import {
NEVENT_KIND,
NewLongFormContent,
NewQuoteRepost,
NewRecommendRelay,
NewShortTextNote,
} from "@nostr-ts/common";
Expand All @@ -36,6 +35,16 @@ export const CreateEventForm = () => {
state.connected && state.keystore !== "none",
]);
const [errors, setErrors] = useState<string[]>([]);
const [users, setUsers] = useState<
{
user: NUser;
relayUrls: string[];
}[]
>([]);
const [publicKeyTags] = useNClient((state) => [
state.newEvent?.hasPublicKeyTags(),
]);
const [isBusy, setBusy] = useState<boolean>(false);
const [keystore, keypair, eventKind, newEventName, newEvent] = useNClient(
(state) => [
state.keystore,
Expand All @@ -45,37 +54,78 @@ export const CreateEventForm = () => {
state.newEvent,
]
);

const [relayUrls, setRelayUrls] = useState<string[]>([]);

const toast = useToast();

const [users, setUsers] = useState<NUser[]>([]);
const [publicKeyTags] = useNClient((state) => [
state.newEvent?.hasPublicKeyTags(),
]);
const [userrelayUrl, setUserrelayUrl] = useState<string>("");
const currentPubkey = useRef<string | undefined>(undefined);

useEffect(() => {
const loadUser = async () => {
const foundUsers = [];
if (
newEventName !== "NewShortTextNoteResponse"
// newEventName !== "NewQuoteRepost"
) {
return;
}

const publicKey = useNClient.getState().newEvent?.pubkey;
if (!publicKey) {
return;
}
if (currentPubkey.current === publicKey) {
return;
}
currentPubkey.current = publicKey;

const foundUsers: {
user: NUser;
relayUrls: string[];
}[] = [];
const foundRelayUrls = [];
if (publicKeyTags) {
for (const tags of publicKeyTags) {
let relayUrl;
/**
* Get the relay url from the tags [p, pubkey, relayUrl]
*/
if (tags.length === 2) {
setUserrelayUrl(tags[1]);
relayUrl = tags[1];
foundRelayUrls.push(tags[1]);
}
const key = tags[0];
const record = await useNClient.getState().getUser(key);
if (record) {
foundUsers.push(record.user);
foundUsers.push({
user: record.user,
relayUrls: record.relayUrls
? record.relayUrls
: relayUrl
? [relayUrl]
: [],
});
} else {
foundUsers.push(new NUser({ pubkey: key }));
foundUsers.push({
user: new NUser({ pubkey: key }),
relayUrls: relayUrl ? [relayUrl] : [],
});
}
}
}
setUsers(foundUsers);
if (foundUsers.length > 0) {
setUsers(foundUsers);
}
if (foundRelayUrls.length > 0) {
setRelayUrls(foundRelayUrls);
}
setKind(newEventName, true);
};
loadUser();
}, [publicKeyTags, newEventName]);

const submit = async () => {
setBusy(true);
setErrors([]);
if (!newEvent) {
setErrors(["Event is required"]);
Expand Down Expand Up @@ -128,6 +178,7 @@ export const CreateEventForm = () => {
try {
const evId = await useNClient.getState().signAndSendEvent({
event: newEvent,
relayUrls,
});
if (evId) {
toast({
Expand All @@ -139,7 +190,9 @@ export const CreateEventForm = () => {
});

const overwrite = true;
setKind(newEventName, overwrite);
const resetUser = true;
setKind("NewShortTextNote", overwrite, resetUser);
setBusy(false);
}
} catch (e) {
let error = "";
Expand All @@ -156,6 +209,7 @@ export const CreateEventForm = () => {
duration: 5000,
isClosable: true,
});
setBusy(false);
return;
}
};
Expand All @@ -177,7 +231,7 @@ export const CreateEventForm = () => {
}
};

const setKind = (name: string, overwrite = false) => {
const setKind = (name: string, overwrite = false, resetUser = false) => {
let event;
if (!overwrite && name === newEventName) {
console.log(`Already set to ${name}`);
Expand All @@ -202,11 +256,15 @@ export const CreateEventForm = () => {
});
name = "NewLongFormContent";
break;
case "NewQuoteRepost":
event = NewQuoteRepost({
inResponseTo: new NUser({ pubkey: "" }),
relayUrl: Object.keys(DEFAULT_RELAYS)[0],
});
// case "NewQuoteRepost":
// console.log("TODO: NewQuoteRepost");
// // event = NewQuoteRepost({
// // inResponseTo: useNClient.getState().newEvent,
// // relayUrl: relayUrls[0],
// // });
// break;
case "NewShortTextNoteResponse":
event = useNClient.getState().newEvent;
break;
default:
setErrors(["Invalid event type"]);
Expand All @@ -216,19 +274,22 @@ export const CreateEventForm = () => {
useNClient.getState().setNewEvent(event);
useNClient.getState().setNewEventName(name);
setErrors([]);
if (resetUser) {
setUsers([]);
}
};

return (
<Box width="100%">
<FormControl marginBottom={4}>
<FormLabel>Type: {translateNameToLabel(newEventName)}</FormLabel>

{users.map((user) => (
{users.map((record) => (
<User
user={user}
key={user.pubkey}
user={record.user}
key={record.user.pubkey}
options={{
relayUrls: [userrelayUrl],
relayUrls: record.relayUrls,
}}
/>
))}
Expand Down Expand Up @@ -291,6 +352,7 @@ export const CreateEventForm = () => {
onClick={submit}
leftIcon={<Icon as={SendIcon} />}
isDisabled={!isReady}
isLoading={isBusy}
>
Send
</Button>
Expand Down
37 changes: 26 additions & 11 deletions client-web/src/components/event.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,18 +103,26 @@ export function Event({
onOpen();
};

const newReply = async () => {
const relatedRelay = async () => {
const relays = await useNClient.getState().getRelays();
// TODO: Select relay related to event
const relay = relays.find((r) => r.url === eventRelayUrls[0]);
const relay = relays.find((r) => eventRelayUrls.includes(r.url));
if (relay) return relay;

toast({
title: "Error",
description: `None of the required relays are active ${eventRelayUrls.join(
", "
)}.`,
status: "error",
duration: 5000,
isClosable: true,
});
return;
};

const newReply = async () => {
const relay = await relatedRelay();
if (!relay) {
toast({
title: "Error",
description: `Relay ${eventRelayUrls[0]} not found`,
status: "error",
duration: 5000,
isClosable: true,
});
return;
}
const ev = NewShortTextNoteResponse({
Expand All @@ -133,13 +141,18 @@ export function Event({
* Quote or react to an event
*/
const newAction = async (type: "quote" | "reaction", reaction?: string) => {
const relay = await relatedRelay();
if (!relay) {
return;
}

let ev: NEvent;

switch (type) {
case "quote":
ev = NewQuoteRepost({
inResponseTo: event,
relayUrl: "",
relayUrl: relay.url,
});
break;
case "reaction":
Expand All @@ -150,6 +163,7 @@ export function Event({
id: event.id,
pubkey: event.pubkey,
},
relayUrl: relay.url,
});
break;
default:
Expand All @@ -159,6 +173,7 @@ export function Event({
try {
const evId = await useNClient.getState().signAndSendEvent({
event: ev,
relayUrls: [relay.url],
});
if (evId) {
toast({
Expand Down
2 changes: 2 additions & 0 deletions client-web/src/routes/relays.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ export function RelaysRoute() {
return (
<Tr key={rl.url}>
<Td>{rl.url}</Td>
<Td>{rl.isReady ? "Ready" : "Not Ready"}</Td>
<Td>
<Button
size={"sm"}
Expand Down Expand Up @@ -127,6 +128,7 @@ export function RelaysRoute() {
<Table variant="simple" marginBottom={4}>
<Thead>
<Tr>
<Th>Ready</Th>
<Th>Url</Th>
<Th>Info</Th>
<Th>Read</Th>
Expand Down
2 changes: 1 addition & 1 deletion client-web/src/routes/welcome.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export function WelcomeRoute() {
if (!connected || initDone.current) return;
initDone.current = true;
await useNClient.getState().clearEvents();
defaultFilters.until = Date.now() - 10000;
defaultFilters.until = Math.round(Date.now() / 1000 - 120);
await useNClient
.getState()
.setViewSubscription("welcome", defaultFilters);
Expand Down
18 changes: 10 additions & 8 deletions client-web/src/state/client-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export interface NClient extends NClientBase {
store: Remote<NClientWorker>;
getRelays: () => Promise<WebSocketClientInfo[]>;
updateRelay: (
id: string,
url: string,
options: {
isEnabled?: boolean;
read?: boolean;
Expand Down Expand Up @@ -56,21 +56,23 @@ export interface NClient extends NClientBase {
clearEvents: () => Promise<void>;

setNewEvent: (event: NEvent) => void;

/**
* Track kind name like NewShortTextNote
*/
newEventName: string;
setNewEventName: (name: string) => void;
setNewEventContent: (content: string) => void;

setMaxEvents: (max: number) => Promise<void>;
determineApplicableRelays: (request: PublishingRequest) => Promise<{
relays: WebSocketClientInfo[];
pow: number;
}>;
generateQueueItems: (
request: PublishingRequest
) => Promise<PublishingQueueItem[]>;
) => Promise<PublishingQueueItem[] | undefined>;
events: ProcessedEvent[];
/**
* Track kind name like NewShortTextNote
*/
newEventName: string;
setNewEventName: (name: string) => void;
setNewEventContent: (content: string) => void;

viewerSubscription?: {
page: string;
Expand Down
Loading

0 comments on commit 1ead16d

Please sign in to comment.