
    	eU                       d dl mZ d dlmZmZmZmZmZmZm	Z	m
Z
 d dlZddlmZ ddlmZmZmZmZ ddlmZmZ ddlmZ dd	lmZ dd
lmZmZ ddlmZ ddl m!Z!m"Z" ddl#m$Z$m%Z%  G d de          Z& G d de          Z'dS )    )annotations)AnyClassVarDictListOptionalTupleTypeUnionN   )Margin)Column	ListPanelRowTabs)PaneBasepanel)Image)Markdown)
LayoutableViewable   )CompositeWidget)ButtonToggle)
StaticText	TextInputc                      e Zd ZU dZ ej        d          Z ej        dddgd          Z ej	        dd	
          Z
 ej        dd
          Z ej        dd
          Z edd
          Z ej        dd
          Z ej        dd
          Z ej        i d
          ZeZded<   	 	 	 	 d(d) fdZd*d$Zd+d'Z xZS ),ChatRowz
    The ChatRow widget allows displaying a message adjacent to an icon and name.

    :Example:

    >>> ChatRow(name="You", value="Welcome!", show_name=True, align="start")
    zThe objects to display)docstartendz@
        Whether to show the name at the start or end of the row)defaultobjectsr    Na  
        The type of Panel object or callable to use if an item in value is not
        already rendered as a Panel object; if None, uses the
        pn.panel function to render a displayable Panel object.
        If the item is not serializable, will fall back to pn.panel.r#   r    z2
        The icon to display adjacent to the valueFz)
        Whether a user liked the messager   z
        Allows to create additional space around the component. May
        be specified as a two-tuple of the form (vertical, horizontal)
        or a four-tuple (top, right, bottom, left).Tz-
        Whether to show the name of the userz(
        Whether to show the like buttonzX
        Dictionary of CSS properties and values to apply
        message to the bubble.ClassVar[Type[ListPanel]]_composite_typevalue	List[Any]iconstr	show_namebool	show_likestylesDict[str, str]c                    ddddd}|r|                     |           t          |pi           }|                    dd            |                    dd            |                     ddd	d
d           d|vrd|d<   | _         t	                      j        d(||d| t          ddd
          }	|rt          |fi |	 _        nd  _        t           fd j	        D             d
d|d _
        t          dddd|           _         j                             dd            j        j                             j        d            fdt"          j        D             }
|
                    dd          }t'          |t(                    r|d         }|r j         j
         j        f}n j
         j        f}|dk    r|d d d         }t          d |d
f!          }t+          |i |}|ra|dk    rd"}nd#}t-           j        ||dfd$d%d&d '           _         j        dk    rt           j        |fi |}nt          | j        fi |}nd  _        |g j        d d <   d S ))Nautoz(rgba(0, 0, 0, 0.15) 1.95px 1.95px 2.6px;z0.5em)
overflow-x
overflow-yz
box-shadowpadding
backgroundcolorz50%boldz1.2emcenter)border-radiuszfont-weight	font-sizez
text-alignblack)r(   r*   0   )widthheightalignc                :    g | ]}                     |          S  )_serialize_obj).0objselfs     5lib/python3.11/site-packages/panel/widgets/chatbox.py
<listcomp>z$ChatRow.__init__.<locals>.<listcomp>k   s'    ===3d!!#&&===       )r@   marginr/      ♡   r"   )namer>   r?   r@   visiblelikedT)r(   bidirectionalr(   c                Z    i | ]'}|d vr!t          |          |t          |          (S ))rN   r?   rK   r/   getattrrD   prF   s     rG   
<dictcomp>z$ChatRow.__init__.<locals>.<dictcomp>y   sM     
 
 
>>>a  , wtQ -,,rI   r@   r!   r   fixed)sizing_moder@   )   r[   r   )r[   r   r[   r\   z0.88emgrey)r;   r7   )objectrK   r@   r/   rZ   rB   )updatedictpop_bubble_stylessuper__init__r   _iconr   r(   _bubbler   _likelinkparamwatch_update_liker   get
isinstancetupler   r   rN   _name
align_name
_composite)rF   r(   r*   r,   r.   r/   paramsbubble_stylesicon_stylesicon_paramsmessage_layouthorizontal_alignrow_objectscontainer_paramsrowname_margin	__class__s   `               rG   rd   zChatRow.__init__A   sO    ! D	
 
  	)  (((FLb**d+++&&&!&%$&	 	
 	
 	
 },,*1M,'+:u4::6::: Bh??? 	t33{33DJJDJ ====$*=== 	
 
 
 b5)
 
 

 	
G4@@@
t0':::
 
 
 
%
 
 
 *--gw??&.. 	3/2 	5:t|TZ@KK<4Ku$$%ddd+K#X.
 
 
 ;3"233 	5((//!y"'1%-??#  DJ '))TZAA0@AAS$*AA0@AADJ!UrI   rE   r   returnr   c                   t          |t                    r|S dg}d| j                            d          i}	 | j        t          | j        t                    r | j        pt          |||          }n|                     |          }n"# t          $ r t          |||          }Y nw xY w|j	        d|_	        d|j
        vr|j
                            ddi           |S )	z6
        Convert an object to a Panel object.
        z8p { margin-block-start: 0.2em; margin-block-end: 0.2em;}r7   N)stylesheetsr/   r(   stretch_widthzoverflow-wrapz
break-word)rm   r   rb   rl   default_message_callable
issubclassr   _panel
ValueErrorrZ   r/   r_   )rF   rE   r   text_styles	panel_objs        rG   rC   zChatRow._serialize_obj   s!    c8$$ 	JQR 3 7 7 @ @A
	Q,4
-x9 94 ET:Df[  		 !999DD	 	Q 	Q 	QsKPPPIII	Q  ($3I!)"222##_l$CDDDs   AB B*)B*eventparam.parameterized.Eventc                `    |j         | _        | j        rd|j        _        dS d|j        _        dS )zA
        Update the like button when the user clicks it.
        u   ❤️rL   N)newrP   rE   rN   )rF   r   s     rG   rk   zChatRow._update_like   s1     Y
: 	#%EINNN"EINNNrI   )NTTN)
r(   r)   r*   r+   r,   r-   r.   r-   r/   r0   )rE   r   r}   r   )r   r   )__name__
__module____qualname____doc__ri   r   r(   Selectorrp   Callabler   Stringr*   BooleanrP   r   rK   r,   r.   r   r/   r   r'   __annotations__rd   rC   rk   __classcell__r|   s   @rG   r   r      s          EJ7888E'59I PC D D DJ  .u~d AH  I  I  I 5< +5 6 6 6D EM% ., - - -E VA $7 8 8 8F
 d 10 1 1 1I d 1+ , , ,I UZ )" # # #F 28O7777
 !%a# a# a# a# a# a# a#F   <# # # # # # # #rI   r   c                  t    e Zd ZU dZ ej        g ed          Z ej        dd          Z	 ej
        dd          Z ej
        d	d
          Z ej
        d	d          Z ej        dd          Z ej        i d          Z ej        i d          Z ej        ddd          Z ej        egd          Z ej
        dd          ZeZded<    fdZdJdKdZdLd#ZdMd$ZdNd*ZedOd,            Z dPd0Z!dQd7Z"dRdSd:Z#dRdTd<Z$e%dUd>            Z&dVd?Z'dWdBZ(dXdDZ)dYdZdFZ*d[dGZ+d\dHZ,d]dIZ- xZ.S )^ChatBoxa5  
    The ChatBox widget displays a conversation between multiple users
    composed of users' icons, names, messages, and likes.

    Reference: https://panel.holoviz.org/reference/widgets/ChatBox.html

    :Example:

    >>> ChatBox(value=[{"You": "Hello!"}, {"Bot": ["How may I help?", "I'm a bot."]}])
    z
        List of messages as dicts, mapping user to message(s),
        e.g. `[{'You': ['Welcome!', 'Good bye!']}]` The message(s) can be
        any Python object that can be rendered by Panel.)r#   	item_typer    NzyName of the primary user (the one who inputs messages);
        the first key found in value will be used if unspecified.r%   TzK
        Whether to allow the primary user to interactively enter messages.FzJ
        Whether to allow the primary user to interactively like messages.z
        Whether to display messages in ascending time order.  If true,
        the latest messages and message_input_widgets will be at the
        bottom of the chat box. Otherwise, they will be at the top.a  
        The type of Panel object to use for items in value if they are
        not already rendered as a Panel object; if None, uses the
        pn.panel function to render a displayable Panel object.
        If the item is not serializable, will fall back to pn.panel.
        zi
        Dictionary mapping name of messages to their icons,
        e.g. `[{'You': 'path/to/icon.png'}]`z]
        Dictionary mapping name of messages to their colors, e.g.
        `[{'You': 'red'}]`)r   h  zW
        Base hue of the message bubbles if message_colors is not specified for a user.)r#   boundsr    zf
        List of widgets to use for message input. Multiple widgets will
        be nested under tabs.zD
        Whether to show chat participant's names below the message.r&   r'   c                2    |                     d          r|                     d          r	d|vrd |d<    t                      j        di |  fdt          j        D             }|                                }|                    dd j        rdndd	           t           j	         d
did           _
        t          di | _        t          dddddd           _                              j        d            j         _         j        r                       j                   _        ng  _         j	        r j
        gng }|                     j                    j        r|                    d j                   n|                     j                    j        r                     ||           ni  _        d  _        | j        d d <    j                             j        d            j                            d           d S )Nr>   r?   rZ   c                Z    i | ]'}|d vt          |          |t          |          (S ))rN   r/   rK   rS   rU   s     rG   rW   z$ChatBox.__init__.<locals>.<dictcomp>  sJ     
 
 
444q9I9I9U wtQ9U9U9UrI   r2   columnzcolumn-reverse)r4   r3   zflex-direction)r/   r;   z1.5emr9   )r(   r/   r@   zScroll to latestrY   s   #   r   )rN   r@   rZ   r>   r?   rK   clicksr(   rB   )rl   rc   rd   r   ri   copyr_   	ascendingr   rN   _chat_titler   	_chat_logr   _scroll_button_add_scroll_callbackmessage_hue_current_hue_generate_default_hsl_default_colorsappendinsertallow_input_attach_input_message_inputs_send_buttonrq   rj   _refresh_logtrigger)rF   rr   layoutchat_layoutbox_objectsr|   s   `    rG   rd   zChatBox.__init__  s|   ::g 	)6::h#7#7 	)MQW<W<W$(F=!""6"""
 
 
 
%
 
 

 kkmm$$.2n"R((BR  	 	
 	
 	
 &Y.)
 
 

  ..+..$#
 
 
 	!!$"5x@@@ , 	&#'#=#=d>O#P#PD  #%D ,0I=t'((24>***> 	4q$"56666t2333 	%{F3333#%D  $D( 	
*G444 	
7#####rI   r   hue
int | None	incrementintr}   	List[str]c                ^    ||z  }|dk    r|dz  }|| _         d| ddfd| ddfd| ddfgS )Nr   zhsl(z, 45%, 50%)whitez, 30%, 55%)z, 15%, 60%))r   )rF   r   r   s      rG   r   zChatBox._generate_default_hslE  sk    y993JC %C$$$g.$C$$$g.$C$$$g.
 	
rI   rE   r   whatr+   c                ^    d}| j         r|dz  }n|dz  } |j        ddd| j        ii||i d S )Nz
            const outerColumn = document.querySelector(".bk-Column")
            const column = outerColumn.shadowRoot.querySelector(".bk-Column")
        z'
column.scrollTop = column.scrollHeightz(
column.scrollTop = -column.scrollHeightargschat_logrB   )r   
jscallbackr   )rF   rE   r   codes       rG   r   zChatBox._add_scroll_callbackQ  sn     > 	@>>DD??D 	
 	
dn-	
Tl	
 	
 	
 	
 	
rI   c           	     n    dD ]1}t          ||t          | |                      | j        |fi ||i 2dS )zg
        Link the disabled and loading attributes of the chat box to the
        given object.
        )disabledloadingN)setattrrT   rh   )rF   rE   keys      rG   _link_disabled_loadingzChatBox._link_disabled_loading`  sZ    
 + 	) 	)CCgdC00111DIc((c3Z((((	) 	)rI   r   r   r   r0   Nonec                   i | _         | j        D ]>}|j        p|j        j        }t          |t                    r
 |            }|| j         |<   ?t          ddddd          | _        | j        	                    | j
                   |                                }|                    dd           |                    d	d           d|d
<   t                      }| j                                         D ]\  }}|                     |           d|_        t          |t"                    r6|j                            | j
        d           |                     |d           | j                                        }	|                     |	           t-          ||	fi |}
|                    ||
f           t1          | j                   dk    r|d         }| j        r|                    |           dS |                    d|           dS )z;
        Attach the input widgets to the chat box.
        Sendr#   r   d   r   )rN   button_typerZ   	max_widthr?   r>   Nr?   rZ   r(   r   r   )r   message_input_widgetsrN   r|   r   rm   typer   r   on_click_enter_messager   ra   r   itemsr   rZ   r   ri   rj   r   cloner   r   lenr   r   )rF   r   r   message_input_widgetr   
row_layoutinput_itemsmessage_input_namemessage_inputsend_buttonmessage_rows              rG   r   zChatBox._attach_inputi  s3     "$($> 	= 	= &+V/C/M/VC.55 >';';'='=$(<D %%"!'
 
 
 	""4#6777[[]]
w%%%x&&&$3
=!ff151E1K1K1M1M 	B 	B-''666(7M% -33 B#))$*=wGGG))-AAA+1133K''444m[GGJGGK 2K@AAAAt#$$))%a.K> 	/{+++++q+.....rI   dict_c                :    t          t          |                     S )z@
        Get the name of the user who sent the message.
        )nextiter)r   s    rG   	_get_namezChatBox._get_name  s    
 DKK   rI   user_message Dict[str, Union[List[Any], Any]]Tuple[str, str]c                    t          |          dk    r|                     |          }||         }n+d|v rd|v r|d         }|d         }nt          d|           ||fS )zB
        Separate the user and message from a dictionary.
        r   rolecontentzExpected a dictionary with one key-value pair, e.g. {'User': 'Message'} or two key-value pairs with 'role' and 'content' as keys, e.g. {'role': 'User', 'content': 'Message'}, but got )r   r   r   )rF   r   usermessage_contentss       rG   _separate_user_messagezChatBox._separate_user_message  s     |!!>>,//D+D1|##	\(A(A'D+I6* (	* *   %%%rI   r   r   Union[Any, List[Any]]r,   r-   r   c                   | j         4| j        r&|                     | j        d                   | _         nd| _         || j        v r,| j        |         }t	          |t
                    r|n|df\  }}n| j        rbt          | j                  dk    r!| 	                    | j
        d          | _        | j                                        \  }}||f| j        |<   n"|| j         k    rd\  }}nd\  }}||f| j        |<   | j                            |d          }|| j         k    }|rd	nd
}	t	          |t                    s|g}t          ||||| j        |	| j        rd	nd
| j        ||dd	  	        }
|
S )z/
        Instantiate a ChatRow object.
        Nr   Your<   X   )r   )zrgb(99, 139, 226)r   )zrgb(235, 235, 235)r<   r!   r"   1em)r6   r7   r:   )	rN   r(   r*   r,   r.   r@   rp   r   r/   )primary_namer(   r   message_colorsrm   rn   r   r   r   r   r   ra   message_iconsrl   listr   allow_likesr   r   )rF   r   r   r,   colorsr6   r7   message_iconis_other_userr@   r   s              rG   _instantiate_message_rowz ChatBox._instantiate_message_row  s    $z *$(NN4:a=$A$A!!$)! 4&&&(.F$VU33J&'9J J  	<4'((A--'+'A'A% (B ( ($ !% 4 8 8 : :J)3U(;D%%t((($B!
EE$C!
E)3U(;D% )--dD99 11(3e*D11 	2 01"&"&.;wwe%)%B(!& 
 
 
 rI   r   #Optional[param.parameterized.Event]c                   |j         }g }d}t          |          D ]\  }}|                     |          \  }}| j        r||k    nd}	|}|                     |||	          }
t          | j        j                  |k    r.| j        j        |         }|j        |
j        k    r|j	        |
_	        |
                    |
           || j        _        dS )zP
        Refresh the chat log for complete replacement of all messages.
        NF)r   	enumerater   
show_namesr   r   r   r$   r(   rP   r   )rF   r   user_messagesmessage_rowsprevious_userir   r   r   r,   r   original_message_rows               rG   r   zChatBox._refresh_log  s     	(77 	- 	-OA|%)%@%@%N%N"D" 26K--eI M77&	 K
 4>)**Q..'+~'=a'@$'-1BBB(<(BK%,,,,!-rI   _c                    | j                                         D ]$}t          |d          rd|_        |j        }|r n%dS | j        pd}|                     ||i           dS )zU
        Append the message from the text input when the user presses Enter.
        value_input Nr   )r   valueshasattrr  r(   r   r   )rF   r  r   messager   s        rG   r   zChatBox._enter_message  s     "188:: 		 		M }m44 /,.)#)G  F )ET7O$$$$$rI   List[ChatRow]c                    | j         j        S )z4
        Returns a list of ChatRow objects.
        )r   r$   rF   s    rG   rowszChatBox.rows  s    
 ~%%rI   c                    t          |t                    st          d|           | j                            |           | j                            d           dS )z
        Appends a message to the chat log.

        Arguments
        ---------
        user_message (dict): Dictionary mapping user to message.
        zExpected a dictionary, but got r(   N)rm   r`   r   r(   r   ri   r   )rF   r   s     rG   r   zChatBox.append&  s`     ,-- 	OM|MMNNN
,'''
7#####rI   r   &List[Dict[str, Union[List[Any], Any]]]c                n    | j                             |           | j                            d           dS )z
        Extends the chat log with new users' messages.

        Arguments
        ---------
        user_messages (list): List of user messages to add.
        r(   N)r(   extendri   r   )rF   r   s     rG   r  zChatBox.extend3  s6     	
-(((
7#####rI   indexc                p    | j                             ||           | j                            d           dS )z
        Inserts a message into the chat log at the given index.

        Arguments
        ---------
        index (int): Index to insert the message at.
        user_message (dict): Dictionary mapping user to message.
        r(   N)r(   r   ri   r   rF   r  r   s      rG   r   zChatBox.insert>  s8     	
%...
7#####rI   rX   c                n    | j                             |          }| j                            d           |S )a  
        Pops the last message from the chat log.

        Arguments
        ---------
        index (int): Index of the message to pop; defaults to the last message.

        Returns
        -------
        user_message (dict): Dictionary mapping user to message.
        r(   )r(   ra   ri   r   )rF   r  r(   s      rG   ra   zChatBox.popJ  s2     
u%%
7###rI   c                N    || j         |<   | j                            d           dS )z
        Replaces a message in the chat log at the given index.

        Arguments
        ---------
        index (int): Index to replace the message at.
        user_message (dict): Dictionary mapping user to message.
        r(   N)r(   ri   r   r  s      rG   replacezChatBox.replaceZ  s,     )
5
7#####rI   c                    g | _         dS )z&
        Clears the chat log.
        Nr   r  s    rG   clearzChatBox.clearf  s     


rI   c                *    t          | j                  S N)r   r(   r  s    rG   __len__zChatBox.__len__l  s    4:rI   )r   )r   r   r   r   r}   r   )rE   r   r   r+   )rE   r   )r   r   r   r0   r}   r   )r   r0   r}   r+   )r   r   r}   r   )r   r+   r   r   r,   r-   r}   r   r  )r   r   r}   r   )r  r   r}   r   )r}   r
  )r   r   r}   r   )r   r  r}   r   )r  r   r   r   r}   r   )rX   )r  r   r}   r   )r  r   r   r   )r}   r   )r}   r   )/r   r   r   r   ri   r   r   r(   r   r   r   r   r   r   r   r   r   r   Integerr   r   r   r   r   r'   r   rd   r   r   r   r   staticmethodr   r   r   r   r   propertyr  r   r  r   ra   r  r  r  r   r   s   @rG   r   r      sh        	 	 EJrT 8< = = =E
  5< 3E F F FL  %- 3N O O OK  %- 4M N N NK e 2G H H HI
  .u~d A       EJr 00 1 1 1M  UZ 1   N  %-X DZ [ [ [K 'EJ	{ A! " " " t 2G H H HJ 28O7777<$ <$ <$ <$ <$|

 

 

 

 


 
 
 
) ) ) )./ ./ ./ ./` ! ! ! \!& & & &,9 9 9 9v. . . . .8% % % % %$ & & & X&$ $ $ $	$ 	$ 	$ 	$
$ 
$ 
$ 
$     
$ 
$ 
$ 
$          rI   r   )(
__future__r   typingr   r   r   r   r   r	   r
   r   ri   _paramr   r   r   r   r   r   	pane.baser   r   r   
pane.imager   pane.markupr   viewabler   r   baser   buttonr   r   inputr   r   r   r   rB   rI   rG   <module>r*     s   " " " " " "                                      2 1 1 1 1 1 1 1       " " " " " " + + + + + + + + ! ! ! ! ! ! " " " " " " " " ( ( ( ( ( ( ( (t# t# t# t# t#o t# t# t#n` ` ` ` `o ` ` ` ` `rI   