o
    Pf-V                     @   s2  d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZ ddlmZ dd	lmZmZmZ d
dlmZmZmZmZ eedddZG dd dZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZ G dd deZ!G dd  d eZ"dS )!z:
Element
-------

A generic class for creating Elements.

    N)hexlify)OrderedDict)escape)urandom)Path)urlopen)EnvironmentPackageLoaderTemplate   )	_camelify_parse_sizenone_maxnone_minbranca	templates)loaderc                   @   s   e Zd ZdZedZd#ddZdd Zdefd	d
Z	dd Z
dd Zdd Zd#ddZd#ddZd#ddZd$ddZd%ddZdd Zdd  Zd&d!d"ZdS )'ElementaJ  Basic Element object that does nothing.
    Other Elements may inherit from this one.

    Parameters
    ----------
    template : str, default None
        A jinaj2-compatible template string for rendering the element.
        If None, template will be:

        .. code-block:: jinja

            {% for name, element in this._children.items() %}
            {{element.render(**kwargs)}}
            {% endfor %}

        so that all the element's children are rendered.
    template_name : str, default None
        If no template is provided, you can also provide a filename.

    z^{% for name, element in this._children.items() %}
    {{element.render(**kwargs)}}{% endfor %}Nc                 C   sd   d| _ ttd | _t | _d | _|| _|| _	|d ur$t
|| _d S |d ur0t|| _d S d S )Nr      )_namer   r   decode_idr   	_children_parent_template_str_template_namer
   	_templateENVget_template)selftemplatetemplate_name r"   Z/home/deployuser/azure_apps/autowriter/venv/lib/python3.10/site-packages/branca/element.py__init__6   s   zElement.__init__c                 C   s   | j  }|dd |S )zModify object state when pickling the object.

        jinja2 Templates cannot be pickled, so remove the instance attribute
        if it exists. It will be added back when unpickling (see __setstate__).
        r   N)__dict__copypopr   stater"   r"   r#   __getstate__C   s   
zElement.__getstate__r)   c                 C   sL   |d durt |d |d< n|d durt|d |d< | j| dS )z3Re-add _template instance attribute when unpicklingr   Nr   r   )r
   r   r   r%   updater(   r"   r"   r#   __setstate__M   s
   zElement.__setstate__c                 C   s   t | jd | j S )zReturns a string representation of the object.
        This string has to be unique and to be a python and
        javascript-compatible
        variable name.
        _)r   r   r   r   r"   r"   r#   get_nameV   s   zElement.get_namec                 C   s   ddgddggS )zComputes the bounds of the object itself (not including it's children)
        in the form [[lat_min, lon_min], [lat_max, lon_max]]
        Nr"   r.   r"   r"   r#   _get_self_bounds^   s   zElement._get_self_boundsc                 C   s   |   }| j D ]:}| }t|d d |d d t|d d |d d gt|d d |d d t|d d |d d gg}q	|S )z~Computes the bounds of the object and all it's children
        in the form [[lat_min, lon_min], [lat_max, lon_max]].
        r   r   )r0   r   values
get_boundsr   r   )r   boundschildchild_boundsr"   r"   r#   r2   d   s   
zElement.get_boundsc                 C   s    t jdtdd | j|||dS )Add a child.zDMethod `add_children` is deprecated. Please use `add_child` instead.   )
stacklevelnameindex)warningswarnFutureWarning	add_child)r   r4   r:   r;   r"   r"   r#   add_childrenx   s   zElement.add_childrenc                    sd    du r|   |du r|| j < n fdd| j D }|t| |f t|| _| |_| S )r6   Nc                    s   g | ]
}|d   kr|qS )r   r"   ).0itemr:   r"   r#   
<listcomp>   s    z%Element.add_child.<locals>.<listcomp>)r/   r   itemsinsertintr   r   )r   r4   r:   r;   rE   r"   rC   r#   r?      s   
zElement.add_childc                 C   s   |j | ||d | S )zAdd element to a parent.r9   )r?   )r   parentr:   r;   r"   r"   r#   add_to   s   zElement.add_toTc                    sT   |rt }nt}| }| j|d< | j|d<  dkr(| fdd| j D |d< |S ),Returns a dict representation of the object.r:   idr   c                    s$   g | ]\}}||j  d  dfqS )r   depth)to_dict)rA   r:   r4   rM   r"   r#   rD      s    z#Element.to_dict.<locals>.<listcomp>children)r   dictr   r   r   rE   )r   rN   orderedkwargsdict_funoutr"   rM   r#   rO      s   


zElement.to_dictc                 K   s   t j| j|ddfi |S )z,Returns a JSON representation of the object.T)rN   rR   )jsondumpsrO   )r   rN   rS   r"   r"   r#   to_json   s   zElement.to_jsonc                 C   s   | j du r| S | j  S )&Returns the root of the elements tree.N)r   get_rootr.   r"   r"   r#   rZ      s   

zElement.get_rootc                 K   s   | j j| |dS )/Renders the HTML representation of the element.thisrS   )r   render)r   rS   r"   r"   r#   r^      s   zElement.renderc                 K   s\   t |tttfrt|d}n|}|  }|jdi |}||d |r,|	  dS dS )a  Saves an Element into a file.

        Parameters
        ----------
        outfile : str or file object
            The file (or filename) where you want to output the html.
        close_file : bool, default True
            Whether the file has to be closed after write.
        wbutf8Nr"   )

isinstancestrbytesr   openrZ   r^   writeencodeclose)r   outfile
close_filerS   fidroothtmlr"   r"   r#   save   s   
zElement.save)NN)rJ   TrJ   )T)__name__
__module____qualname____doc__r
   r   r$   r*   rQ   r,   r/   r0   r2   r@   r?   rI   rO   rX   rZ   r^   rm   r"   r"   r"   r#   r      s&    

	

	


r   c                       s*   e Zd ZdZdd Zd fdd	Z  ZS )Linkz3An abstract class for embedding a link in the HTML.c                 C   s    | j du rt| j | _ | j S )z2Opens the link and returns the response's content.N)coder   urlreadr.   r"   r"   r#   get_code   s   
zLink.get_coderJ   c                    s$   t  jdddi|}| j|d< |S )rK   rN   rJ   ru   Nr"   )superrO   ru   r   rN   rS   rU   	__class__r"   r#   rO      s   
zLink.to_dictrn   )ro   rp   rq   rr   rw   rO   __classcell__r"   r"   rz   r#   rs      s    rs   c                       *   e Zd ZdZedZd fdd	Z  ZS )JavascriptLinkzCreate a JavascriptLink object based on a url.

    Parameters
    ----------
    url : str
        The url to be linked
    download : bool, default False
        Whether the target document shall be loaded right now.

    z{% if kwargs.get("embedded",False) %}<script>{{this.get_code()}}</script>{% else %}<script src="{{this.url}}"></script>{% endif %}Fc                    0   t    d| _|| _d | _|r|   d S d S )Nr~   rx   r$   r   ru   rt   rw   r   ru   downloadrz   r"   r#   r$         
zJavascriptLink.__init__Fro   rp   rq   rr   r
   r   r$   r|   r"   r"   rz   r#   r~          r~   c                       r}   )CssLinkzCreate a CssLink object based on a url.

    Parameters
    ----------
    url : str
        The url to be linked
    download : bool, default False
        Whether the target document shall be loaded right now.

    z{% if kwargs.get("embedded",False) %}<style>{{this.get_code()}}</style>{% else %}<link rel="stylesheet" href="{{this.url}}"/>{% endif %}Fc                    r   )Nr   r   r   rz   r"   r#   r$     r   zCssLink.__init__r   r   r"   r"   rz   r#   r      r   r   c                       sd   e Zd ZdZedZ					d fdd	Zd fd	d
	Zdd Zdd Z	dd Z
dddZ  ZS )Figurea&  Create a Figure object, to plot things into it.

    Parameters
    ----------
    width : str, default "100%"
        The width of the Figure.
        It may be a percentage or pixel value (like "300px").
    height : str, default None
        The height of the Figure.
        It may be a percentage or a pixel value (like "300px").
    ratio : str, default "60%"
        A percentage defining the aspect ratio of the Figure.
        It will be ignored if height is not None.
    title : str, default None
        Figure title.
    figsize : tuple of two int, default None
        If you're a matplotlib addict, you can overwrite width and
        height. Values will be converted into pixels in using 60 dpi.
        For example figsize=(10, 5) will result in
        width="600px", height="300px".
    z<!DOCTYPE html>
<html>
<head>
{% if this.title %}<title>{{this.title}}</title>{% endif %}    {{this.header.render(**kwargs)}}
</head>
<body>
    {{this.html.render(**kwargs)}}
</body>
<script>
    {{this.script.render(**kwargs)}}
</script>
</html>
100%N60%c                    s   t    d| _t | _t | _t | _| | j_| | j_| | j_|| _|| _	|| _
|| _|d urFtd|d  d | _td|d  d | _	| jjtddd d S )	Nr   <   r   pxr   zE<meta http-equiv="content-type" content="text/html; charset=UTF-8" />	meta_httprC   )rx   r$   r   r   headerrl   scriptr   widthheightratiotitlerb   r?   )r   r   r   r   r   figsizerz   r"   r#   r$   ;  s*   

zFigure.__init__rJ   c                    st   t  jdd|i|}| jjdd|d i||d< | jjdd|d i||d< | jjdd|d i||d< |S )rK   rN   r   r   rl   r   Nr"   )rx   rO   r   rl   r   ry   rz   r"   r#   rO   ]  s
   zFigure.to_dictc                 C      | S rY   r"   r.   r"   r"   r#   rZ   e     zFigure.get_rootc                 K   s4   | j  D ]\}}|jdi | q| jj| |dS )r[   r\   Nr"   )r   rE   r^   r   )r   rS   r:   r4   r"   r"   r#   r^   i  s   zFigure.renderc                 K   sN   t | jdi |}| jdu rdj|| j| jd}|S dj|| j| jd}|S )z*Displays the Figure in a Jupyter notebook.Na  <div style="width:{width};"><div style="position:relative;width:100%;height:0;padding-bottom:{ratio};"><span style="color:#565656">Make this Notebook Trusted to load map: File -> Trust Notebook</span><iframe srcdoc="{html}" style="position:absolute;width:100%;height:100%;left:0;top:0;border:none !important;" allowfullscreen webkitallowfullscreen mozallowfullscreen></iframe></div></div>rl   r   r   z<iframe srcdoc="{html}" width="{width}" height="{height}"style="border:none !important;" "allowfullscreen" "webkitallowfullscreen" "mozallowfullscreen"></iframe>rl   r   r   r"   )r   r^   r   formatr   r   r   rS   rl   iframer"   r"   r#   _repr_html_o  s   
zFigure._repr_html_皙?c           
      C   s   d| }d| }|d | | }|d | | }|||  }|||  }|dd|   }|dd|   }t dd|  dd|  dd|  dd|  dd}	| |	 |	S )a  Creates a div child subplot in a matplotlib.figure.add_subplot style.

        Parameters
        ----------
        x : int
            The number of rows in the grid.
        y : int
            The number of columns in the grid.
        n : int
            The cell number in the grid, counted from 1 to x*y.

        Example:
        >>> fig.add_subplot(3, 2, 5)
        # Create a div in the 5th cell of a 3rows x 2columns
        grid(bottom-left corner).
        g      ?r   g       @absoluteg      Y@%)positionr   r   lefttop)Divr?   )
r   xynmarginr   r   r   r   divr"   r"   r#   add_subplot  s"   
zFigure.add_subplot)r   Nr   NNrn   )r   )ro   rp   rq   rr   r
   r   r$   rO   rZ   r^   r   r   r|   r"   r"   rz   r#   r     s     "r   c                       s*   e Zd ZdZedZd fdd	Z  ZS )Htmla  Create an HTML div object for embedding data.

    Parameters
    ----------
    data : str
        The HTML data to be embedded.
    script : bool
        If True, data will be embedded without escaping
        (suitable for embedding html-ready code)
    width : int or str, default '100%'
        The width of the output div element.
        Ex: 120 , '80%'
    height : int or str, default '100%'
        The height of the output div element.
        Ex: 120 , '80%'
    z<div id="{{this.get_name()}}" style="width: {{this.width[0]}}{{this.width[1]}}; height: {{this.height[0]}}{{this.height[1]}};">{% if this.script %}{{this.data}}{% else %}{{this.data|e}}{% endif %}</div>Fr   c                    s4   t    d| _|| _|| _t|| _t|| _d S )Nr   )rx   r$   r   r   datar   r   r   )r   r   r   r   r   rz   r"   r#   r$     s   

zHtml.__init__)Fr   r   r   r"   r"   rz   r#   r     s    r   c                       sL   e Zd ZdZedZ					d fdd	Zdd	 Zd
d Zdd Z	  Z
S )r   a  Create a Div to be embedded in a Figure.

    Parameters
    ----------
    width: int or str, default '100%'
        The width of the div in pixels (int) or percentage (str).
    height: int or str, default '100%'
        The height of the div in pixels (int) or percentage (str).
    left: int or str, default '0%'
        The left-position of the div in pixels (int) or percentage (str).
    top: int or str, default '0%'
        The top-position of the div in pixels (int) or percentage (str).
    position: str, default 'relative'
        The position policy of the div.
        Usual values are 'relative', 'absolute', 'fixed', 'static'.
    a  {% macro header(this, kwargs) %}<style> #{{this.get_name()}} {
        position : {{this.position}};
        width : {{this.width[0]}}{{this.width[1]}};
        height: {{this.height[0]}}{{this.height[1]}};
        left: {{this.left[0]}}{{this.left[1]}};
        top: {{this.top[0]}}{{this.top[1]}};
    </style>{% endmacro %}{% macro html(this, kwargs) %}<div id="{{this.get_name()}}">{{this.html.render(**kwargs)}}</div>{% endmacro %}r   0%relativec                    sx   t t|   d| _t|| _t|| _t|| _t|| _|| _	t
 | _t
d| _t
 | _| | j_| | j_| | j_d S )Nr   zY{% for name, element in this._children.items() %}{{element.render(**kwargs)}}{% endfor %})rx   r   r$   r   r   r   r   r   r   r   r   r   rl   r   r   )r   r   r   r   r   r   rz   r"   r#   r$     s   



zDiv.__init__c                 C   r   r   r"   r.   r"   r"   r#   rZ     r   zDiv.get_rootc                 K   s8  | j }t|tsJ d| j D ]\}}|jdi | q| jj D ]\}}|jj||d q$| jj D ]\}}|jj||d q7| j	j
jdd}|dur`|jjt|| ||  d | j	j
jdd}|dur||jjt|| ||  d | j	j
jdd}|dur|jjt|| ||  d dS dS )r[   8You cannot render this Element if it is not in a Figure.rC   r   Nrl   r   r"   )r   ra   r   r   rE   r^   r   r?   r   r   moduler%   getr   r/   rl   )r   rS   figurer:   elementr   rl   r   r"   r"   r#   r^     s(   "z
Div.renderc                 K   sH   | j du r| t  | j jdi |}d| _ |S | j jdi |}|S )z'Displays the Div in a Jupyter notebook.Nr"   )r   rI   r   r   )r   rS   rU   r"   r"   r#   r   -  s   
zDiv._repr_html_)r   r   r   r   r   )ro   rp   rq   rr   r
   r   r$   rZ   r^   r   r|   r"   r"   rz   r#   r     s    r   c                       s.   e Zd ZdZd	 fdd	Z fddZ  ZS )
IFrameaM  Create a Figure object, to plot things into it.

    Parameters
    ----------
    html : str, default None
        Eventual HTML code that you want to put in the frame.
    width : str, default "100%"
        The width of the Figure.
        It may be a percentage or pixel value (like "300px").
    height : str, default None
        The height of the Figure.
        It may be a percentage or a pixel value (like "300px").
    ratio : str, default "60%"
        A percentage defining the aspect ratio of the Figure.
        It will be ignored if height is not None.
    figsize : tuple of two int, default None
        If you're a matplotlib addict, you can overwrite width and
        height. Values will be converted into pixels in using 60 dpi.
        For example figsize=(10, 5) will result in
        width="600px", height="300px".
    Nr   r   c                    s   t    d| _|| _|| _|| _|d ur+td|d  d | _td|d  d | _t|ts5t|tr>| 	t
| d S |d urI| 	| d S d S )Nr   r   r   r   r   )rx   r$   r   r   r   r   rb   ra   rc   r?   r   )r   rl   r   r   r   r   rz   r"   r#   r$   O  s   
zIFrame.__init__c                    sf   t  jdi |}dt|dd }| jdu r'dj|| j| j	d}|S dj|| j| jd}|S )	r[   z$data:text/html;charset=utf-8;base64,r`   Nz<div style="width:{width};"><div style="position:relative;width:100%;height:0;padding-bottom:{ratio};"><iframe src="{html}" style="position:absolute;width:100%;height:100%;left:0;top:0;border:none !important;"></iframe></div></div>r   z`<iframe src="{html}" width="{width}" style="border:none !important;" height="{height}"></iframe>r   r"   )
rx   r^   base64	b64encoderf   r   r   r   r   r   r   rz   r"   r#   r^   _  s"   
zIFrame.render)Nr   Nr   N)ro   rp   rq   rr   r$   r^   r|   r"   r"   rz   r#   r   8  s    r   c                       s0   e Zd ZdZedZ fddZdd Z  ZS )MacroElementa  This is a parent class for Elements defined by a macro template.
    To compute your own element, all you have to do is:

    * To inherit from this class
    * Overwrite the '_name' attribute
    * Overwrite the '_template' attribute with something of the form::

        {% macro header(this, kwargs) %}
            ...
        {% endmacro %}

        {% macro html(this, kwargs) %}
            ...
        {% endmacro %}

        {% macro script(this, kwargs) %}
            ...
        {% endmacro %}

     c                    s   t    d| _d S )Nr   )rx   r$   r   r.   rz   r"   r#   r$     s   

zMacroElement.__init__c                 K   s   |   }t|tsJ d| jjjdd}|dur)|jjt	|| || 
 d | jjjdd}|durE|jjt	|| || 
 d | jjjdd}|dura|jjt	|| || 
 d | j D ]\}}|jdi | qfdS )r[   r   r   NrC   rl   r   r"   )rZ   ra   r   r   r   r%   r   r   r?   r   r/   rl   r   r   rE   r^   )r   rS   r   r   rl   r   r:   r   r"   r"   r#   r^     s    zMacroElement.render)	ro   rp   rq   rr   r
   r   r$   r^   r|   r"   r"   rz   r#   r   y  s
    r   )#rr   r   rV   r<   binasciir   collectionsr   rl   r   osr   pathlibr   urllib.requestr   jinja2r   r	   r
   	utilitiesr   r   r   r   r   r   rs   r~   r   r   r   r   r   r   r"   r"   r"   r#   <module>   s0     1 "jA