search.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. from nicegui import events, ui
  2. class Search:
  3. def __init__(self) -> None:
  4. ui.add_head_html(r'''
  5. <script>
  6. async function loadSearchData() {
  7. const response = await fetch("/static/search_index.json");
  8. if (!response.ok) {
  9. throw new Error(`HTTP error! status: ${response.status}`);
  10. }
  11. const searchData = await response.json();
  12. const options = {
  13. keys: [
  14. { name: "title", weight: 0.7 },
  15. { name: "content", weight: 0.3 },
  16. ],
  17. tokenize: true, // each word is ranked individually
  18. threshold: 0.3,
  19. location: 0,
  20. distance: 10000,
  21. };
  22. window.fuse = new Fuse(searchData, options);
  23. }
  24. loadSearchData();
  25. </script>
  26. ''')
  27. with ui.dialog() as self.dialog, ui.card().tight().classes('w-[800px] h-[600px]'):
  28. with ui.row().classes('w-full items-center px-4'):
  29. ui.icon('search', size='2em')
  30. ui.input(placeholder='Search documentation', on_change=self.handle_input) \
  31. .classes('flex-grow').props('borderless autofocus')
  32. ui.button('ESC').props('padding="2px 8px" outline size=sm color=grey-5').classes('shadow')
  33. ui.separator()
  34. self.results = ui.element('q-list').classes('w-full').props('separator')
  35. ui.keyboard(self.handle_keypress)
  36. def create_button(self) -> ui.button:
  37. return ui.button(on_click=self.dialog.open).props('flat icon=search color=white')
  38. def handle_keypress(self, e: events.KeyEventArguments) -> None:
  39. if not e.action.keydown:
  40. return
  41. if e.key == '/':
  42. self.dialog.open()
  43. if e.key == 'k' and (e.modifiers.ctrl or e.modifiers.meta):
  44. self.dialog.open()
  45. async def handle_input(self, e: events.ValueChangeEventArguments) -> None:
  46. self.results.clear()
  47. with self.results:
  48. for result in await ui.run_javascript(f'return window.fuse.search("{e.value}").slice(0, 50)'):
  49. href: str = result['item']['url']
  50. with ui.element('q-item').props(f'clickable').on('click', lambda href=href: self.clicked(href)):
  51. with ui.element('q-item-section'):
  52. ui.label(result['item']['title'])
  53. async def clicked(self, url: str) -> None:
  54. await ui.run_javascript(f'''
  55. const url = "{url}"
  56. if (url.startsWith("http"))
  57. window.open(url, "_blank");
  58. else
  59. window.location.href = url;
  60. ''', respond=False)
  61. self.dialog.close()
  62. print(url, flush=True)