Ejemplo n.º 1
0
def create_examples(examples_data):
    examples = []
    for example in examples_data:
        examples += [
            html.H3(example['param_name'].title()),
            dcc.Markdown(example['description']),
            ComponentBlock(example['code']),
            html.Hr()
        ]
    return examples
Ejemplo n.º 2
0
        dcc.Markdown('''
    ```
    >>> import dash_core_components as dcc
    >>> print(dcc.__version__)
    {}
    ```
    '''.replace('    ', '').format(dcc.__version__),
                     style=styles.code_container),
        html.Hr(),
        html.H3(dcc.Link('Dropdown', href='/dash-core-components/dropdown')),
        ComponentBlock('''import dash_core_components as dcc

dcc.Dropdown(
    options=[
        {'label': 'New York City', 'value': 'NYC'},
        {'label': 'Montréal', 'value': 'MTL'},
        {'label': 'San Francisco', 'value': 'SF'}
    ],
    value='MTL'
)''',
                       style=styles.code_container),
        ComponentBlock('''import dash_core_components as dcc

dcc.Dropdown(
    options=[
        {'label': 'New York City', 'value': 'NYC'},
        {'label': 'Montréal', 'value': 'MTL'},
        {'label': 'San Francisco', 'value': 'SF'}
    ],
    multi=True,
    value="MTL"
    dcc.Markdown(examples['dropdown'][0], style=styles.code_container),
    html.Div(examples['dropdown'][1],
             className='example-container',
             style={'overflow-x': 'initial'}),
    html.Hr(),
    html.H3('Multi-Value Dropdown'),
    dcc.Markdown(
        "A dropdown component with the `multi` property set to `True` \
                  will allow the user to select more than one value \
                  at a time."),
    ComponentBlock('''import dash_core_components as dcc

dcc.Dropdown(
    options=[
        {'label': 'New York City', 'value': 'NYC'},
        {'label': 'Montreal', 'value': 'MTL'},
        {'label': 'San Francisco', 'value': 'SF'}
    ],
    value=['MTL', 'NYC'],
    multi=True
)''',
                   style=styles.code_container),
    html.Hr(),
    html.H3('Disable Search'),
    dcc.Markdown(
        "The `searchable` property is set to `True` by default on all \
            `Dropdown` components. To prevent searching the dropdown \
            value, just set the `searchable` property to `False`. \
            Try searching for 'New York' on this dropdown below and compare \
            it to the other dropdowns on the page to see the difference."),
    ComponentBlock('''import dash_core_components as dcc
Ejemplo n.º 4
0
def generate_component_example(component_name,
                               library_name,
                               library_short,
                               description='',
                               params=None,
                               style=None,
                               default_id=True,
                               datafile=None,
                               library_imports=None,
                               setup_code='',
                               component_wrap=None,
                               iframe_info=None):
    '''Generate an example for a component, with hyperlinks to the
    appropriate component-specific pages.

    :param (str) component_name: The name of the component as it is
    defined within the package.
    :param (str) library_name: The full name of the library (e.g.,
    dash_bio).
    :param (str) library_short: The short name of the library, used in an
    import statement (i.e., import library_name as library_short).
    :param (str) description: A short string describing the component.
    :param (dict) params: A dictionary that contains the parameters
    assigned to the component that is to be displayed as a live
    example; the keys correspond to the parameter names.
    :param (dict) style: A dictionary that contains any style
    options. The keys correspond to the style parameter names.
    :param (bool) default_id: Whether or not to assign a default ID to
    the component in the example code.
    :param (string) datafile: The name of the data file, if any, used
    for the component. This file should be present in the folder
    specified by the variable DATA_LOCATION_PREFIX.
    :param (list[list]) library_imports: A list for which each element
    is a list with two elements: the first element should be the full
    name of the library, and the second element should be the short
    name of the library. Contains all of the libraries necessary for
    running the example code (e.g., pandas).
    :param (str) setup_code: Any additional code required before
    rendering the component (e.g., parsing a data file).
    :param (str) component_wrap: A string that will wrap the component
    (e.g., if the component needs to be an argument for a dcc.Graph).
    The location of the component code is represented by an
    underscore (_).
    :param (dict) iframe_info: The URL and, if applicable, the height
    and width of the iframe containing the example.
    :rtype (list[obj]): A list containing the entire section for the
    component in question, including the code block, component demo,
    description, and hyperlinks to the component-specific page.
    '''

    # location of all sample data
    DATA_LOCATION_PREFIX = '''https://raw.githubusercontent.com/plotly/\
dash-bio/master/tests/dashbio_demos/sample_data/'''

    if library_imports is None:
        library_imports = []

    # parameters for initial declaration of component
    paramstring = '\n  '

    if default_id is True:
        paramstring += 'id=\'my-{}-{}\', '.format(library_short,
                                                  component_name.lower())

    if params is not None:
        for key in params.keys():
            paramstring += '{}={}, '.format(key, params[key])

    # style options
    if style is not None:
        styleString = 'style={\n  '
        for key in style.keys():
            styleString += '  \'{}\': \'{}\', '.format(key, str(style[key]))

        # remove comma and space following the last style option
        styleString = styleString[:-2]

        styleString += '\n  }, '
        paramstring += styleString

    # loading data if necessary
    if datafile is not None:
        library_imports.append(['urllib.request', 'urlreq'])

        # only decode for python 3
        decode_string = ''
        if sys.version_info >= (3, 0):
            decode_string = '.decode(\"utf-8\")'

        # add data location
        setup_code = '''\ndata = urlreq.urlopen(\"{}{}\").read(){}
'''.format(DATA_LOCATION_PREFIX, datafile['name'], decode_string) + setup_code

        # declare data in component initialization if necessary
        if 'parameter' in datafile.keys():
            paramstring += '{}=data, '.format(datafile['parameter'])

    # pretty-print param string (spaces for indentation)
    paramstring = paramstring.replace(', ', ',\n  ')

    # remove the characters following the final parameter
    # (',\n  '), and add unindented newline at end
    if (len(paramstring) > 4):
        paramstring = paramstring[:-4] + '\n'
    # if no params were supplied, remove all newlines
    else:
        paramstring = ''

    # format component string
    component_string = '{}.{}({})'.format(library_short, component_name,
                                          paramstring)
    # wrap component if necessary
    if component_wrap is not None:
        component_string = component_wrap.replace('_', component_string)

    # add imports
    imports_string = ''
    for library in library_imports:
        if library[0] != library[1]:
            imports_string += 'import {} as {}\n'.format(
                library[0], library[1])
        else:
            imports_string += 'import {}\n'.format(library[0])

    # change urllib package if necessary (due to Python version)
    if sys.version_info < (3, 0):
        imports_string = imports_string.replace('urllib.request', 'urllib2')

    # full code
    example_string = '''import {} as {}
{}
{}
component = {}
'''.format(library_name, library_short, imports_string, setup_code,
           component_string)

    # load the iframe if that is where the app is
    if iframe_info is not None:
        component_demo = IframeComponentBlock(example_string, **iframe_info)
    else:
        component_demo = ComponentBlock(example_string)

    # full component section
    return [
        html.Hr(),
        html.H3(dcc.Link(component_name,
                         href='/{}/{}'.format(library_name.replace('_', '-'),
                                              component_name.lower())),
                id=component_name.replace(' ', '-').lower()),
        dcc.Markdown(s(description)), component_demo,
        html.Br(),
        dcc.Link('More {} Examples and Reference'.format(component_name),
                 href='/{}/{}'.format(library_name.replace('_', '-'),
                                      component_name.lower()))
    ]
Ejemplo n.º 5
0
    html.Hr(),
    html.H3('Default Boolean Switch'),
    html.P("An example of a default boolean switch without \
            any extra properties."),
    dcc.Markdown(examples['boolean-switch'][0], style=styles.code_container),
    html.Div(examples['boolean-switch'][1],
             className='example-container',
             style={'overflow-x': 'initial'}),
    html.Hr(),
    html.H3('Color'),
    dcc.Markdown("Set the color of the boolean switch with \
    `color=#<hex_value>`."),
    ComponentBlock('''import dash_daq as daq

daq.BooleanSwitch(
  on=True,
  color="#9B51E0",
)''',
                   style=styles.code_container),
    html.Hr(),
    html.H3('Label'),
    dcc.Markdown(
        "Set the label and label position using the `label` and `labelPosition` \
    properties."),
    ComponentBlock('''import dash_daq as daq

daq.BooleanSwitch(
  on=True,
  label="Label",
  labelPosition="top"
)''',
def generate_code_container(
        component_name,
        library_name, library_short,
        default_id=True,
        description='',
        props=None,
        style=None
):
    '''
    Generates a section for the component specified, including pretty-printed 
    code containing top-level props (not dicts) and style dictionaries.

    :param (str) component_name: The component name in camelcase with the first 
                                 letter also capitalized. 
    :param (str) library_name: Name of the library the component belongs to,
                               with words separated by dashes ('-'). 
    :param (str) library_short: A short name for the library (e.g., "dcc"). 
    :param (bool) default_id: Whether or not to generate an id for the
                              component. Can be useful for custom styling. 
    :param (dict) props: A dictionary of the component's keys and the values 
                         corresponding to those keys. 
    :param (dict) style: A dictionary that determines the styling of the 
                         component, if 'style' is a property of that component.
                         (Will fail if this is not true.) 
    '''
    propString = '\n  '
    if(default_id):
        propString += 'id=\'my-{}-{}\', '.format(
            library_short,
            component_name.lower())

    if props is not None:
        for key in props.keys():
            propString += '{}={}, '.format(key, props[key])

    if style is not None:
        styleString = 'style={\n  '
        for key in style.keys():
            styleString += '  \'{}\': \'{}\', '.format(
                key,
                str(style[key])
            )
        styleString = styleString[:-2]
        styleString += '\n  }, '
        propString += styleString
 
    propString = propString.replace(', ', ',\n  ')

    if(len(propString) > 4): 
        propString = propString[:-4] + '\n'
    else:
        propString = ''

    example_string = '''import {} as {}

{}.{}({})'''.format(library_name.replace('-', '_'),
                    library_short,
                    library_short, 
                    component_name,
                    propString)
    return [

        html.Hr(),

        html.H3(dcc.Link(component_name,
                         href='/{}/{}'.format(
                             library_name,
                             component_name.lower())),
                id=component_name.replace(' ', '-').lower()),
        
        dcc.Markdown(description),
        
        ComponentBlock(
            example_string
        ),

        html.Br(), 
        
        dcc.Link('More {} Examples and Reference'.format(component_name),
                 href='/{}/{}'.format(
                     library_name,
                     component_name.lower()))
    ]