U
    Zf}                     @   s  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZddlmZ ddl	m
Z
 dZdZdZdZd	Zd
ZdZdZdZdZdZdZdd Zdd Zdd Zdd Zdd Zd4ddZdd Zdd  Zd!d" Zd#d$ Z d%d& Z!d'd( Z"d)d* Z#d5d,d-Z$d.d/ Z%d6d0d1Z&d2d3 Z'dS )7    N   )
r_keywords)reorder_propsa  #' @export
{funcname} <- function({default_argtext}{wildcards}) {{
    {wildcard_declaration}
    props <- list({default_paramtext}{wildcards})
    if (length(props) > 0) {{
        props <- props[!vapply(props, is.null, logical(1))]
    }}
    component <- list(
        props = props,
        type = '{name}',
        namespace = '{project_shortname}',
        propNames = c({prop_names}{wildcard_names}),
        package = '{package_name}'
        )

    structure(component, class = c('dash_component', 'list'))
}}
z?.{rpkgname}_js_metadata <- function() {{
deps_metadata <- list(a,  `{dep_name}` = structure(list(name = "{dep_name}",
version = "{project_ver}", src = list(href = NULL,
file = "deps"), meta = NULL,
script = {script_name},
stylesheet = {css_name}, head = NULL, attachment = NULL, package = "{rpkgname}",
all_files = FALSE{async_or_dynamic}), class = "html_dependency")a>  `{project_shortname}` = structure(list(name = "{project_shortname}",
version = "{project_ver}", src = list(href = NULL,
file = "deps"), meta = NULL,
script = {script_name},
stylesheet = {css_name}, head = NULL, attachment = NULL, package = "{rpkgname}",
all_files = FALSE{async_or_dynamic}), class = "html_dependency")z)
return(deps_metadata)
}
z% Auto-generated: do not edit by hand
\name{{{funcname}}}

\alias{{{funcname}}}

\title{{{name} component}}

\description{{
{description}
}}

\usage{{
{funcname}({default_argtext})
}}

\arguments{{
{item_text}
}}

\value{{{value_text}}}

a~  Package: {package_name}
Title: {package_title}
Version: {package_version}
Description: {package_description}
Depends: R (>= 3.0.2){package_depends}
Imports: {package_imports}
Suggests: {package_suggests}{package_rauthors}
License: {package_license}{package_copyright}
URL: {package_url}
BugReports: {package_issues}
Encoding: UTF-8
LazyData: true{vignette_builder}
KeepSource: true
a  # ignore JS config files/folders
node_modules/
coverage/
src/
lib/
.babelrc
.builderrc
.eslintrc
.npmignore
.editorconfig
.eslintignore
.prettierrc
.circleci
.github

# demo folder has special meaning in R
# this should hopefully make it still
# allow for the possibility to make R demos
demo/.*\.js
demo/.*\.html
demo/.*\.css

# ignore Python files/folders
setup.py
usage.py
setup.py
requirements.txt
MANIFEST.in
CHANGELOG.md
test/
# CRAN has weird LICENSE requirements
LICENSE.txt
^.*\.Rproj$
^\.Rproj\.user$
z% Auto-generated: do not edit by hand
\docType{{package}}
\name{{{package_name}-package}}
\alias{{{package_name}}}
\title{{{pkg_help_title}}}
\description{{
{pkg_help_description}
}}
\author{{
\strong{{Maintainer}}: {maintainer}
}}
a+  
dash_assert_valid_wildcards <- function (attrib = list("data", "aria"), ...)
{
    args <- list(...)
    validation_results <- lapply(names(args), function(x) {
        grepl(paste0("^(", paste0(attrib, collapse="|"), ")-[a-zA-Z0-9_-]+$"),
            x)
    })
    if (FALSE %in% validation_results) {
        stop(sprintf("The following props are not valid in this component: '%s'",
            paste(names(args)[grepl(FALSE, unlist(validation_results))],
                collapse = ", ")), call. = FALSE)
    }
    else {
        return(args)
    }
}
zQ
    wildcard_names = names(dash_assert_valid_wildcards(attrib = list({}), ...))
z9


\item{{...}}{{wildcards allowed have the form: `{}`}}
c                 C   s&  t |}t|d}t| }d}d}d}d}	d}
d}tdd |D rjt|}d}t|dd}d}d	d	d |D }|d d  D ]F}|
ds|d
kr|| q|tkr|| td||  q|
d	dd |D 7 }
|	d	dd |D 7 }	tjt|| | |
|||	||||d
S )Nprops c                 s   s   | ]}| d V  qdS -*Nendswith.0key r   M/tmp/pip-unpacked-wheel-47crqvv_/dash/development/_r_components_generation.py	<genexpr>   s     z(generate_class_string.<locals>.<genexpr>, ...r	   z, wildcard_names, c                 s   s(   | ] }d |kr|dkrd |V  qdS )*)setProps'{}'Nformatr   pr   r   r   r      s      r   zSWARNING: prop "{}" in component "{}" is an R keyword - REMOVED FROM THE R COMPONENTc                 s   s   | ]}d  |V  qdS z{}=NULLNr   r   r   r   r   r      s     c                 s   s*   | ]"}|d krd |nd |V  qdS )childrenz{0}={0}z{}=childrenNr   r   r   r   r   r      s   )
funcnamenamedefault_argtext	wildcardswildcard_declarationdefault_paramtextproject_shortname
prop_nameswildcard_namespackage_name)snake_case_to_camel_caser   listkeysanyget_wildcards_rwildcard_templater   replacejoinr   remover   warningswarnr_component_stringformat_fn_name)r   r   r#   prefixr&   	prop_keysr    r!   r%   r"   r   accepted_wildcardsr$   itemr   r   r   generate_class_string   s^    



 
r8   c                 C   s|  t jdt  t|}t|dg t|dg  }| d}t	|}t
j|d}g }g }t|dkrtt|D ]}	||	 }
|
d }t|
}d|kr|d	d }n
d
|}d|krd|}d}nd|}d}|tj|||||||dg7 }d|}qtndt|dkrh|d }	|	d }t|	}d|krDd|}d}nd|}d}tj||||||d}d||tg}|S )aC  Dynamically generate R function to supply JavaScript and CSS dependency
    information required by the dash package for R.

    Parameters
    ----------
    project_shortname = component library name, in snake case

    Returns
    -------
    function_string = complete R function code to provide component features
    r   Z_js_distZ	_css_distversion)rpkgnamer   Zrelative_package_pathZdash_.{}cssr   NULL)dep_nameproject_verr:   r#   script_namecss_nameasync_or_dynamicz,
)r#   r@   r:   rA   rB   rC   r   )syspathinsertosgetcwd	importlibimport_modulegetattrgetr'   frame_open_templater   lenrangeget_async_typesplitframe_element_templater.   frame_body_templateframe_close_template)pkg_datar#   modZalldistr@   r:   Zfunction_frame_openZfunction_frameZfunction_frame_bodydepZcurr_depZrpprC   r?   rB   rA   function_stringr   r   r   generate_js_metadata   sl    







	rY   c                 C   sX   d}|   D ]F}|dkr| | }t|ts:d| }nt| }d||}q|S )Nr   )asyncZdynamicr   z	, {} = {})r)   
isinstanceboolr   lowerstrupper)rW   rC   r   keyvalr   r   r   rP   V  s    
rP   c                 C   s   | dkr|S d | |S )Nr   z
\{}{{
{}}}r   )tagcoder   r   r   wrape  s    rc   c                    s  t ||   d }d}d}d}d}	d}
t }tdd |D rPt|}	d}|dd D ](}|dsz|tksz|d	kr\|| q\|d
dd |D 7 }|dfdd|D 7 }t	
dd|}t	
dd|}d|kr|dd  }|dkr||7 }|t|	7 }tjd|}t|ddd6}|tj | tj|ddd||
|ddd W 5 Q R X |dk	rd|kr|d} fdd|D pdgd }d}|rd| kr|td t|d!rd!nd|d 7 }t|d"dd}||d  W 5 Q R X dS )#a  Write R documentation file (.Rd) given component name and properties.

    Parameters
    ----------
    name = the name of the Dash component for which a help file is generated
    props = the properties of the component
    description = the component's description, inserted into help file header
    prefix = the DashR library prefix (optional, can be a blank string)
    rpkg_data = package metadata (optional)

    Returns
    -------
    writes an R help file to the man directory for the generated R package
    z.Rdr   zQnamed list of JSON elements corresponding to React.js properties and their valuesc                 s   s   | ]}| d V  qdS r   r
   r   r   r   r   r     s     z"write_help_file.<locals>.<genexpr>r   Nr	   r   r   c                 s   s   | ]}d  |V  qdS r   r   r   r   r   r   r     s     z

c                 3   s0   | ](}d  |t | d  | d V  qdS )z\item{{{}}}{{{}{}}}typedescriptionN)r   print_r_typer   r   r   r   r     s     
z(?<!\\)%z\%z**Example Usage**r   manwutf-8encoding<   F)widthbreak_long_words
 )r   r   r   	item_text
value_textre   Z
r_examplesc                    s   g | ]}| d  kr|qS )r   )rL   )r   e)r   r   r   
<listcomp>  s      z#write_help_file.<locals>.<listcomp>rb   ZexamplesZdontrunza+)r3   r(   r)   r*   r+   r   r   r/   r.   resubrQ   rstripwildcard_help_templater   rG   rE   openwritehelp_stringtextwrapfillr-   rL   rc   )r   r   re   r4   	rpkg_data	file_namer    r   rq   r6   rr   r5   r7   	file_pathfexZthe_exresultfar   )r   r   r   write_help_filek  sh    


  

r   c              	   C   s   t |d}t| |||| d}t| |||}t|| d }tjd|}	t|	ddd}
|
| |
| W 5 Q R X t	d
| d S )	Nr   %# AUTO GENERATED FILE - DO NOT EDIT

.RRrh   ri   rj   zGenerated {})r   r   r8   r3   rG   rE   r.   ry   rz   printr   )r   r   re   r#   r4   r~   import_stringZclass_stringr   r   r   r   r   r   write_class_file  s    

r   c                 C   s  t | |d}d}tjds&td tjd|}t|ddd}|| |r\|t W 5 Q R X tjdr|t	
d td t|D ]z\}}}	|	D ]j}
tj|
d }|d	krqtjtjd
tj||}tj|st| t	tj||
| qqdS )zWrite an internal (not exported) R function to return all JS
    dependencies as required by dash.

    Parameters
    ----------
    project_shortname = hyphenated string, e.g. dash-html-components

    Returns
    -------
    )rU   r#   
internal.Rr   rh   ri   rj   z	inst/depsr   )z.pyz.pycz.jsonz
inst/deps/N)rY   rG   rE   existsmakedirsr.   ry   rz   wildcard_helpershutilrmtreewalksplitextrelpathcopy)rU   r#   has_wildcardsrX   r   r   r   Zrel_dirname_	filenamesfilename	extensionZtarget_dirnamer   r   r   write_js_metadata  s:     



 
r   c           $      C   s  t |}d}	d}
| d}|dk	r||dr@|d| dd}|dr^|d| dd}|drd|dd}	n| dd}| dd}| d	d
}|rd|d  }tdd|}|r|d }tdd|}|r|d }tdd|}d| kr"| d dd}nd}tdtj	d d| krL| dd}nd}tdtj	d | d}|
dd }|
dd dd }|
dd }|ddd }| d| d}d|krtdtj	d td |dk	r|drd|dd}
nd |||}
tjd!s@tjd"s@| d#d}n*| d#dd$ }tjd!sjtd"d! d%}d}|
d|
d }tt|}|r|D ]}|d&|7 }qtjd'rd(}d)|krd*|kr|d+7 }|d}nd}tjd,|d- }t| || td.d/d0d1$}|| || || W 5 Q R X td2d/d0d1}|t W 5 Q R X tj|||||
|||||	|||d3} td4d/d0d1}!|!|  W 5 Q R X |dk	r
|dr
tj||d|d||d5}"t|d6d0d1}#|#|" W 5 Q R X dS )7zGenerate documents for R package creation.

    Parameters
    ----------
    pkg_data
    rpkg_data
    project_shortname
    export_string
    package_depends
    package_imports
    package_suggests
    has_wildcards

    Returns
    -------
    r   r   Npkg_help_titlere   pkg_help_descriptionZpkg_copyrightz
Copyright: {}r9   z0.0.1r   ,z
(,(?![ ]))ZbugsurlzGWarning: a URL for bug reports was not provided. Empty string inserted.)fileZhomepagez@Warning: a homepage URL was not provided. Empty string inserted.authorz <r   r   rp      
maintainer<zError, aborting R package generation: R packages require a properly formatted author field or installation will fail. Please include an email address enclosed within < > brackets in package.json. Zpkg_authorsz
Authors@R: {}zD
Authors@R: person("{}", "{}", role = c("aut", "cre"), email = "{}")LICENSEzLICENSE.txtlicensez + file LICENSEr   z
import({})
Z	vignettesz
VignetteBuilder: knitrZknitrZ	rmarkdownz, knitr, rmarkdownrg   z-package.RdZ	NAMESPACEzw+ri   rj   z.Rbuildignore)r&   package_titlepackage_descriptionpackage_versionpackage_rauthorspackage_dependspackage_importspackage_suggestspackage_licensepackage_copyrightpackage_urlpackage_issuesvignette_builderZDESCRIPTION)r&   r   r   lib_namer   rh   )r'   rL   r   striplstripru   rv   r   rD   stderrrQ   rsplitexitrG   rE   isfilesymlinkfilterr\   r   r.   r   ry   rz   rbuild_ignore_stringdescription_templatepkghelp_stub)$rU   r~   r#   export_stringr   r   r   r   r&   r   r   r   r   r   r   r   r   Zpackage_authorZpackage_author_nameZpackage_author_emailZpackage_author_fnZpackage_author_lnr   r   r   Zpackages_stringZrpackage_listZrpackager   Zpkghelp_stub_pathr   f2Zdescription_stringZf3ZpkghelpZf4r   r   r   generate_rpkg  s    

 

 









  



r   c                 C   s.   |  d}|d ddd |dd  D  S )Nr   r   r   c                 s   s   | ]}|  V  qd S )N)
capitalize)r   rh   r   r   r   r     s     z+snake_case_to_camel_case.<locals>.<genexpr>r   )rQ   r.   )Z
namestringsr   r   r   r'     s    
r'   c                 C   s,   | r| t | S t |d  |dd   S )Nr   r   )r'   r]   )r4   r   r   r   r   r3     s    r3   c	              	   K   sT   t ||}
d}| D ]"}tdd |d D rd} q:qt||| |
|||| d S )NFc                 s   s   | ]}| d V  qdS r   r
   r   r   r   r   r     s     z#generate_exports.<locals>.<genexpr>r   T)make_namespace_exportsvaluesr*   r   )r#   
componentsmetadatarU   r~   r4   r   r   r   kwargsr   r   Zcomponent_datar   r   r   generate_exports  s     
r   c              
      s  d}| D ]6}| dst|tkrt|dkr|d |7 }qg }ddg fdd| D  }g }td	D ]*}| d
rl||krl|tjd	|g7 }ql|D ]}t|ddd}|	 }	t
jdd|	t
jd}	|	dddd}	t
dd|	}	t
dd|	}	t|	d }
t|	|
k r>t|	}
t
dd|	}	t
dd|	}	qt
d|	}|D ]0}|d }|d dkrN||krN|| qNW 5 Q R X q|ddd  |D 7 }|S )!Nr   r	   )r   r   zexport({}{})
zutils.Rr   c                    s   g | ]}d   |qS )z{}{}.Rr   )r   	componentr4   r   r   rt      s    z*make_namespace_exports.<locals>.<listcomp>r   r   rri   rj   z#.*$)flagsro   rp   z'([^'\\]|\\'|\\[^'])*'z''z"([^"\\]|\\"|\\[^"])*"z""r   z\(([^()]|\(\))*\)z()z\{([^{}]|\{\})*\}r<   z6([^A-Za-z0-9._]|^)([A-Za-z0-9._]+)\s*(=|<-)\s*functionr   r;   c                 s   s   | ]}d  |V  qdS )z
export({})Nr   )r   functionr   r   r   r   L  s     z)make_namespace_exports.<locals>.<genexpr>)r   r^   r   r   rG   listdirrE   r.   ry   readru   rv   Mr-   rN   findallappend)r   r4   r   r   Z	rfilelistZomitlistZfnlistscriptrfiler   Zprev_lenmatchesmatchfnr   r   r   r     sN    

r   c                    sp    fdd}t dd dd dd dd dd d	d d
d dd  fdd fdd fdd fdd||dS )z8Mapping from the PropTypes js type object to the R type.c                
      s>   d ddd  d D d ddd  d  D S )	Nz lists containing elements {}.
{}r   c                 s   s   | ]}d  |V  qdS )r   Nr   r   tr   r   r   r   U  s     z;get_r_prop_types.<locals>.shape_or_exact.<locals>.<genexpr>valuez+Those elements have the following types:
{}ro   c              	   s   s0   | ](\}}t |||d  |ddddV  qdS )requiredre   r   r   )	prop_nametype_objectr   re   
indent_numN)create_prop_docstring_rrL   )r   r   propr   r   r   r   W  s   
)r   r.   itemsr   r   r   r   shape_or_exactS  s    

z(get_r_prop_types.<locals>.shape_or_exactc                   S   s   dS )Nzunnamed listr   r   r   r   r   <lambda>e      z"get_r_prop_types.<locals>.<lambda>c                   S   s   dS )Nlogicalr   r   r   r   r   r   f  r   c                   S   s   dS )Nnumericr   r   r   r   r   r   g  r   c                   S   s   dS )N	characterr   r   r   r   r   r   h  r   c                   S   s   dS )Nz
named listr   r   r   r   r   r   i  r   c                   S   s   dS )Nz9logical | numeric | character | named list | unnamed listr   r   r   r   r   r   j  r   c                   S   s   dS )Nzdash componentr   r   r   r   r   r   k  r   c                   S   s   dS )Nz8a list of or a singular dash component, string or numberr   r   r   r   r   r   l  r   c                      s   d ddd  d D S )Nza value equal to: {}r   c                 s   s    | ]}d  t|d V  qdS )r<   r   N)r   r^   r   r   r   r   r   o  s     5get_r_prop_types.<locals>.<lambda>.<locals>.<genexpr>r   r   r.   r   r   r   r   r   n  s   c                      s   d ddd  d D S )Nr<   z | c                 s   s(   | ] }t |d krdt |V  qdS )r   r<   N
get_r_typer   )r   ZsubTyper   r   r   r   s  s   r   r   r   r   r   r   r   r   r  s   
c                      s*   dt  d dkr$dt  d nd S )Nr(   r   r   z of {}sr   r   r   r   r   r   z  s
    c                      s   d t d S )Nz.list with named elements and values of type {}r   )r   r   r   r   r   r   r     s   
)arrayr\   numberstringobjectr*   elementnodeenumunionZarrayOfZobjectOfshapeexact)dict)r   r   r   r   r   get_r_prop_typesP  s"    


	
r   Fc                 C   sP   | d }t | d}d| kr"| d s2| dddkr6dS ||krL||  }|S dS )aP  
    Convert JS types to R types for the component definition
    Parameters
    ----------
    type_object: dict
        react-docgen-generated prop type dictionary
    is_flow_type: bool
    indent_num: int
        Number of indents to use for the docstring for the prop
    Returns
    -------
    str
        Python type string
    r   r   Zcomputedrd   r   r   )r   rL   )r   is_flow_typer   Zjs_type_nameZjs_to_r_typesZ	prop_typer   r   r   r     s    

r   c                 C   s   t |  }|r|d7 }|S )Nz. )r   r   )ZtypedataZ
typestringr   r   r   rf     s    rf   c                 C   sz   t |||d d}d| }d|kr>dj|| |||r6dnddS d	j|| |rTd
|nd|dkrhd|nd|rrdnddS )aS  
    Create the Dash component prop docstring
    Parameters
    ----------
    prop_name: str
        Name of the Dash component prop
    type_object: dict
        react-docgen-generated prop type dictionary
    required: bool
        Component is required?
    description: str
        Dash component description
    indent_num: int
        Number of indents to use for the context block
        (creates 2 spaces for every indent)
    is_flow_type: bool
        Does the prop use Flow types? Otherwise, uses PropTypes
    Returns
    -------
    str
        Dash component prop docstring
    r   )r   r   r   z  ro   z^{indent_spacing}- {name} ({is_required}): {description}. {name} has the following type: {type}r   optional)indent_spacingr   rd   re   Zis_requiredz;{indent_spacing}- {name} ({type}{is_required}){description}z{}; r   z: {}r   )r   r   r   re   r   r   Zr_type_namer   r   r   r   r     s,      


r   c                 C   s,   d}|d dd | D 7 }|dkr(d}|S )Nr   r   c                 s   s"   | ]}| d rd|V  qdS )r	   r   N)r   r   r   r   r   r   r     s     
 z"get_wildcards_r.<locals>.<genexpr>r>   )r.   )r5   r    r   r   r   r+     s
    r+   )NN)Fr   )F)(rG   rD   r   rI   r|   ru   r0   Z_all_keywordsr   Z_py_components_generationr   r2   rM   rR   rS   rT   r{   r   r   r   r   r,   rx   r8   rY   rP   rc   r   r   r   r   r'   r3   r   r   r   r   rf   r   r+   r   r   r   r   <module>   sR   $Aba  
7 B	$?=
	 
2