New search functionality

This commit is contained in:
2025-07-19 15:31:29 -06:00
parent 04eb5f7546
commit 46e39e8c36
12 changed files with 734 additions and 5 deletions

View File

@@ -868,6 +868,175 @@ body {
transform: scale(0.95);
}
/* Documentation Search Styles */
.docs-search-container {
position: relative;
flex: 0 1 400px;
margin: 0 1rem;
}
.docs-search-wrapper {
position: relative;
}
.docs-search-input {
width: 100%;
padding: 0.5rem 2.5rem 0.5rem 1rem;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;
background: white;
transition: border-color 0.2s;
}
.docs-search-input:focus {
outline: none;
border-color: #4CAF50;
box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.1);
}
.docs-search-icon {
position: absolute;
right: 0.75rem;
top: 50%;
transform: translateY(-50%);
opacity: 0.5;
pointer-events: none;
}
.docs-search-results {
position: absolute;
top: calc(100% + 0.5rem);
left: 0;
right: 0;
max-height: 60vh;
background: white;
border: 1px solid #ddd;
border-radius: 4px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
z-index: 1000;
overflow: hidden;
display: flex;
flex-direction: column;
}
.docs-search-results.hidden {
display: none;
}
.docs-search-results-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.75rem 1rem;
border-bottom: 1px solid #eee;
background: #f5f5f5;
}
.results-count {
font-size: 12px;
color: #666;
font-weight: 500;
}
.close-results {
background: none;
border: none;
font-size: 20px;
cursor: pointer;
color: #666;
padding: 0;
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 4px;
transition: background-color 0.2s;
}
.close-results:hover {
background-color: #e0e0e0;
}
.docs-search-results-list {
overflow-y: auto;
flex: 1;
}
.search-result {
display: block;
padding: 1rem;
border-bottom: 1px solid #eee;
text-decoration: none;
color: inherit;
transition: background-color 0.2s;
}
.search-result:hover {
background-color: #f5f5f5;
}
.search-result:last-child {
border-bottom: none;
}
.search-result-title {
font-weight: 500;
color: #333;
margin-bottom: 0.25rem;
}
.search-result-snippet {
font-size: 13px;
color: #666;
line-height: 1.4;
margin-bottom: 0.25rem;
}
.search-result-snippet mark {
background-color: #ffeb3b;
color: inherit;
font-weight: 500;
padding: 0 2px;
}
.search-result-path {
font-size: 11px;
color: #999;
}
.no-results {
padding: 2rem;
text-align: center;
color: #666;
}
/* Mobile responsiveness */
@media (max-width: 768px) {
.docs-search-container {
display: block; /* Show on mobile */
width: 100%;
margin: 10px 0;
padding: 0 10px;
}
.docs-search-wrapper {
width: 100%;
}
.docs-search-input {
width: 100%;
font-size: 16px;
padding: 0.75rem 2.5rem 0.75rem 1rem;
}
.docs-search-results {
left: 0;
right: 0;
width: 100vw;
max-width: 100vw;
min-width: 0;
}
}
/* Desktop styles - show normal layout */
@media (min-width: 769px) {
.mobile-dropdown {

View File

@@ -19,6 +19,26 @@
<!-- Header -->
<header class="header">
<h1>Map for CM-lite</h1>
<!-- Add documentation search bar -->
<div class="docs-search-container">
<div class="docs-search-wrapper">
<input type="text"
id="docs-search-input"
class="docs-search-input"
placeholder="Search docs... (Ctrl+K)"
autocomplete="off">
<span class="docs-search-icon">🔍</span>
</div>
<div id="docs-search-results" class="docs-search-results hidden">
<div class="docs-search-results-header">
<span class="results-count"></span>
<button class="close-results" title="Close (Esc)">&times;</button>
</div>
<div class="docs-search-results-list"></div>
</div>
</div>
<div class="header-actions">
<a href="/shifts.html" class="btn btn-secondary">
<span class="btn-icon">📅</span>

View File

@@ -5,9 +5,11 @@ import { checkAuth } from './auth.js';
import { initializeMap } from './map-manager.js';
import { loadLocations } from './location-manager.js';
import { setupEventListeners } from './ui-controls.js';
import { MkDocsSearch } from './mkdocs-search.js';
// Application state
let refreshInterval = null;
let mkdocsSearch = null;
// Initialize the application
document.addEventListener('DOMContentLoaded', async () => {
@@ -27,6 +29,9 @@ document.addEventListener('DOMContentLoaded', async () => {
setupEventListeners();
setupAutoRefresh();
// Initialize MkDocs search
await initializeMkDocsSearch();
} catch (error) {
console.error('Initialization error:', error);
showStatus('Failed to initialize application', 'error');
@@ -47,3 +52,34 @@ window.addEventListener('beforeunload', () => {
clearInterval(refreshInterval);
}
});
// Initialize MkDocs search
async function initializeMkDocsSearch() {
try {
// Get config from server
const configResponse = await fetch('/api/config');
const config = await configResponse.json();
mkdocsSearch = new MkDocsSearch({
mkdocsUrl: config.mkdocsUrl || 'http://localhost:4002',
minSearchLength: 2
});
const initialized = await mkdocsSearch.initialize();
if (initialized) {
// Bind to search input
const searchInput = document.getElementById('docs-search-input');
const searchResults = document.getElementById('docs-search-results');
if (searchInput && searchResults) {
mkdocsSearch.bindToInput(searchInput, searchResults);
console.log('Documentation search ready');
}
} else {
console.warn('Documentation search could not be initialized');
}
} catch (error) {
console.error('Error setting up documentation search:', error);
}
}

View File

@@ -0,0 +1,241 @@
/**
* MkDocs Search Integration
* Integrates MkDocs Material's search functionality into the map application
*/
export class MkDocsSearch {
constructor(config = {}) {
// Determine if we're in production based on current URL
const isProduction = window.location.hostname !== 'localhost' && !window.location.hostname.includes('127.0.0.1');
// Use production URL if we're not on localhost
if (isProduction && config.mkdocsUrl && config.mkdocsUrl.includes('localhost')) {
// Extract the base domain from the current hostname
// If we're on map.cmlite.org, we want cmlite.org
const currentDomain = window.location.hostname.replace(/^map\./, '');
this.mkdocsUrl = `https://${currentDomain}`;
} else {
this.mkdocsUrl = config.mkdocsUrl || window.MKDOCS_URL || 'http://localhost:4002';
}
this.searchIndex = null;
this.searchDocs = null;
this.lunr = null;
this.debounceTimeout = null;
this.minSearchLength = config.minSearchLength || 2;
this.initialized = false;
console.log('MkDocs Search initialized with URL:', this.mkdocsUrl);
}
async initialize() {
try {
console.log('Initializing MkDocs search...');
// Load Lunr.js dynamically
await this.loadLunr();
// Try multiple approaches to get the search index
let searchData = null;
// First try the proxy endpoint
try {
console.log('Trying proxy endpoint: /api/docs-search');
const proxyResponse = await fetch('/api/docs-search');
if (proxyResponse.ok) {
searchData = await proxyResponse.json();
console.log('Successfully loaded search index via proxy');
}
} catch (proxyError) {
console.warn('Proxy endpoint failed:', proxyError);
}
// If proxy fails, try direct access
if (!searchData) {
console.log(`Trying direct access: ${this.mkdocsUrl}/search/search_index.json`);
const response = await fetch(`${this.mkdocsUrl}/search/search_index.json`);
if (!response.ok) {
throw new Error(`Failed to load search index: ${response.status}`);
}
searchData = await response.json();
console.log('Successfully loaded search index directly');
}
// Build the Lunr index
this.searchIndex = this.lunr(function() {
this.ref('location');
this.field('title', { boost: 10 });
this.field('text');
searchData.docs.forEach(doc => {
this.add(doc);
});
});
this.searchDocs = searchData.docs;
this.initialized = true;
console.log('MkDocs search initialized with', this.searchDocs.length, 'documents');
return true;
} catch (error) {
console.error('Failed to initialize MkDocs search:', error);
this.initialized = false;
return false;
}
}
async loadLunr() {
if (window.lunr) {
this.lunr = window.lunr;
return;
}
// Load Lunr.js from CDN
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = 'https://unpkg.com/lunr@2.3.9/lunr.min.js';
script.onload = () => {
this.lunr = window.lunr;
resolve();
};
script.onerror = reject;
document.head.appendChild(script);
});
}
search(query) {
if (!this.initialized) {
console.warn('Search not initialized');
return [];
}
if (!this.searchIndex || !query || query.length < this.minSearchLength) {
return [];
}
try {
// Perform the search
const results = this.searchIndex.search(query);
// Map results to include document data
return results.slice(0, 10).map(result => {
const doc = this.searchDocs.find(d => d.location === result.ref);
if (!doc) return null;
// Extract a snippet around the matched text
const snippet = this.extractSnippet(doc.text, query);
return {
...doc,
score: result.score,
url: `${this.mkdocsUrl}/${doc.location}`,
snippet: snippet
};
}).filter(Boolean);
} catch (error) {
console.error('Search error:', error);
return [];
}
}
extractSnippet(text, query, maxLength = 150) {
const lowerText = text.toLowerCase();
const lowerQuery = query.toLowerCase();
const index = lowerText.indexOf(lowerQuery);
if (index === -1) {
return text.substring(0, maxLength) + '...';
}
const start = Math.max(0, index - 50);
const end = Math.min(text.length, index + query.length + 100);
let snippet = text.substring(start, end);
if (start > 0) snippet = '...' + snippet;
if (end < text.length) snippet = snippet + '...';
// Highlight the search term
const regex = new RegExp(`(${query})`, 'gi');
snippet = snippet.replace(regex, '<mark>$1</mark>');
return snippet;
}
bindToInput(inputElement, resultsElement) {
const resultsContainer = resultsElement.querySelector('.docs-search-results-list');
const resultsCount = resultsElement.querySelector('.results-count');
const closeBtn = resultsElement.querySelector('.close-results');
// Handle input with debouncing
inputElement.addEventListener('input', (e) => {
clearTimeout(this.debounceTimeout);
this.debounceTimeout = setTimeout(() => {
this.performSearch(e.target.value, resultsContainer, resultsCount, resultsElement);
}, 300);
});
// Handle keyboard shortcuts
inputElement.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
this.closeResults(inputElement, resultsElement);
}
});
// Global keyboard shortcut (Ctrl+K or Cmd+K)
document.addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
e.preventDefault();
inputElement.focus();
inputElement.select();
}
});
// Close button
closeBtn.addEventListener('click', () => {
this.closeResults(inputElement, resultsElement);
});
// Click outside to close
document.addEventListener('click', (e) => {
if (!inputElement.contains(e.target) && !resultsElement.contains(e.target)) {
resultsElement.classList.add('hidden');
}
});
}
performSearch(query, resultsContainer, resultsCount, resultsElement) {
if (!query || query.length < this.minSearchLength) {
resultsElement.classList.add('hidden');
return;
}
const results = this.search(query);
if (results.length === 0) {
resultsContainer.innerHTML = '<div class="no-results">No results found</div>';
resultsCount.textContent = 'No results';
} else {
resultsCount.textContent = `${results.length} result${results.length > 1 ? 's' : ''}`;
resultsContainer.innerHTML = results.map(result => `
<a href="${result.url}" class="search-result" target="_blank" rel="noopener">
<div class="search-result-title">${this.escapeHtml(result.title)}</div>
<div class="search-result-snippet">${result.snippet}</div>
<div class="search-result-path">${result.location}</div>
</a>
`).join('');
}
resultsElement.classList.remove('hidden');
}
closeResults(inputElement, resultsElement) {
resultsElement.classList.add('hidden');
inputElement.value = '';
inputElement.blur();
}
escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
}