Kaynağa Gözat

Merge pull request #903 from zauberzeug/avatar_images

Fixes images inside ui.avatar
Rodja Trappe 2 yıl önce
ebeveyn
işleme
e26a890d47

+ 14 - 13
examples/chat_app/main.py

@@ -1,20 +1,17 @@
 #!/usr/bin/env python3
 from datetime import datetime
 from typing import List, Tuple
+from uuid import uuid4
 
 from nicegui import Client, ui
 
-messages: List[Tuple[str, str, str]] = []
+messages: List[Tuple[str, str, str, str]] = []
 
 
 @ui.refreshable
-async def chat_messages(name_input: ui.input) -> None:
-    for name, text, stamp in messages:
-        ui.chat_message(text=text,
-                        name=name,
-                        stamp=stamp,
-                        avatar=f'https://robohash.org/{name or "anonymous"}?bgset=bg2',
-                        sent=name == name_input.value)
+async def chat_messages(own_id: str) -> None:
+    for user_id, avatar, text, stamp in messages:
+        ui.chat_message(text=text, stamp=stamp, avatar=avatar, sent=own_id == user_id)
     await ui.run_javascript('window.scrollTo(0, document.body.scrollHeight)', respond=False)
 
 
@@ -22,22 +19,26 @@ async def chat_messages(name_input: ui.input) -> None:
 async def main(client: Client):
     def send() -> None:
         stamp = datetime.utcnow().strftime('%X')
-        messages.append((name.value, text.value, stamp))
+        messages.append((user_id, avatar, text.value, stamp))
         text.value = ''
         chat_messages.refresh()
 
+    user_id = str(uuid4())
+    avatar = f'https://robohash.org/{user_id}?bgset=bg2'
+
     anchor_style = r'a:link, a:visited {color: inherit !important; text-decoration: none; font-weight: 500}'
     ui.add_head_html(f'<style>{anchor_style}</style>')
     with ui.footer().classes('bg-white'), ui.column().classes('w-full max-w-3xl mx-auto my-6'):
         with ui.row().classes('w-full no-wrap items-center'):
-            name = ui.input(placeholder='name').props('rounded outlined autofocus input-class=mx-3')
-            text = ui.input(placeholder='message').props('rounded outlined input-class=mx-3') \
-                .classes('w-full self-center').on('keydown.enter', send)
+            with ui.avatar().on('click', lambda: ui.open(main)):
+                ui.image(avatar)
+            text = ui.input(placeholder='message').on('keydown.enter', send) \
+                .props('rounded outlined input-class=mx-3').classes('flex-grow')
         ui.markdown('simple chat app built with [NiceGUI](https://nicegui.io)') \
             .classes('text-xs self-end mr-8 m-[-1em] text-primary')
 
     await client.connected()  # chat_messages(...) uses run_javascript which is only possible after connecting
     with ui.column().classes('w-full max-w-2xl mx-auto items-stretch'):
-        await chat_messages(name_input=name)
+        await chat_messages(user_id)
 
 ui.run()

+ 3 - 2
nicegui/elements/avatar.py

@@ -7,7 +7,7 @@ from ..element import Element
 class Avatar(Element):
 
     def __init__(self,
-                 icon: str = 'none', *,
+                 icon: Optional[str] = None, *,
                  color: Optional[str] = 'primary',
                  text_color: Optional[str] = None,
                  size: Optional[str] = None,
@@ -30,7 +30,8 @@ class Avatar(Element):
         """
         super().__init__('q-avatar')
 
-        self._props['icon'] = icon
+        if icon is not None:
+            self._props['icon'] = icon
         self._props['square'] = square
         self._props['rounded'] = rounded
 

+ 11 - 0
website/more_documentation/avatar_documentation.py

@@ -1,6 +1,17 @@
 from nicegui import ui
 
+from ..documentation_tools import text_demo
+
 
 def main_demo() -> None:
     ui.avatar('favorite_border', text_color='grey-11', square=True)
     ui.avatar('img:https://nicegui.io/logo_square.png', color='blue-2')
+
+
+def more() -> None:
+    @text_demo('Photos', '''
+        To use a photo as an avatar, you can use `ui.image` within `ui.avatar`.
+    ''')
+    def photos() -> None:
+        with ui.avatar():
+            ui.image('https://robohash.org/robot?bgset=bg2')