Browse Source

Consolidate some state values in search

master
buttercat1791 7 months ago
parent
commit
8b61566322
  1. 133
      src/lib/components/EventSearch.svelte
  2. 1
      src/lib/models/search_type.d.ts
  3. 1109
      src/routes/events/+page.svelte

133
src/lib/components/EventSearch.svelte

@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import { goto } from '$app/navigation'; import { goto } from "$app/navigation";
import { Input, Button } from "flowbite-svelte"; import { Input, Button } from "flowbite-svelte";
import { Spinner } from "flowbite-svelte"; import { Spinner } from "flowbite-svelte";
import type { NDKEvent } from "$lib/utils/nostrUtils"; import type { NDKEvent } from "$lib/utils/nostrUtils";
@ -8,19 +8,22 @@
searchBySubscription, searchBySubscription,
searchNip05, searchNip05,
} from "$lib/utils/search_utility"; } from "$lib/utils/search_utility";
import type { SearchCallbacks } from "$lib/utils/search_types";
import { neventEncode, naddrEncode, nprofileEncode } from "$lib/utils"; import { neventEncode, naddrEncode, nprofileEncode } from "$lib/utils";
import { activeInboxRelays, activeOutboxRelays, getNdkContext } from "$lib/ndk"; import {
activeInboxRelays,
activeOutboxRelays,
getNdkContext,
} from "$lib/ndk";
import { getMatchingTags, toNpub } from "$lib/utils/nostrUtils"; import { getMatchingTags, toNpub } from "$lib/utils/nostrUtils";
import { isEventId } from "$lib/utils/nostr_identifiers"; import { isEventId } from "$lib/utils/nostr_identifiers";
import type NDK from '@nostr-dev-kit/ndk'; import type { SearchType } from "$lib/models/search_type";
// Props definition // Props definition
let { let {
loading, loading,
error, error,
searchValue, searchValue,
dTagValue, searchType,
onEventFound, onEventFound,
onSearchResults, onSearchResults,
event, event,
@ -30,7 +33,7 @@
loading: boolean; loading: boolean;
error: string | null; error: string | null;
searchValue: string | null; searchValue: string | null;
dTagValue: string | null; searchType: SearchType | null;
onEventFound: (event: NDKEvent) => void; onEventFound: (event: NDKEvent) => void;
onSearchResults: ( onSearchResults: (
firstOrder: NDKEvent[], firstOrder: NDKEvent[],
@ -70,7 +73,7 @@
// Track last processed values to prevent loops // Track last processed values to prevent loops
let lastProcessedSearchValue = $state<string | null>(null); let lastProcessedSearchValue = $state<string | null>(null);
let lastProcessedDTagValue = $state<string | null>(null); let lastProcessedSearchType = $state<SearchType | null>(null);
let isProcessingSearch = $state(false); let isProcessingSearch = $state(false);
let currentProcessingSearchValue = $state<string | null>(null); let currentProcessingSearchValue = $state<string | null>(null);
let lastSearchValue = $state<string | null>(null); let lastSearchValue = $state<string | null>(null);
@ -110,7 +113,10 @@
updateSearchState(false, true, 1, "event"); updateSearchState(false, true, 1, "event");
} }
} catch (err) { } catch (err) {
handleSearchError(err, "Error fetching event. Please check the ID and try again."); handleSearchError(
err,
"Error fetching event. Please check the ID and try again.",
);
} }
} }
@ -129,7 +135,9 @@
isResetting = false; isResetting = false;
isUserEditing = false; isUserEditing = false;
const query = (queryOverride !== undefined ? queryOverride || "" : searchQuery || "").trim(); const query = (
queryOverride !== undefined ? queryOverride || "" : searchQuery || ""
).trim();
if (!query) { if (!query) {
updateSearchState(false, false, null, null); updateSearchState(false, false, null, null);
return; return;
@ -181,7 +189,12 @@
// AI-NOTE: 2025-01-24 - Treat plain text searches as profile searches by default // AI-NOTE: 2025-01-24 - Treat plain text searches as profile searches by default
// This allows searching for names like "thebeave" or "TheBeave" without needing n: prefix // This allows searching for names like "thebeave" or "TheBeave" without needing n: prefix
if (trimmedQuery && !trimmedQuery.startsWith("nevent") && !trimmedQuery.startsWith("npub") && !trimmedQuery.startsWith("naddr")) { if (
trimmedQuery &&
!trimmedQuery.startsWith("nevent") &&
!trimmedQuery.startsWith("npub") &&
!trimmedQuery.startsWith("naddr")
) {
return { type: "n", term: trimmedQuery }; return { type: "n", term: trimmedQuery };
} }
@ -191,7 +204,7 @@
async function handleSearchByType( async function handleSearchByType(
searchType: { type: string; term: string }, searchType: { type: string; term: string },
query: string, query: string,
clearInput: boolean clearInput: boolean,
) { ) {
const { type, term } = searchType; const { type, term } = searchType;
@ -250,10 +263,16 @@
return; return;
} }
if (dTagValue) { if (searchValue && searchType) {
searchQuery = `d:${dTagValue}`; if (searchType === "d") {
} else if (searchValue) { searchQuery = `d:${searchValue}`;
searchQuery = searchValue; } else if (searchType === "t") {
searchQuery = `t:${searchValue}`;
} else if (searchType === "n") {
searchQuery = `n:${searchValue}`;
} else {
searchQuery = searchValue;
}
} else if (!searchQuery) { } else if (!searchQuery) {
searchQuery = ""; searchQuery = "";
} }
@ -303,17 +322,29 @@
$effect(() => { $effect(() => {
if ( if (
dTagValue && searchValue &&
searchType &&
!searching && !searching &&
!isResetting && !isResetting &&
dTagValue !== lastProcessedDTagValue (searchType !== lastProcessedSearchType ||
searchValue !== lastProcessedSearchValue)
) { ) {
console.log("EventSearch: Processing dTagValue:", dTagValue); console.log("EventSearch: Processing search:", {
lastProcessedDTagValue = dTagValue; searchType,
searchValue,
});
lastProcessedSearchType = searchType;
lastProcessedSearchValue = searchValue;
setTimeout(() => { setTimeout(() => {
if (!searching && !isResetting) { if (!searching && !isResetting) {
handleSearchBySubscription("d", dTagValue); if (searchType === "d") {
handleSearchBySubscription("d", searchValue);
} else if (searchType === "t") {
handleSearchBySubscription("t", searchValue);
} else if (searchType === "n") {
handleSearchBySubscription("n", searchValue);
}
} }
}, 100); }, 100);
} }
@ -386,7 +417,7 @@
foundEvent = null; foundEvent = null;
localError = null; localError = null;
lastProcessedSearchValue = null; lastProcessedSearchValue = null;
lastProcessedDTagValue = null; lastProcessedSearchType = null;
isProcessingSearch = false; isProcessingSearch = false;
currentProcessingSearchValue = null; currentProcessingSearchValue = null;
lastSearchValue = null; lastSearchValue = null;
@ -421,6 +452,10 @@
lastSearchValue = searchValue; lastSearchValue = searchValue;
} }
if (searchType) {
lastProcessedSearchType = searchType;
}
isProcessingSearch = false; isProcessingSearch = false;
currentProcessingSearchValue = null; currentProcessingSearchValue = null;
isWaitingForSearchResult = false; isWaitingForSearchResult = false;
@ -476,18 +511,10 @@
while (retryCount < maxRetries) { while (retryCount < maxRetries) {
// Check if we have any relays in the NDK pool // Check if we have any relays in the NDK pool
if (ndk && ndk.pool && ndk.pool.relays && ndk.pool.relays.size > 0) { if (ndk && ndk.pool && ndk.pool.relays && ndk.pool.relays.size > 0) {
console.debug(`EventSearch: Found ${ndk.pool.relays.size} relays in NDK pool`);
break; break;
} }
// Also check active relay stores as fallback await new Promise((resolve) => setTimeout(resolve, 500));
if ($activeInboxRelays.length > 0 || $activeOutboxRelays.length > 0) {
console.debug(`EventSearch: Found active relays - inbox: ${$activeInboxRelays.length}, outbox: ${$activeOutboxRelays.length}`);
break;
}
console.debug(`EventSearch: Waiting for relays... (attempt ${retryCount + 1}/${maxRetries})`);
await new Promise(resolve => setTimeout(resolve, 500));
retryCount++; retryCount++;
} }
@ -499,18 +526,30 @@
poolRelayCount, poolRelayCount,
inboxCount: $activeInboxRelays.length, inboxCount: $activeInboxRelays.length,
outboxCount: $activeOutboxRelays.length, outboxCount: $activeOutboxRelays.length,
willUseAllRelays: poolRelayCount > 0 || $activeInboxRelays.length > 0 || $activeOutboxRelays.length > 0 willUseAllRelays:
poolRelayCount > 0 ||
$activeInboxRelays.length > 0 ||
$activeOutboxRelays.length > 0,
}); });
// If we have any relays available, proceed with search // If we have any relays available, proceed with search
if (poolRelayCount > 0 || $activeInboxRelays.length > 0 || $activeOutboxRelays.length > 0) { if (
poolRelayCount > 0 ||
$activeInboxRelays.length > 0 ||
$activeOutboxRelays.length > 0
) {
console.log("EventSearch: Relays available, proceeding with search"); console.log("EventSearch: Relays available, proceeding with search");
} else { } else {
console.warn("EventSearch: No relays detected, but proceeding with search - fallback relays will be used"); console.warn(
"EventSearch: No relays detected, but proceeding with search - fallback relays will be used",
);
} }
} }
async function performSubscriptionSearch(searchType: "d" | "t" | "n", searchTerm: string): Promise<void> { async function performSubscriptionSearch(
searchType: "d" | "t" | "n",
searchTerm: string,
): Promise<void> {
if (currentAbortController) { if (currentAbortController) {
currentAbortController.abort(); currentAbortController.abort();
} }
@ -547,11 +586,13 @@
const timeoutPromise = new Promise((_, reject) => { const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => { setTimeout(() => {
reject(new Error("Search timeout: No results received within 30 seconds")); reject(
new Error("Search timeout: No results received within 30 seconds"),
);
}, 30000); }, 30000);
}); });
const result = await Promise.race([searchPromise, timeoutPromise]) as any; const result = (await Promise.race([searchPromise, timeoutPromise])) as any;
console.log("EventSearch: Search completed:", result); console.log("EventSearch: Search completed:", result);
onSearchResults( onSearchResults(
@ -565,7 +606,10 @@
false, // AI-NOTE: 2025-01-24 - Search is complete false, // AI-NOTE: 2025-01-24 - Search is complete
); );
const totalCount = result.events.length + result.secondOrder.length + result.tTagEvents.length; const totalCount =
result.events.length +
result.secondOrder.length +
result.tTagEvents.length;
localError = null; localError = null;
cleanupSearch(); cleanupSearch();
@ -590,10 +634,15 @@
console.error("EventSearch: Search failed:", error); console.error("EventSearch: Search failed:", error);
if (error instanceof Error) { if (error instanceof Error) {
if (error.message.includes("timeout") || error.message.includes("connection")) { if (
localError = "Search timed out. The relays may be temporarily unavailable. Please try again."; error.message.includes("timeout") ||
error.message.includes("connection")
) {
localError =
"Search timed out. The relays may be temporarily unavailable. Please try again.";
} else if (error.message.includes("NDK not initialized")) { } else if (error.message.includes("NDK not initialized")) {
localError = "Nostr client not initialized. Please refresh the page and try again."; localError =
"Nostr client not initialized. Please refresh the page and try again.";
} else { } else {
localError = `Search failed: ${error.message}`; localError = `Search failed: ${error.message}`;
} }
@ -610,6 +659,10 @@
if (searchValue) { if (searchValue) {
lastProcessedSearchValue = searchValue; lastProcessedSearchValue = searchValue;
} }
if (searchType) {
lastProcessedSearchType = searchType;
}
} }
// AI-NOTE: 2025-01-24 - Background profile search is now handled by centralized searchProfiles function // AI-NOTE: 2025-01-24 - Background profile search is now handled by centralized searchProfiles function

1
src/lib/models/search_type.d.ts vendored

@ -0,0 +1 @@
export type SearchType = "id" | "d" | "t" | "n";

1109
src/routes/events/+page.svelte

File diff suppressed because it is too large Load Diff
Loading…
Cancel
Save