diff --git a/index.html b/index.html index 95f2087..f6745c4 100644 --- a/index.html +++ b/index.html @@ -399,6 +399,46 @@ .status-dot { animation: none; } .loading { animation: none; } } + + /* ── Pagination ── */ + .pagination { + display: flex; align-items: center; justify-content: center; + gap: 16px; padding: 24px 0 8px; + } + .page-btn { + font-family: 'Courier New', monospace; + font-size: 0.8rem; font-weight: 700; + letter-spacing: 0.06em; + padding: 10px 22px; + border-radius: 25px; + cursor: pointer; + transition: all 0.25s ease; + text-transform: uppercase; + border: 2px solid rgba(0,240,255,0.25); + background: rgba(0,240,255,0.06); + color: var(--neon-cyan); + text-shadow: 0 0 8px rgba(0,240,255,0.3); + } + .page-btn:hover:not(:disabled) { + background: rgba(0,240,255,0.18); + border-color: var(--neon-cyan); + box-shadow: 0 0 20px rgba(0,240,255,0.25), 0 0 40px rgba(0,240,255,0.08); + transform: translateY(-1px); + } + .page-btn:disabled { + opacity: 0.2; cursor: not-allowed; box-shadow: none; transform: none; + } + .page-info { + font-family: 'Courier New', monospace; + font-size: 0.7rem; + color: rgba(200,200,255,0.35); + letter-spacing: 0.05em; + white-space: nowrap; + } + .page-info span { + color: var(--neon-cyan); + text-shadow: 0 0 6px rgba(0,240,255,0.3); + } @@ -447,6 +487,11 @@
+
@@ -539,65 +584,42 @@ const resultsList = document.getElementById('resultsList'); const resultsMeta = document.getElementById('resultsMeta'); - /** - * Build a list of search endpoints to try in order: - * 1. Local proxy (if on localhost) - * 2. Netlify function (relative URL — works on Netlify) - * 3. Direct Brave API (needs key in localStorage) - */ - function getSearchEndpoints(q) { - const endpoints = []; + // Pagination state + const pagination = document.getElementById('pagination'); + const prevBtn = document.getElementById('prevBtn'); + const nextBtn = document.getElementById('nextBtn'); + const pageInfo = document.getElementById('pageInfo'); + const RESULTS_PER_PAGE = 12; + let currentQuery = ''; + let currentOffset = 0; + let totalResults = 0; - // 1. Local Python proxy (any time we're local — file://, localhost, etc.) - if (isLocalhost) { - endpoints.push({ - name: 'Local Proxy', - url: `http://localhost:8777/search?q=${encodeURIComponent(q)}&count=12`, - }); - // Also send key to proxy if we have one - const apiKey = getApiKey(); - if (apiKey) { - fetch(`http://localhost:8777/key?set=${encodeURIComponent(apiKey)}`).catch(() => {}); - } + function updatePagination() { + if (totalResults === 0 || currentQuery === '') { + pagination.style.display = 'none'; + return; } - - // 2. Netlify function (relative URL — only when NOT on file:// protocol) - // On Netlify this hits the serverless function; on file:// it's meaningless - if (!isFileProtocol) { - endpoints.push({ - name: 'Netlify Function', - url: `/search?q=${encodeURIComponent(q)}&count=12`, - }); - } - - // 3. Direct Brave API fallback (needs localStorage key) - const localKey = getApiKey(); - if (localKey) { - endpoints.push({ - name: 'Brave Direct', - url: `https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(q)}&count=12`, - headers: { - 'Accept': 'application/json', - 'X-Subscription-Token': localKey, - }, - }); - } - - return endpoints; + pagination.style.display = 'flex'; + const currentPage = Math.floor(currentOffset / RESULTS_PER_PAGE) + 1; + const totalPages = Math.max(1, Math.ceil(totalResults / RESULTS_PER_PAGE)); + const isLastPage = currentOffset + RESULTS_PER_PAGE >= totalResults; + pageInfo.innerHTML = `PAGE ${currentPage} / ${totalPages}`; + prevBtn.disabled = currentOffset === 0; + nextBtn.disabled = isLastPage; } - async function doSearch(query) { - const q = query || input.value.trim(); + async function doPagedSearch(offset) { + const q = currentQuery; if (!q) return; - // Switch to results mode - app.classList.add('has-results'); - input.value = q; - resultsList.innerHTML = '
◆ SEARCHING THE GRID ◆
'; + currentOffset = offset; + resultsList.innerHTML = '
◆ SCANNING GRID PAGE ' + (Math.floor(offset / RESULTS_PER_PAGE) + 1) + ' ◆
'; btn.disabled = true; btn.textContent = '...'; + prevBtn.disabled = true; + nextBtn.disabled = true; - const endpoints = getSearchEndpoints(q); + const endpoints = getSearchEndpoints(q, offset); let lastError = null; for (const endpoint of endpoints) { @@ -612,16 +634,20 @@ const data = await res.json(); - // If the response is an error from our proxy/function, continue to next if (data.error) { throw new Error(data.error); } const web = data.web; const results = web?.results || []; + totalResults = web?.total_result_count || (currentOffset + results.length); + + // If we got fewer results than requested OR hit the total, this is the last page + const isLastPage = results.length < RESULTS_PER_PAGE || + (web?.total_result_count && currentOffset + RESULTS_PER_PAGE >= web.total_result_count); resultsMeta.textContent = - `Found ~${web?.total_result_count?.toLocaleString() || results.length} results · ` + + `Found ~${totalResults.toLocaleString()} results · ` + `${(data.processing_time_ms / 1000).toFixed(2)}s · [${endpoint.name}]`; if (results.length === 0) { @@ -636,15 +662,14 @@ `).join(''); } - // Success — exit the loop + updatePagination(); return; } catch (err) { lastError = err; - // Continue to next endpoint } } - // All endpoints failed + // All failed resultsList.innerHTML = `
⚠ GRID DISRUPTION

${escapeHtml(lastError?.message || 'All search endpoints failed')}

@@ -652,11 +677,84 @@ ${isLocalhost ? 'Make sure the proxy is running:
python3 neonex-proxy.py' : 'Check that BRAVE_API_KEY is set in Netlify environment variables'}
`; - + pagination.style.display = 'none'; btn.disabled = false; btn.textContent = 'SEARCH'; } + // Pagination button handlers + prevBtn.addEventListener('click', () => { + if (currentOffset > 0) { + doPagedSearch(Math.max(0, currentOffset - RESULTS_PER_PAGE)); + } + }); + + nextBtn.addEventListener('click', () => { + doPagedSearch(currentOffset + RESULTS_PER_PAGE); + }); + + /** + * Build a list of search endpoints to try in order: + * 1. Local proxy (if on localhost) + * 2. Netlify function (relative URL — works on Netlify) + * 3. Direct Brave API (needs key in localStorage) + */ + function getSearchEndpoints(q, offset = 0) { + const endpoints = []; + + // 1. Local Python proxy (any time we're local — file://, localhost, etc.) + if (isLocalhost) { + endpoints.push({ + name: 'Local Proxy', + url: `http://localhost:8777/search?q=${encodeURIComponent(q)}&count=${RESULTS_PER_PAGE}&offset=${offset}`, + }); + // Also send key to proxy if we have one + const apiKey = getApiKey(); + if (apiKey) { + fetch(`http://localhost:8777/key?set=${encodeURIComponent(apiKey)}`).catch(() => {}); + } + } + + // 2. Netlify function (relative URL — only when NOT on file:// protocol) + if (!isFileProtocol) { + endpoints.push({ + name: 'Netlify Function', + url: `/search?q=${encodeURIComponent(q)}&count=${RESULTS_PER_PAGE}&offset=${offset}`, + }); + } + + // 3. Direct Brave API fallback (needs localStorage key) + const localKey = getApiKey(); + if (localKey) { + endpoints.push({ + name: 'Brave Direct', + url: `https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(q)}&count=${RESULTS_PER_PAGE}&offset=${offset}`, + headers: { + 'Accept': 'application/json', + 'X-Subscription-Token': localKey, + }, + }); + } + + return endpoints; + } + + async function doSearch(query) { + const q = query || input.value.trim(); + if (!q) return; + + // Reset pagination state for a new search + currentQuery = q; + currentOffset = 0; + totalResults = 0; + + // Switch to results mode + app.classList.add('has-results'); + input.value = q; + + await doPagedSearch(0); + } + function escapeHtml(str) { const div = document.createElement('div'); div.textContent = str; @@ -678,6 +776,10 @@ if (app.classList.contains('has-results')) { app.classList.remove('has-results'); resultsList.innerHTML = ''; + pagination.style.display = 'none'; + currentQuery = ''; + currentOffset = 0; + totalResults = 0; input.value = ''; input.focus(); // Glitch effect diff --git a/neonex-proxy.py b/neonex-proxy.py new file mode 100755 index 0000000..52c65ce --- /dev/null +++ b/neonex-proxy.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +"""NEONEX Search Proxy — forwards requests to Brave Search API from localhost. + Keeps your API key server-side so it never hits the browser.""" + +import json, os, sys, gzip, io +from http.server import HTTPServer, BaseHTTPRequestHandler +from urllib.request import Request, urlopen +from urllib.parse import urlparse, parse_qs, quote +from urllib.error import HTTPError + +API_KEY = os.environ.get("BRAVE_API_KEY", "") +# Also try reading from file +_key_file = os.path.join(os.path.dirname(__file__), ".neonex_key") +if not API_KEY and os.path.exists(_key_file): + with open(_key_file) as f: + API_KEY = f.read().strip() +PORT = int(os.environ.get("PORT", "8777")) +BRAVE_URL = "https://api.search.brave.com/res/v1/web/search" + +class Proxy(BaseHTTPRequestHandler): + def do_GET(self): + global API_KEY + parsed = urlparse(self.path) + + # Serve the HTML file + if parsed.path == "/" or parsed.path == "/index.html": + html_path = os.path.join(os.path.dirname(__file__), "NEONEX Search Engine.html") + if not os.path.exists(html_path): + html_path = os.path.join(os.getcwd(), "NEONEX Search Engine.html") + try: + with open(html_path) as f: + html = f.read() + self.send_response(200) + self.send_header("Content-Type", "text/html") + self.send_header("Access-Control-Allow-Origin", "*") + self.end_headers() + self.wfile.write(html.encode()) + except FileNotFoundError: + self.send_error(404, "NEONEX HTML file not found") + return + + # API key set/check + if parsed.path == "/key": + params = parse_qs(parsed.query) + if "set" in params: + raw = params["set"][0] + # Support base64-encoded keys + import base64 as _b64 + try: + API_KEY = _b64.b64decode(raw).decode() + except Exception: + API_KEY = raw + self.send_json({"status": "ok", "has_key": True}) + return + if "setb64" in params: + import base64 as _b64 + API_KEY = _b64.b64decode(params["setb64"][0]).decode() + self.send_json({"status": "ok", "has_key": True}) + return + self.send_json({"has_key": bool(API_KEY)}) + return + + # Search proxy + if parsed.path == "/search": + if not API_KEY: + self.send_json({"error": "No API key configured. Set BRAVE_API_KEY env var or POST /key?set=YOUR_KEY"}, 401) + return + + params = parse_qs(parsed.query) + query = params.get("q", [""])[0] + if not query: + self.send_json({"error": "Missing ?q= parameter"}, 400) + return + + count = params.get("count", ["12"])[0] + offset = params.get("offset", ["0"])[0] + url = f"{BRAVE_URL}?q={quote(query)}&count={count}&offset={offset}" + + try: + req = Request(url, headers={ + "Accept": "application/json", + "X-Subscription-Token": API_KEY, + }) + with urlopen(req, timeout=10) as resp: + raw = resp.read() + # Handle gzip encoding + if resp.headers.get('Content-Encoding') == 'gzip': + raw = gzip.decompress(raw) + data = json.loads(raw.decode()) + self.send_json(data) + except HTTPError as e: + err_body = e.read().decode()[:300] if e.fp else str(e) + self.send_json({"error": f"Brave API error {e.code}: {err_body}"}, e.code) + except Exception as e: + self.send_json({"error": str(e)}, 500) + return + + # CORS preflight + if self.command == "OPTIONS": + self.send_response(204) + self.send_header("Access-Control-Allow-Origin", "*") + self.send_header("Access-Control-Allow-Methods", "GET, OPTIONS") + self.send_header("Access-Control-Allow-Headers", "Content-Type") + self.end_headers() + return + + self.send_error(404, "Not found") + + def send_json(self, data, status=200): + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Access-Control-Allow-Origin", "*") + self.end_headers() + self.wfile.write(json.dumps(data).encode()) + + def log_message(self, fmt, *args): + print(f"[neonex] {args[0]}", flush=True) + +if __name__ == "__main__": + print(f"╔══════════════════════════════════╗") + print(f"║ NEONEX Search Proxy ║") + print(f"║ http://localhost:{PORT} ║") + print(f"╚══════════════════════════════════╝") + if not API_KEY: + print(f"⚠ No API key set. Set it via:") + print(f" curl 'http://localhost:{PORT}/key?set=YOUR_BRAVE_API_KEY'") + print(f" or set the BRAVE_API_KEY env var.") + else: + print(f"✓ API key configured ({API_KEY[:8]}...)") + print() + server = HTTPServer(("0.0.0.0", PORT), Proxy) + try: + server.serve_forever() + except KeyboardInterrupt: + print("\nShutting down.") + server.server_close() diff --git a/netlify/functions/search.js b/netlify/functions/search.js index 760ceb1..64cda79 100644 --- a/netlify/functions/search.js +++ b/netlify/functions/search.js @@ -23,6 +23,7 @@ exports.handler = async (event) => { const query = event.queryStringParameters?.q; const count = event.queryStringParameters?.count || "12"; + const offset = event.queryStringParameters?.offset || "0"; if (!query) { return { @@ -41,7 +42,7 @@ exports.handler = async (event) => { }; } - const braveUrl = `https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(query)}&count=${count}`; + const braveUrl = `https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(query)}&count=${count}&offset=${offset}`; try { // Node 18+ has global fetch built in