plebdevs/src/hooks/useContentSearch.js

74 lines
2.1 KiB
JavaScript
Raw Normal View History

import { useState, useEffect } from 'react';
import { useContentIdsQuery } from '@/hooks/apiQueries/useContentIdsQuery';
import { useNDKContext } from '@/context/NDKContext';
import { parseEvent, parseCourseEvent } from '@/utils/nostr';
2025-04-02 17:47:30 -05:00
import appConfig from '@/config/appConfig';
export const useContentSearch = () => {
2025-04-02 17:47:30 -05:00
const [allContent, setAllContent] = useState([]);
const [searchResults, setSearchResults] = useState([]);
const { contentIds } = useContentIdsQuery();
const { ndk } = useNDKContext();
2025-04-02 17:47:30 -05:00
const fetchAllEvents = async ids => {
try {
await ndk.connect();
const filter = {
authors: appConfig.authorPubkeys,
kinds: [30004, 30023, 30402],
'#d': ids,
};
const events = await ndk.fetchEvents(filter);
const parsedEvents = [];
2025-04-02 17:47:30 -05:00
events.forEach(event => {
let parsed;
if (event.kind === 30004) {
parsed = parseCourseEvent(event);
} else {
parsed = parseEvent(event);
}
parsedEvents.push(parsed);
2025-04-02 17:47:30 -05:00
});
setAllContent(parsedEvents);
} catch (error) {
console.error('error', error);
}
2025-04-02 17:47:30 -05:00
};
2025-04-02 17:47:30 -05:00
useEffect(() => {
if (contentIds) {
fetchAllEvents(contentIds);
}
}, [contentIds]);
2025-04-02 17:47:30 -05:00
const searchContent = term => {
if (term.length > 2) {
const searchTerm = term.toLowerCase();
const filtered = allContent.filter(content => {
// Search in title/name
2025-04-02 17:47:30 -05:00
const searchableTitle = (content?.title || content?.name || '').toLowerCase();
if (searchableTitle.includes(searchTerm)) return true;
// Search in summary/description
2025-04-02 17:47:30 -05:00
const searchableDescription = (
content?.summary ||
content?.description ||
''
).toLowerCase();
if (searchableDescription.includes(searchTerm)) return true;
// Search in topics/tags
const topics = content?.topics || [];
return topics.some(topic => topic.toLowerCase().includes(searchTerm));
2025-04-02 17:47:30 -05:00
});
2025-04-02 17:47:30 -05:00
setSearchResults(filtered);
} else {
setSearchResults([]);
}
};
2025-04-02 17:47:30 -05:00
return { searchContent, searchResults };
};