main.py 1.8 KB

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