diff --git a/cmd/server/main.go b/cmd/server/main.go
index 347b3e2..94715fb 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -607,6 +607,7 @@ func main() {
e.GET("/docs", docsHandler.DocsHome)
e.GET("/docs/*", docsHandler.ShowDocumentation)
e.GET("/docs/api/search", docsHandler.Search)
+ e.GET("/docs/search-index.json", docsHandler.ServeSearchIndex)
// Start server
log.Printf("Starting server on port %s", cfg.ServerPort)
diff --git a/internal/docs/handler.go b/internal/docs/handler.go
index cd6b95f..daf09ed 100644
--- a/internal/docs/handler.go
+++ b/internal/docs/handler.go
@@ -359,3 +359,59 @@ func (h *DocsHandler) GetAPIEndpointData(endpointPath string) (*templates.Endpoi
return nil, fmt.Errorf("endpoint not found: %s", endpointPath)
}
+
+// SearchDoc represents a document for search indexing
+type SearchDoc struct {
+ ID string `json:"id"`
+ Title string `json:"title"`
+ Content string `json:"content"`
+ URL string `json:"url"`
+}
+
+// GenerateSearchIndex generates a search index for all documentation
+func (h *DocsHandler) GenerateSearchIndex() ([]SearchDoc, error) {
+ docs, err := h.ListDocuments()
+ if err != nil {
+ return nil, fmt.Errorf("failed to list documents: %w", err)
+ }
+
+ var searchDocs []SearchDoc
+ for _, path := range docs {
+ doc, err := h.LoadDocument(path)
+ if err != nil {
+ continue
+ }
+
+ // Strip HTML tags for better search
+ content := h.stripHTML(doc.Content)
+
+ searchDocs = append(searchDocs, SearchDoc{
+ ID: path,
+ Title: doc.Title,
+ Content: content,
+ URL: "/docs/" + strings.TrimSuffix(path, ".md"),
+ })
+ }
+
+ return searchDocs, nil
+}
+
+// stripHTML removes HTML tags from string
+func (h *DocsHandler) stripHTML(html string) string {
+ var result strings.Builder
+ inTag := false
+ for _, r := range html {
+ if r == '<' {
+ inTag = true
+ continue
+ }
+ if r == '>' {
+ inTag = false
+ continue
+ }
+ if !inTag {
+ result.WriteRune(r)
+ }
+ }
+ return result.String()
+}
diff --git a/internal/docs/http_handler.go b/internal/docs/http_handler.go
index 34050a8..a7a1967 100644
--- a/internal/docs/http_handler.go
+++ b/internal/docs/http_handler.go
@@ -332,3 +332,14 @@ func (h *HTTPHandler) TryEndpoint(c echo.Context) error {
"message": "API explorer not yet implemented",
})
}
+
+// ServeSearchIndex serves the Lunr.js search index
+func (h *HTTPHandler) ServeSearchIndex(c echo.Context) error {
+ index, err := h.docs.GenerateSearchIndex()
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": "failed to generate search index",
+ })
+ }
+ return c.JSON(http.StatusOK, index)
+}
diff --git a/templates/docs.templ b/templates/docs.templ
index 7631780..07c54cc 100644
--- a/templates/docs.templ
+++ b/templates/docs.templ
@@ -14,6 +14,8 @@ templ DocsLayout(nav Navigation, doc Document, user User) {
{ doc.Title } - Bookhoard Documentation
+
+
@@ -270,21 +320,110 @@ templ DocsLayout(nav Navigation, doc Document, user User) {
// Initialize syntax highlighting
hljs.highlightAll();
});
-
- // Search functionality
- async function searchDocs(query) {
- if (query.length < 2) return;
-
- try {
- const response = await fetch('/docs/api/search?q=' + encodeURIComponent(query));
- const data = await response.json();
-
- // Display search results (you can enhance this)
- console.log('Search results:', data.results);
- } catch (error) {
- console.error('Search failed:', error);
+
+ // Search state
+ let idx;
+ let searchResults = [];
+
+ // Load index on page load
+ fetch('/docs/search-index.json')
+ .then(r => r.json())
+ .then(data => {
+ // Initialize Lunr with fuzzy matching
+ idx = lunr(function() {
+ this.use(lunr.flex)
+ this.ref('id')
+ this.field('title', {boost: 10})
+ this.field('content', {boost: 1})
+ data.forEach(doc => this.add(doc))
+ })
+ console.log('Search index loaded:', data.length, 'documents')
+ })
+ .catch(err => console.error('Failed to load search index:', err));
+
+ // Search input with debounce
+ const searchInput = document.getElementById('docs-search');
+ const searchResultsDiv = document.getElementById('search-results');
+
+ let debounceTimer;
+
+ searchInput.addEventListener('input', (e) => {
+ clearTimeout(debounceTimer);
+ debounceTimer = setTimeout(() => {
+ const query = e.target.value.trim();
+
+ if (query.length < 2) {
+ searchResultsDiv.style.display = 'none';
+ return;
+ }
+
+ // Search with fuzzy matching
+ const results = idx.search(query, {
+ fields: {title: {boost: 10}, content: 1},
+ expand: true
+ });
+
+ // Store results for highlighting
+ searchResults = results;
+
+ // Render results
+ renderSearchResults(results, query);
+ }, 150);
+ });
+
+ // Render search results
+ function renderSearchResults(results, query) {
+ if (results.length === 0) {
+ searchResultsDiv.innerHTML = 'No results found
';
+ searchResultsDiv.style.display = 'block';
+ return;
}
+
+ searchResultsDiv.innerHTML = results.map(r => {
+ const doc = getDocById(r.ref);
+ if (!doc) return '';
+
+ const snippet = getSnippet(doc.content, query);
+
+ return `
+
+ ${doc.title}
+ ${snippet}...
+
+ `;
+ }).join('');
+
+ searchResultsDiv.style.display = 'block';
}
+
+ function getDocById(id) {
+ // This would be populated from the index
+ // For now, return a placeholder
+ return {title: id, url: '/docs/' + id.replace('.md', ''), content: ''};
+ }
+
+ function getSnippet(content, query) {
+ // Simple snippet extraction
+ const words = query.toLowerCase().split(/\s+/);
+ const contentLower = content.toLowerCase();
+
+ for (const word of words) {
+ const idx = contentLower.indexOf(word);
+ if (idx !== -1) {
+ const start = Math.max(0, idx - 50);
+ const end = Math.min(content.length, idx + 100);
+ return '...' + content.substring(start, end) + '...';
+ }
+ }
+ return content.substring(0, 150) + '...';
+ }
+
+ // Close search results when clicking outside
+ document.addEventListener('click', (e) => {
+ if (!searchResultsDiv.contains(e.target) && e.target !== searchInput) {
+ searchResultsDiv.style.display = 'none';
+ }
+ });