search.py 3.2 KB

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