main.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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}') \
  20. # .classes('text-lg m-2')
  21. # A more advanced example is using quasar chat_message:
  22. sent = not sent
  23. if sent:
  24. ui.chat_message(text=text,
  25. name=name,
  26. sent=sent,
  27. stamp=datetime.utcnow().isoformat()) \
  28. .classes('w-full')
  29. else:
  30. avatar = "https://cdn.quasar.dev/img/avatar3.jpg"
  31. ui.chat_message(text=text,
  32. name=name,
  33. sent=sent,
  34. avatar=avatar,
  35. stamp=datetime.utcnow().isoformat()) \
  36. .classes('w-full')
  37. await ui.run_javascript(
  38. 'window.scrollTo(0, document.body.scrollHeight)',
  39. respond=False)
  40. @ui.page('/')
  41. async def main(client: Client):
  42. async def send() -> None:
  43. messages.append((name.value, text.value))
  44. text.value = ''
  45. await asyncio.gather(*[update(content) for content in contents]) # run updates concurrently
  46. anchor_style = r'a:link, a:visited {color: inherit !important; text-decoration: none; font-weight: 500}'
  47. ui.add_head_html(f'<style>{anchor_style}</style>')
  48. with ui.footer().classes('bg-white'), ui.column().classes('w-full max-w-3xl mx-auto my-6'):
  49. with ui.row().classes('w-full no-wrap items-center'):
  50. name = ui.input(placeholder='name').props('rounded outlined autofocus input-class=mx-3')
  51. text = ui.input(placeholder='message').props('rounded outlined input-class=mx-3') \
  52. .classes('w-full self-center').on('keydown.enter', send)
  53. ui.markdown('simple chat app built with [NiceGUI](https://nicegui.io)') \
  54. .classes('text-xs self-end mr-8 m-[-1em] text-primary')
  55. await client.connected() # update(...) uses run_javascript which is only possible after connecting
  56. contents.append(ui.column().classes('w-full max-w-2xl mx-auto')) # save ui context for updates
  57. await update(contents[-1]) # ensure all messages are shown after connecting
  58. ui.run()