main.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536
  1. #!/usr/bin/env python3
  2. from nicegui import ui
  3. messages = []
  4. @ui.page('/')
  5. def main():
  6. def send() -> None:
  7. messages.append((name.value, text.value))
  8. text.value = ''
  9. anchor_style = r'a:link, a:visited {color: inherit !important; text-decoration: none; font-weight: 500}'
  10. ui.add_head_html(f'<style>{anchor_style}</style>')
  11. content = ui.column().classes('w-full max-w-2xl mx-auto')
  12. with ui.footer().classes('bg-white'), ui.column().classes('w-full max-w-3xl mx-auto my-6'):
  13. with ui.row().classes('w-full no-wrap items-center'):
  14. name = ui.input(placeholder='name').props('rounded outlined autofocus input-class=mx-3')
  15. text = ui.input(placeholder='message').props('rounded outlined input-class=mx-3') \
  16. .classes('w-full self-center').on('keydown.enter', send)
  17. ui.markdown('simple chat app built with [NiceGUI](https://nicegui.io)') \
  18. .classes('text-xs self-end mr-8 m-[-1em] text-primary')
  19. async def update_messages() -> None:
  20. if len(messages) != len(content.default_slot.children):
  21. content.clear()
  22. with content:
  23. for name, text in messages:
  24. ui.markdown(f'**{name or "someone"}:** {text}').classes('text-lg m-2')
  25. await ui.run_javascript(f'window.scrollTo(0, document.body.scrollHeight)', respond=False)
  26. ui.timer(0.1, update_messages)
  27. ui.run()