main.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #!/usr/bin/env python3
  2. from datetime import datetime
  3. from typing import List, Tuple
  4. from nicegui import Client, ui
  5. messages: List[Tuple[str, str]] = []
  6. @ui.refreshable
  7. async def chat_messages(name_input: ui.input) -> None:
  8. for name, text in messages:
  9. ui.chat_message(text=text,
  10. name=name,
  11. stamp=datetime.utcnow().strftime('%X'),
  12. avatar=f'https://robohash.org/{name or "anonymous"}?bgset=bg2',
  13. sent=name == name_input.value)
  14. await ui.run_javascript('window.scrollTo(0, document.body.scrollHeight)', respond=False)
  15. @ui.page('/')
  16. async def main(client: Client):
  17. def send() -> None:
  18. messages.append((name.value, text.value))
  19. text.value = ''
  20. chat_messages.refresh()
  21. anchor_style = r'a:link, a:visited {color: inherit !important; text-decoration: none; font-weight: 500}'
  22. ui.add_head_html(f'<style>{anchor_style}</style>')
  23. with ui.footer().classes('bg-white'), ui.column().classes('w-full max-w-3xl mx-auto my-6'):
  24. with ui.row().classes('w-full no-wrap items-center'):
  25. name = ui.input(placeholder='name').props('rounded outlined autofocus input-class=mx-3')
  26. text = ui.input(placeholder='message').props('rounded outlined input-class=mx-3') \
  27. .classes('w-full self-center').on('keydown.enter', send)
  28. ui.markdown('simple chat app built with [NiceGUI](https://nicegui.io)') \
  29. .classes('text-xs self-end mr-8 m-[-1em] text-primary')
  30. await client.connected() # chat_messages(...) uses run_javascript which is only possible after connecting
  31. with ui.column().classes('w-full max-w-2xl mx-auto items-stretch'):
  32. await chat_messages(name_input=name)
  33. ui.run()