main.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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, str]] = []
  6. @ui.refreshable
  7. async def chat_messages(name_input: ui.input) -> None:
  8. for name, text, stamp in messages:
  9. ui.chat_message(text=text,
  10. name=name,
  11. stamp=stamp,
  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. stamp = datetime.utcnow().strftime('%X')
  19. messages.append((name.value, text.value, stamp))
  20. text.value = ''
  21. chat_messages.refresh()
  22. anchor_style = r'a:link, a:visited {color: inherit !important; text-decoration: none; font-weight: 500}'
  23. ui.add_head_html(f'<style>{anchor_style}</style>')
  24. with ui.footer().classes('bg-white'), ui.column().classes('w-full max-w-3xl mx-auto my-6'):
  25. with ui.row().classes('w-full no-wrap items-center'):
  26. name = ui.input(placeholder='name').props('rounded outlined autofocus input-class=mx-3')
  27. text = ui.input(placeholder='message').props('rounded outlined input-class=mx-3') \
  28. .classes('w-full self-center').on('keydown.enter', send)
  29. ui.markdown('simple chat app built with [NiceGUI](https://nicegui.io)') \
  30. .classes('text-xs self-end mr-8 m-[-1em] text-primary')
  31. await client.connected() # chat_messages(...) uses run_javascript which is only possible after connecting
  32. with ui.column().classes('w-full max-w-2xl mx-auto items-stretch'):
  33. await chat_messages(name_input=name)
  34. ui.run()