Starting on handlesubmit for course form, added filter to zaps, using subscribemany for zaps

This commit is contained in:
austinkelsay 2024-04-24 14:30:40 -05:00
parent 24881fe856
commit 76d40c6deb
3 changed files with 114 additions and 34 deletions

View File

@ -64,36 +64,53 @@ const CourseForm = () => {
const createdAt = Math.floor(Date.now() / 1000); // UNIX timestamp const createdAt = Math.floor(Date.now() / 1000); // UNIX timestamp
const eventKind = 30050; // Custom kind for a course list const eventKind = 30050; // Custom kind for a course list
// Publish unpublished drafts as NIP-23 events
const publishedLessons = await Promise.all(
lessons.map(async (lesson) => {
console.log('lesson:', lesson);
if (lesson.type === 'draft') {
const draftEvent = {
kind: 30023,
created_at: createdAt,
content: lesson.content,
tags: [
["d", lesson.id],
["title", lesson.title],
// Add other metadata tags as needed
],
pubkey: pubkey,
};
console.log('draftEvent:', draftEvent);
return draftEvent;
}
}));
const tags = [ const tags = [
["title", title], ["title", title],
["summary", summary], ["summary", summary],
["price", checked ? price.toString() : "free"], ["price", checked ? price.toString() : "free"],
["image", coverImage], ["image", coverImage],
...lessons.map(lesson => ["a", lesson.id, lesson.title.toLowerCase()]), ...publishedLessons.map(lesson => ["a", `30023:${lesson.id}:${lesson.id}`]),
...topics.map(topic => ["topic", topic.trim().toLowerCase()]) ...topics.map(topic => ["topic", topic.trim().toLowerCase()])
]; ];
const content = JSON.stringify({ description: "Course content details" }); // Placeholder content const content = JSON.stringify({ description: "Course content details" }); // Placeholder content
const eventData = JSON.stringify([0, pubkey, createdAt, eventKind, tags, content]); const courseEvent = {
const nostrEvent = {
id: '', // ID would typically be a hash of eventData, to be filled in after eventData is signed
pubkey,
created_at: createdAt,
kind: eventKind, kind: eventKind,
tags, created_at: createdAt,
content, content: content,
sig: '', // Signature to be generated externally tags: tags,
pubkey: pubkey,
}; };
console.log(nostrEvent); // Logging the event console.log('courseEvent:', courseEvent);
}; };
const handleLessonChange = (e, index) => { const handleLessonChange = (e, index) => {
const selectedLessonId = e.value; const selectedLessonId = e.value;
const selectedLesson = getContentOptions(index).flatMap(group => group.items).find(lesson => lesson.value === selectedLessonId); const selectedLesson = getContentOptions(index).flatMap(group => group.items).find(lesson => lesson.value === selectedLessonId);
const updatedLessons = lessons.map((lesson, i) => const updatedLessons = lessons.map((lesson, i) =>
i === index ? { ...lesson, id: selectedLessonId, title: selectedLesson.label.props.content.title } : lesson i === index ? { ...lesson, id: selectedLessonId, title: selectedLesson.label.props.content.title } : lesson
); );
@ -112,11 +129,11 @@ const CourseForm = () => {
const removeLesson = (index) => { const removeLesson = (index) => {
const updatedLessons = lessons.filter((_, i) => i !== index); const updatedLessons = lessons.filter((_, i) => i !== index);
const updatedSelectedLessons = selectedLessons.filter((_, i) => i !== index); const updatedSelectedLessons = selectedLessons.filter((_, i) => i !== index);
if (updatedLessons.length === 0) { if (updatedLessons.length === 0) {
updatedLessons.push({ id: uuidv4(), title: 'Select a lesson' }); updatedLessons.push({ id: uuidv4(), title: 'Select a lesson' });
} }
setLessons(updatedLessons); setLessons(updatedLessons);
setSelectedLessons(updatedSelectedLessons); setSelectedLessons(updatedSelectedLessons);
}; };
@ -140,7 +157,7 @@ const CourseForm = () => {
label: <ContentDropdownItem content={draft} onSelect={(content) => handleLessonSelect(content, index)} selected={lessons[index] && lessons[index].id === draft.id} />, label: <ContentDropdownItem content={draft} onSelect={(content) => handleLessonSelect(content, index)} selected={lessons[index] && lessons[index].id === draft.id} />,
value: draft.id value: draft.id
})); }));
const resourceOptions = resources.map(resource => { const resourceOptions = resources.map(resource => {
const { id, title, summary, image, published_at } = parseEvent(resource); const { id, title, summary, image, published_at } = parseEvent(resource);
return { return {
@ -148,7 +165,7 @@ const CourseForm = () => {
value: id value: id
}; };
}); });
const workshopOptions = workshops.map(workshop => { const workshopOptions = workshops.map(workshop => {
const { id, title, summary, image, published_at } = parseEvent(workshop); const { id, title, summary, image, published_at } = parseEvent(workshop);
return { return {
@ -156,7 +173,7 @@ const CourseForm = () => {
value: id value: id
}; };
}); });
return [ return [
{ {
label: 'Drafts', label: 'Drafts',

View File

@ -20,3 +20,54 @@ const ZapForm = ({ event }) => {
}; };
export default ZapForm; export default ZapForm;
// import React, { useState } from "react";
// import { Button } from 'primereact/button';
// import { InputText } from 'primereact/inputtext';
// import { InputTextarea } from 'primereact/inputtextarea';
// import { useNostr } from "@/hooks/useNostr";
// const ZapForm = ({event}) => {
// const [zapAmount, setZapAmount] = useState(0);
// const [comment, setComment] = useState("");
// const { zapEvent } = useNostr();
// const handleZapButton = (amount) => {
// setZapAmount(amount);
// };
// const handleCustomAmountChange = (event) => {
// setZapAmount(event.target.value);
// };
// const handleCommentChange = (event) => {
// setComment(event.target.value);
// };
// const handleSubmit = async () => {
// const millisatAmount = zapAmount * 1000;
// const response = await zapEvent(event, millisatAmount, comment);
// console.log('zap response:', response);
// };
// return (
// <div className="flex flex-col">
// <div className="flex flex-row justify-start">
// {[1, 10, 21, 100, 500, 1000].map(amount => (
// <Button key={amount} label={amount.toString()} icon="pi pi-bolt" severity="success"
// rounded className="mr-2" onClick={() => handleZapButton(amount)} />
// ))}
// </div>
// <div className="flex flex-row w-[100%] justify-between my-4">
// <InputText placeholder="Custom Amount" value={zapAmount} onChange={handleCustomAmountChange} />
// </div>
// <InputTextarea rows={5} placeholder="Message" value={comment} onChange={handleCommentChange} />
// <Button label="Zap" icon="pi pi-bolt" severity="success" className="mt-4" onClick={handleSubmit} />
// </div>
// );
// };
// export default ZapForm;

View File

@ -166,33 +166,45 @@ export function useNostr() {
try { try {
// Collect all #a and #e tag values from the list of events // Collect all #a and #e tag values from the list of events
let aTags = []; let aTags = [];
let aTagsAlt = [];
let eTags = []; let eTags = [];
events.forEach(event => { events.forEach(event => {
aTags.push(`${event.kind}:${event.id}:${event.d}`); aTags.push(`${event.kind}:${event.id}:${event.d}`);
aTagsAlt.push(`${event.kind}:${event.pubkey}:${event.d}`);
eTags.push(event.id); eTags.push(event.id);
}); });
// Create filters for batch querying // Create filters for batch querying
const filterA = { kinds: [9735], '#a': aTags }; const filterA = { kinds: [9735], '#a': aTags };
const filterE = { kinds: [9735], '#e': eTags }; const filterE = { kinds: [9735], '#e': eTags };
const filterAAlt = { kinds: [9735], '#a': aTagsAlt };
// Perform batch queries // Perform batch queries
const [zapsA, zapsE] = await Promise.all([ // const [zapsA, zapsE] = await Promise.all([
pool.querySync(defaultRelays, filterA), // pool.querySync(defaultRelays, filterA),
pool.querySync(defaultRelays, filterE) // pool.querySync(defaultRelays, filterE)
]); // ]);
let allZaps = []
// Combine results and filter out duplicates
const combinedZaps = [...zapsA]; await new Promise((resolve) => pool.subscribeMany(defaultRelays, [filterA, filterE, filterAAlt], {
const existingIds = new Set(zapsA.map(zap => zap.id)); onerror: (error) => {
zapsE.forEach(zap => { console.error('Failed to fetch zaps for events:', error);
if (!existingIds.has(zap.id)) { resolve([]);
combinedZaps.push(zap); },
existingIds.add(zap.id); onevent: (event) => {
allZaps.push(event);
},
oneose: () => {
resolve(allZaps);
} }
}); }))
return combinedZaps; // remove any duplicates
allZaps = allZaps.filter((zap, index, self) => index === self.findIndex((t) => (
t.id === zap.id
)))
return allZaps;
} catch (error) { } catch (error) {
console.error('Failed to fetch zaps for events:', error); console.error('Failed to fetch zaps for events:', error);
return []; return [];
@ -275,12 +287,12 @@ export function useNostr() {
kind: 9734, kind: 9734,
content: "", content: "",
tags: [ tags: [
["relays", defaultRelays[4], defaultRelays[5]], ["relays", defaultRelays.join(",")],
["amount", amount.toString()], ["amount", amount.toString()],
// ["lnurl", lnurl], // ["lnurl", lnurl],
["e", event.id], ["e", event.id],
["p", event.pubkey], ["p", event.pubkey],
["a", `${event.kind}:${event.id}:${event.d}`], ["a", `${event.kind}:${event.pubkey}:${event.d}`],
], ],
created_at: Math.floor(Date.now() / 1000) created_at: Math.floor(Date.now() / 1000)
} }