#!/usr/bin/env python3 from nicegui import ui from contextlib import contextmanager import inspect import sys from typing import Union import docutils.core import re import asyncio from nicegui.elements.markdown import Markdown from nicegui.elements.element import Design, Element from nicegui.globals import page_stack # add docutils css to webpage page_stack[0].head_html += docutils.core.publish_parts('', writer_name='html')['stylesheet'] @contextmanager def example(content: Union[Element, str]): callFrame = inspect.currentframe().f_back.f_back begin = callFrame.f_lineno with ui.row().classes('flex w-full'): if isinstance(content, str): ui.markdown(content).classes('mr-8 w-4/12') else: doc = content.__init__.__doc__ if doc: html = docutils.core.publish_parts(doc, writer_name='html')['html_body'] html = html.replace('
', '
demo paragraph in html
') with example(ui.button): def button_increment(): global button_count button_count += 1 button_result.set_text(f'pressed: {button_count}') button_count = 0 ui.button('Button', on_click=button_increment) button_result = ui.label('pressed: 0') async_button = '''### Button with asynchronous action The button element does also support asynchronous action. ''' with example(async_button): async def async_task(): ui.notify('Asynchronous task started') await asyncio.sleep(5) ui.notify('Asynchronous task finished') ui.button('Start asynchronous task', on_click=async_task) with example(ui.checkbox): ui.checkbox('check me', on_change=lambda e: checkbox_state.set_text(e.value)) with ui.row(): ui.label('the checkbox is:') checkbox_state = ui.label('False') with example(ui.switch): ui.switch('switch me', on_change=lambda e: switch_state.set_text("ON" if e.value else'OFF')) with ui.row(): ui.label('the switch is:') switch_state = ui.label('OFF') with example(ui.slider): slider = ui.slider(min=0, max=100, value=50).props('label') ui.label().bind_text_from(slider.value) with example(ui.input): ui.input( label='Text', placeholder='press ENTER to apply', on_change=lambda e: result.set_text('you typed: ' + e.value), ).classes('w-full') result = ui.label('') with example(ui.number): number_input = ui.number(label='Number', value=3.1415927, format='%.2f') with ui.row(): ui.label('underlying value: ') ui.label().bind_text_from(number_input.value) with example(ui.radio): radio = ui.radio([1, 2, 3], value=1).props('inline') ui.radio({1: 'A', 2: 'B', 3: 'C'}, value=1).props('inline').bind_value(radio.value) with example(ui.toggle): toggle = ui.toggle([1, 2, 3], value=1) ui.toggle({1: 'A', 2: 'B', 3: 'C'}, value=1).bind_value(toggle.value) with example(ui.select): with ui.row(): select = ui.select([1, 2, 3], value=1).props('inline') ui.select({1: 'One', 2: 'Two', 3: 'Three'}, value=1).props('inline').bind_value(select.value) with example(ui.upload): ui.upload(on_upload=lambda files: content.set_text(files)) content = ui.label() with example(ui.plot): from matplotlib import pyplot as plt import numpy as np with ui.plot(figsize=(2.5, 1.8)): x = np.linspace(0.0, 5.0) y = np.cos(2 * np.pi * x) * np.exp(-x) plt.plot(x, y, '-') plt.xlabel('time (s)') plt.ylabel('Damped oscillation') with example(ui.line_plot): lines = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)).with_legend(['sin', 'cos'], loc='upper center', ncol=2) line_updates = ui.timer(0.1, lambda: lines.push([datetime.now()], [ [np.sin(datetime.now().timestamp()) + 0.02 * np.random.randn()], [np.cos(datetime.now().timestamp()) + 0.02 * np.random.randn()], ]), active=False) ui.checkbox('active').bind_value(line_updates.active) with example(ui.log): from datetime import datetime log = ui.log(max_lines=10).classes('h-16') ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5])) with example(ui.scene): with ui.scene(width=200, height=200) as scene: scene.sphere().material('#4488ff') scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1) scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2) with scene.group().move(z=2): box1 = scene.box().move(x=2) scene.box().move(y=2).rotate(0.25, 0.5, 0.75) scene.box(wireframe=True).material('#888888').move(x=2, y=2) scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000') scene.curve([-4, -2, 0], [-4, -1, 0], [-3, -1, 0], [-3, 0, 0]).material('#008800') logo = "https://avatars.githubusercontent.com/u/2843826" scene.texture(logo, [[[0, 3, 0], [3, 3, 0]], [[0, 0, 0], [3, 0, 0]]]).move(1, -2) teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl' scene.stl(teapot).scale(0.2).move(-3, 4) with example(ui.joystick): ui.joystick( color='blue', size=50, on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'), on_end=lambda _: coordinates.set_text('0, 0')) coordinates = ui.label('0, 0') with example(ui.dialog): with ui.dialog() as dialog: with ui.card(): ui.label('Hello world!') ui.button('Close', on_click=dialog.close) ui.button('Open dialog', on_click=dialog.open) with example(ui.menu): choice = ui.label('Try the menu.') with ui.menu() as menu: ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.')) ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.')) ui.menu_separator() ui.menu_item('Close', on_click=menu.close) ui.button('Open menu', on_click=menu.open).props('color=secondary') with example(ui.notify): ui.button('Show notification', on_click=lambda: ui.notify('Some message', close_button='OK')) design = '''### Styling NiceGUI uses the [Quasar Framework](https://quasar.dev/) and hence has its full design power. Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components): Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props. You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method. If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space. All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling. ''' with example(design): ui.radio(['x', 'y', 'z'], value='x').props('inline color=green') ui.button().props('icon=touch_app outline round').classes('shadow-lg ml-14') with example(ui.card): with ui.card(design=Design.plain): ui.image('http://placeimg.com/640/360/nature') with ui.card_section(): ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...') with example(ui.column): with ui.column(): ui.label('label 1') ui.label('label 2') ui.label('label 3') with example(ui.row): with ui.row(): ui.label('label 1') ui.label('label 2') ui.label('label 3') binding = '''### Bindings With help of the [binding](https://pypi.org/project/binding/) package NiceGUI is able to directly bind UI elements to models. Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes. Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property. To define a one-way binding use the `_from` and `_to` variants of these methods. Just pass a property of the model as parameter to these methods to create the binding. ''' with example(binding): class Demo: def __init__(self): self.number = 1 demo = Demo() v = ui.checkbox('visible', value=True) with ui.column().bind_visibility_from(v.value): ui.slider(min=1, max=3).bind_value(demo.number) ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo.number) ui.number().bind_value(demo.number) with example(ui.timer): from datetime import datetime with ui.row().classes('items-center'): clock = ui.label() t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5])) ui.checkbox('active').bind_value(t.active) with ui.row(): def lazy_update(): new_text = datetime.now().strftime('%X.%f')[:-5] if lazy_clock.text[:8] == new_text[:8]: return False lazy_clock.text = new_text lazy_clock = ui.label() ui.timer(interval=0.1, callback=lazy_update) lifecycle = '''### Lifecycle You can run a function or coroutine on startup as a parallel task by passing it to `ui.on_startup`. If NiceGUI is shut down or restarted, the tasks will be automatically canceled (for example when you make a code change). You can also execute cleanup code with `ui.on_shutdown`. ''' with example(lifecycle): with ui.row() as row: ui.label('count:') count_label = ui.label('0') count = 0 async def counter(): global count while True: count_label.text = str(count) count += 1 await row.view.update() await asyncio.sleep(1) ui.on_startup(counter()) with example(ui.page): with ui.page('/other_page') as other: ui.label('Welcome to the other side') ui.link('Back to main page', '/') ui.link('Visit other page', '/other_page') add_route = """###Route Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called. Routed paths must start with a `'/'`. """ with example(add_route): import starlette ui.add_route( starlette.routing.Route( '/new/route', lambda request: starlette.responses.PlainTextResponse('Response') ) ) ui.link('Try the new route!', '/new/route') get_decorator = """###Get decorator Syntactic sugar to add routes. Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/1'`. """ with example(get_decorator): import starlette @ui.get('/another/route/{id}') def produce_plain_response(request): path_param_id = request.path_params['id'] return starlette.responses.PlainTextResponse(f'Response {path_param_id}') ui.link('Try yet another route!', '/another/route/1') ui.run()