main.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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[ui.column] = []
  8. async def update(content: ui.column) -> None:
  9. # Note: Messages should come from a database
  10. sent = False
  11. # 'sent' should be determined based on the current user
  12. # which requires session/user auth - outside of scope
  13. # of this example
  14. # For now we just alternate for every new message
  15. content.clear()
  16. with content: # use the context of each client to update their ui
  17. for name, text in messages:
  18. # A simple way to show a message:
  19. # ui.markdown(f'**{name or "someone"}:** {text}').classes('text-lg m-2')
  20. # A more advanced example is using quasar chat_message:
  21. sent = not sent
  22. ui.chat_message(text=text,
  23. name=name,
  24. sent=sent,
  25. avatar="https://cdn.quasar.dev/img/avatar2.jpg",
  26. stamp=datetime.utcnow().isoformat()).classes('w-full')
  27. await ui.run_javascript('window.scrollTo(0, document.body.scrollHeight)', respond=False)
  28. @ui.page('/')
  29. async def main(client: Client):
  30. async def send() -> None:
  31. messages.append((name.value, text.value))
  32. text.value = ''
  33. await asyncio.gather(*[update(content) for content in contents]) # run updates concurrently
  34. anchor_style = r'a:link, a:visited {color: inherit !important; text-decoration: none; font-weight: 500}'
  35. ui.add_head_html(f'<style>{anchor_style}</style>')
  36. with ui.footer().classes('bg-white'), ui.column().classes('w-full max-w-3xl mx-auto my-6'):
  37. with ui.row().classes('w-full no-wrap items-center'):
  38. name = ui.input(placeholder='name').props('rounded outlined autofocus input-class=mx-3')
  39. text = ui.input(placeholder='message').props('rounded outlined input-class=mx-3') \
  40. .classes('w-full self-center').on('keydown.enter', send)
  41. ui.markdown('simple chat app built with [NiceGUI](https://nicegui.io)') \
  42. .classes('text-xs self-end mr-8 m-[-1em] text-primary')
  43. await client.connected() # update(...) uses run_javascript which is only possible after connecting
  44. contents.append(ui.column().classes('w-full max-w-2xl mx-auto')) # save ui context for updates
  45. await update(contents[-1]) # ensure all messages are shown after connecting
  46. ui.run()