~james/core

core/web/src/lib/components/search/codeSearch.svelte.ts -rw-r--r-- 3.6 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import { SvelteSet } from "svelte/reactivity";
import type { Did } from "@atcute/lexicons";
import { createBobbinClient, type BobbinContext } from "#lib/api/client.ts";
import type { FileResult } from "#lib/api/lexicons/types/org/tangled/temp/search/searchCode.ts";
import { errorMessage } from "#lib/api/load.ts";
import { searchCode } from "#lib/api/search.ts";
import { getAuth } from "#lib/auth.svelte.ts";

const PAGE_LIMIT = 50;

const resultKey = (r: FileResult) => `${r.repo.did}/${r.commit}/${r.path}`;

const dedupeResults = (existing: FileResult[], incoming: FileResult[]): FileResult[] => {
	const seen = new SvelteSet(existing.map(resultKey));
	const out = [...existing];
	for (const item of incoming) {
		const key = resultKey(item);
		if (!seen.has(key)) {
			seen.add(key);
			out.push(item);
		}
	}
	return out;
};

export interface CodeSearchOptions {
	/** the committed query */
	query: () => string;
	/** repo did to scope the search to. omit to search everything */
	repo?: () => Did | undefined;
}

export const createCodeSearch = (opts: CodeSearchOptions) => {
	const auth = getAuth();

	let results = $state<FileResult[]>([]);
	let cursor = $state<string | undefined>(undefined);
	let requesting = $state(false);
	let error = $state<string | null>(null);

	let loadingMore = $state(false);
	let moreError = $state<string | null>(null);

	let session: {
		ctx: BobbinContext;
		q: string;
		repo: Did | undefined;
		signal: AbortSignal;
	} | null = null;

	const waitingForAgent = $derived(auth.currentDid !== null && auth.agent === null);
	const loading = $derived(requesting || (waitingForAgent && opts.query().trim() !== ""));

	$effect(() => {
		const q = opts.query().trim();
		const repo = opts.repo?.();
		const agent = auth.agent;

		if (!q || !agent) {
			session = null;
			results = [];
			cursor = undefined;
			requesting = false;
			loadingMore = false;
			error = null;
			moreError = null;
			return;
		}

		const controller = new AbortController();
		const { signal } = controller;
		const scope = {
			ctx: createBobbinClient({ serviceUrl: auth.bobbinUrl, agent }),
			q,
			repo,
			signal
		};
		session = scope;

		results = [];
		cursor = undefined;
		requesting = true;
		loadingMore = false;
		error = null;
		moreError = null;

		searchCode(scope.ctx, { q, repo, limit: PAGE_LIMIT }, { signal })
			.then((found) => {
				if (signal.aborted) return;
				results = dedupeResults([], found.results);
				cursor = found.cursor;
			})
			.catch((cause: unknown) => {
				if (signal.aborted) return;
				results = [];
				error = errorMessage(cause, "Could not search code.");
			})
			.finally(() => {
				if (signal.aborted) return;
				requesting = false;
			});

		return () => controller.abort();
	});

	const loadMore = async () => {
		const scope = session;
		if (!scope || !cursor || loadingMore) return;

		loadingMore = true;
		moreError = null;
		try {
			const found = await searchCode(
				scope.ctx,
				{ q: scope.q, repo: scope.repo, limit: PAGE_LIMIT, cursor },
				{ signal: scope.signal }
			);
			if (scope.signal.aborted) return;
			results = dedupeResults(results, found.results);
			cursor = found.cursor;
		} catch (cause: unknown) {
			if (scope.signal.aborted) return;
			moreError = errorMessage(cause, "Could not load more results.");
		} finally {
			if (!scope.signal.aborted) loadingMore = false;
		}
	};

	return {
		get results() {
			return results;
		},
		get cursor() {
			return cursor;
		},
		get loading() {
			return loading;
		},
		get error() {
			return error;
		},
		get loadingMore() {
			return loadingMore;
		},
		get moreError() {
			return moreError;
		},
		loadMore
	};
};