瀏覽代碼

Update results as you type

Daoud Clarke 3 年之前
父節點
當前提交
af29b4c039
共有 5 個文件被更改,包括 76 次插入11 次删除
  1. 4 0
      app.py
  2. 6 10
      create_app.py
  3. 6 1
      static/index.html
  4. 42 0
      static/index.js
  5. 18 0
      static/search.html

+ 4 - 0
app.py

@@ -1,3 +1,5 @@
+import logging
+
 import uvicorn
 import uvicorn
 
 
 import create_app
 import create_app
@@ -8,6 +10,8 @@ from paths import INDEX_PATH
 tiny_index = TinyIndex(Document, INDEX_PATH, NUM_PAGES, PAGE_SIZE)
 tiny_index = TinyIndex(Document, INDEX_PATH, NUM_PAGES, PAGE_SIZE)
 app = create_app.create(tiny_index)
 app = create_app.create(tiny_index)
 
 
+logging.basicConfig()
+
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
     uvicorn.run("app:app", host="127.0.0.1", port=8000, log_level="info")
     uvicorn.run("app:app", host="127.0.0.1", port=8000, log_level="info")

+ 6 - 10
create_app.py

@@ -1,3 +1,4 @@
+from logging import getLogger
 from typing import List
 from typing import List
 
 
 import Levenshtein
 import Levenshtein
@@ -8,22 +9,17 @@ from starlette.staticfiles import StaticFiles
 from index import TinyIndex, Document
 from index import TinyIndex, Document
 
 
 
 
+logger = getLogger(__name__)
+
+
 def create(tiny_index: TinyIndex):
 def create(tiny_index: TinyIndex):
     app = FastAPI()
     app = FastAPI()
 
 
     @app.get("/search")
     @app.get("/search")
     def search(s: str):
     def search(s: str):
         results = get_results(s)
         results = get_results(s)
-        doc = ""
-        for result in results:
-            doc += f'<p><a href="{result.url}">{result.title}</a></p>\n'
-        return HTMLResponse(doc)
-
-        # if '—' in s:
-        #     url = s.split('—')[1].strip()
-        # else:
-        #     url = f'https://www.google.com/search?q={s}'
-        # return RedirectResponse(url)
+        logger.info("Return results: %r", results)
+        return results
 
 
     def order_results(query, results: List[Document]):
     def order_results(query, results: List[Document]):
         ordered_results = sorted(results, key=lambda result: Levenshtein.distance(query, result.title))
         ordered_results = sorted(results, key=lambda result: Levenshtein.distance(query, result.title))

+ 6 - 1
static/index.html

@@ -5,12 +5,17 @@
       type="application/opensearchdescription+xml"
       type="application/opensearchdescription+xml"
       title="Stoatally Different"
       title="Stoatally Different"
       href="http://localhost:8000/plugin.xml">
       href="http://localhost:8000/plugin.xml">
+<script src="/index.js"></script>
 </head>
 </head>
 <body>
 <body>
 Stoatally different.
 Stoatally different.
 
 
 <form action="/search">
 <form action="/search">
-  <input type="search" name="s" />
+  <input type="search" id="search" name="s" />
 </form>
 </form>
+
+<div id="results">
+
+</div>
 </body>
 </body>
 </html>
 </html>

+ 42 - 0
static/index.js

@@ -0,0 +1,42 @@
+
+
+window.onload = (event) => {
+    const searchInput = document.getElementById('search');
+
+    searchInput.addEventListener('keyup', (e) => {
+        console.log(searchInput.value);
+
+        const encodedValue = encodeURIComponent(searchInput.value);
+        fetch('/search?s=' + encodedValue).then(response => {
+            clearResults();
+            console.log(response);
+            response.json().then(content => {
+                console.log(content);
+                content.forEach(element => {
+                    addResult(element.title, element.url);
+                })
+            });
+        });
+    });
+};
+
+
+function clearResults() {
+  const results = document.getElementById('results');
+  results.innerHTML = '';
+}
+
+
+function addResult(title, url) {
+   const par = document.createElement("p");
+
+   const link = document.createElement("a");
+   const linkText = document.createTextNode(title);
+   link.appendChild(linkText);
+   link.href = url;
+
+   par.appendChild(link);
+
+   const results = document.getElementById('results');
+   results.appendChild(par);
+}

+ 18 - 0
static/search.html

@@ -0,0 +1,18 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <title>Search results</title>
+</head>
+<body>
+
+<div id="remote">
+  <form action="/search">
+    <input class="typeahead" type="search" placeholder="Search" name="s">
+    <!--<input type="search" name="s" />-->
+  </form>
+</div>
+
+
+</body>
+</html>