File size: 11,314 Bytes
7c012de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import React, { useState, useEffect, useCallback } from "react";
import { createRoot } from "react-dom/client";

interface Document {
  id: number;
  title: string;
  content: string;
  snippet: string;
  source: string;
  source_type: string;
  url?: string;
  relevance_score: number;
  rank: number;
  metadata?: Record<string, any>;
}

interface SearchResponse {
  documents: Document[];
  search_time: number;
  query: string;
  total_count: number;
}

interface KnowledgeBrowserProps {
  query?: string;
  results?: Document[];
  search_type?: "semantic" | "keyword" | "hybrid";
  max_results?: number;
  elem_id?: string;
  elem_classes?: string[];
  visible?: boolean;
  onSubmit?: (query: string) => void;
  onSelect?: (document: Document) => void;
}

const KnowledgeBrowser: React.FC<KnowledgeBrowserProps> = ({
  query: initialQuery = "",
  results: initialResults = [],
  search_type: initialSearchType = "semantic",
  max_results: initialMaxResults = 10,
  elem_id,
  elem_classes = [],
  visible = true,
  onSubmit,
  onSelect,
}) => {
  const [query, setQuery] = useState(initialQuery);
  const [results, setResults] = useState<Document[]>(initialResults);
  const [searchType, setSearchType] = useState(initialSearchType);
  const [maxResults, setMaxResults] = useState(initialMaxResults);
  const [isLoading, setIsLoading] = useState(false);
  const [expandedResults, setExpandedResults] = useState<Set<number>>(new Set());
  const [searchTime, setSearchTime] = useState(0);

  const performSearch = useCallback(async (searchQuery: string) => {
    if (!searchQuery.trim()) return;

    setIsLoading(true);
    
    try {
      const response = await fetch("/api/search", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          query: searchQuery,
          search_type: searchType,
          limit: maxResults,
          offset: 0,
        }),
      });

      if (!response.ok) {
        throw new Error(`Search failed: ${response.statusText}`);
      }

      const data: SearchResponse = await response.json();
      setResults(data.documents || []);
      setSearchTime(data.search_time || 0);
      
      // Trigger submit event
      if (onSubmit) {
        onSubmit(searchQuery);
      }
    } catch (error) {
      console.error("Search error:", error);
      setResults([]);
    } finally {
      setIsLoading(false);
    }
  }, [searchType, maxResults, onSubmit]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    performSearch(query);
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      performSearch(query);
    }
  };

  const toggleExpanded = (documentId: number) => {
    const newExpanded = new Set(expandedResults);
    if (newExpanded.has(documentId)) {
      newExpanded.delete(documentId);
    } else {
      newExpanded.add(documentId);
    }
    setExpandedResults(newExpanded);
  };

  const handleSelect = (document: Document) => {
    if (onSelect) {
      onSelect(document);
    }
  };

  const getSourceTypeBadgeClass = (sourceType: string) => {
    const baseClass = "source-type-badge";
    switch (sourceType) {
      case "academic":
        return `${baseClass} source-type-academic`;
      case "web":
        return `${baseClass} source-type-web`;
      case "pdf":
        return `${baseClass} source-type-pdf`;
      case "code":
        return `${baseClass} source-type-code`;
      default:
        return `${baseClass} source-type-web`;
    }
  };

  const formatRelevanceScore = (score: number) => {
    return `${Math.round(score * 100)}%`;
  };

  const formatSearchTime = (time: number) => {
    return time < 1 ? `${Math.round(time * 1000)}ms` : `${time.toFixed(2)}s`;
  };

  if (!visible) {
    return null;
  }

  const containerClasses = ["kb-browser", ...elem_classes].join(" ");

  return (
    <div id={elem_id} className={containerClasses}>
      {/* Search Interface */}
      <div className="search-interface">
        <form onSubmit={handleSubmit}>
          <div className="search-input-container">
            <input
              type="text"
              className="search-input"
              placeholder="Enter your search query..."
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              onKeyDown={handleKeyDown}
              disabled={isLoading}
            />
            <button
              type="submit"
              className="search-button"
              disabled={!query.trim() || isLoading}
            >
              {isLoading ? (
                <>
                  <span className="loading-spinner"></span>
                  <span style={{ marginLeft: "8px" }}>Searching...</span>
                </>
              ) : (
                "Search"
              )}
            </button>
          </div>
          
          <div className="search-options">
            <label>
              Search Type:
              <select
                className="search-type-select"
                value={searchType}
                onChange={(e) => setSearchType(e.target.value as any)}
                disabled={isLoading}
              >
                <option value="semantic">Semantic</option>
                <option value="keyword">Keyword</option>
                <option value="hybrid">Hybrid</option>
              </select>
            </label>
            
            <label>
              Max Results:
              <select
                className="search-type-select"
                value={maxResults}
                onChange={(e) => setMaxResults(parseInt(e.target.value))}
                disabled={isLoading}
              >
                <option value={5}>5</option>
                <option value={10}>10</option>
                <option value={20}>20</option>
              </select>
            </label>
          </div>
        </form>
      </div>

      {/* Results Container */}
      <div className="results-container">
        {results.length > 0 && (
          <div className="results-header">
            <div className="results-info">
              <strong>{results.length}</strong> results found in{" "}
              <strong>{formatSearchTime(searchTime)}</strong>
            </div>
          </div>
        )}

        {isLoading ? (
          <div className="empty-state">
            <div className="loading-spinner" style={{ marginBottom: "12px" }}></div>
            <p>Searching knowledge base...</p>
          </div>
        ) : results.length === 0 && query ? (
          <div className="empty-state">
            <p>No results found for "{query}"</p>
            <p style={{ fontSize: "14px", marginTop: "8px" }}>
              Try adjusting your search terms or search type.
            </p>
          </div>
        ) : results.length === 0 ? (
          <div className="empty-state">
            <p>Enter a search query to find relevant documents</p>
          </div>
        ) : (
          <div>
            {results.map((result) => (
              <div key={result.id} className="result-card">
                <div className="result-header">
                  <div className="result-meta">
                    <span className={getSourceTypeBadgeClass(result.source_type)}>
                      {result.source_type}
                    </span>
                    <span className="relevance-score">
                      {formatRelevanceScore(result.relevance_score)}
                    </span>
                  </div>
                  
                  <h3 className="result-title">{result.title}</h3>
                  <p className="result-source">{result.source}</p>
                  
                  <div className="result-snippet">{result.snippet}</div>
                  
                  <div className="result-actions">
                    <button
                      className="action-button"
                      onClick={() => toggleExpanded(result.id)}
                    >
                      {expandedResults.has(result.id) ? "Collapse" : "Expand"}
                    </button>
                    
                    {result.url && (
                      <button
                        className="action-button"
                        onClick={() => window.open(result.url, "_blank")}
                      >
                        View Source
                      </button>
                    )}
                    
                    <button
                      className="action-button primary"
                      onClick={() => handleSelect(result)}
                    >
                      Use This
                    </button>
                  </div>
                </div>
                
                {expandedResults.has(result.id) && (
                  <div className="expanded-content">
                    <h4>Full Content</h4>
                    <p style={{ lineHeight: "1.6", marginBottom: "16px" }}>
                      {result.content.length > 500
                        ? `${result.content.substring(0, 500)}...`
                        : result.content}
                    </p>
                    
                    {result.metadata && Object.keys(result.metadata).length > 0 && (
                      <>
                        <h4>Metadata</h4>
                        <div className="metadata-grid">
                          {Object.entries(result.metadata).map(([key, value]) => (
                            <div key={key} className="metadata-item">
                              <span className="metadata-label">
                                {key.charAt(0).toUpperCase() + key.slice(1)}:
                              </span>
                              <span className="metadata-value">
                                {Array.isArray(value) ? value.join(", ") : String(value)}
                              </span>
                            </div>
                          ))}
                        </div>
                      </>
                    )}
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

// Initialize the component when DOM is ready
const initializeComponent = () => {
  const container = document.getElementById("kb-browser-root");
  if (container) {
    const root = createRoot(container);
    root.render(
      <KnowledgeBrowser
        onSubmit={(query) => {
          console.log("Search submitted:", query);
          // Dispatch custom event for Gradio integration
          window.dispatchEvent(new CustomEvent("kb-browser-submit", { 
            detail: { query } 
          }));
        }}
        onSelect={(document) => {
          console.log("Document selected:", document);
          // Dispatch custom event for Gradio integration
          window.dispatchEvent(new CustomEvent("kb-browser-select", { 
            detail: { document } 
          }));
        }}
      />
    );
  }
};

// Initialize when DOM is loaded
if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", initializeComponent);
} else {
  initializeComponent();
}

export default KnowledgeBrowser;