main.py 2.0 KB

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