lca_index
int64 0
223
| idx
stringlengths 7
11
| line_type
stringclasses 6
values | ground_truth
stringlengths 2
35
| completions
sequencelengths 3
1.16k
| prefix
stringlengths 298
32.8k
| postfix
stringlengths 0
28.6k
| repo
stringclasses 34
values |
---|---|---|---|---|---|---|---|
47 | 47-145-11 | non_informative | markdown | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui. | ('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-162-11 | inproject | html | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui. | (content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-178-15 | inproject | label | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui. | ('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-178-30 | inproject | classes | [
"bind_text",
"bind_text_from",
"bind_text_to",
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"page",
"parent_view",
"props",
"set_text",
"style",
"text",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!'). | ('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-185-15 | inproject | html | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui. | (content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-185-29 | inproject | style | [
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"content",
"page",
"parent_view",
"props",
"set_content",
"style",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content). | ('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-187-20 | infile | interactive_image | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui. | ):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-201-19 | random | table | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui. | ({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-215-18 | commited | update | [
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"options",
"page",
"parent_view",
"props",
"style",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table. | ()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-219-20 | infile | chart | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui. | ):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-230-11 | inproject | classes | [
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"options",
"page",
"parent_view",
"props",
"style",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}). | ('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-234-18 | commited | update | [
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"options",
"page",
"parent_view",
"props",
"style",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart. | ()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-236-11 | commited | button | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui. | ('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-249-20 | infile | line_plot | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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. | ):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-262-22 | inproject | push | [
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"close",
"fig",
"lines",
"page",
"parent_view",
"props",
"push",
"push_counter",
"slice",
"style",
"tooltip",
"update",
"update_every",
"view",
"visible",
"with_legend",
"x",
"Y",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__enter__",
"__eq__",
"__exit__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot. | ([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-264-26 | infile | timer | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui. | (0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-265-11 | inproject | checkbox | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui. | ('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-265-30 | inproject | bind_value | [
"bind_value",
"bind_value_from",
"bind_value_to",
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"change_handler",
"classes",
"handle_change",
"page",
"parent_view",
"props",
"set_value",
"style",
"tooltip",
"update",
"value",
"value_to_view",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active'). | (line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-268-16 | random | scene | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui. | (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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-278-18 | inproject | line | [
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"box",
"classes",
"curve",
"cylinder",
"extrusion",
"group",
"line",
"move_camera",
"page",
"parent_view",
"props",
"quadratic_bezier_tube",
"ring",
"sphere",
"spot_light",
"stl",
"style",
"text",
"text3d",
"texture",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__enter__",
"__eq__",
"__exit__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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. | ([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-278-47 | inproject | material | [
"args",
"color",
"delete",
"id",
"material",
"move",
"name",
"opacity",
"page",
"parent",
"R",
"rotate",
"rotate_R",
"run_command",
"scale",
"send_to",
"side_",
"stack",
"sx",
"sy",
"sz",
"type",
"view",
"visible",
"visible_",
"with_name",
"x",
"y",
"z",
"_create_command",
"_delete_command",
"_material_command",
"_move_command",
"_rotate_command",
"_scale_command",
"_visible_command",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__enter__",
"__eq__",
"__exit__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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]). | ('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-279-18 | inproject | curve | [
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"box",
"classes",
"curve",
"cylinder",
"extrusion",
"group",
"line",
"move_camera",
"page",
"parent_view",
"props",
"quadratic_bezier_tube",
"ring",
"sphere",
"spot_light",
"stl",
"style",
"text",
"text3d",
"texture",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__enter__",
"__eq__",
"__exit__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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. | ([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-279-75 | inproject | material | [
"args",
"color",
"delete",
"id",
"material",
"move",
"name",
"opacity",
"page",
"parent",
"R",
"rotate",
"rotate_R",
"run_command",
"scale",
"send_to",
"side_",
"stack",
"sx",
"sy",
"sz",
"type",
"view",
"visible",
"visible_",
"with_name",
"x",
"y",
"z",
"_create_command",
"_delete_command",
"_material_command",
"_move_command",
"_rotate_command",
"_scale_command",
"_visible_command",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__enter__",
"__eq__",
"__exit__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]). | ('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-286-18 | inproject | stl | [
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"box",
"classes",
"curve",
"cylinder",
"extrusion",
"group",
"line",
"move_camera",
"page",
"parent_view",
"props",
"quadratic_bezier_tube",
"ring",
"sphere",
"spot_light",
"stl",
"style",
"text",
"text3d",
"texture",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__enter__",
"__eq__",
"__exit__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene. | (teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-286-30 | inproject | scale | [
"args",
"color",
"delete",
"id",
"material",
"move",
"name",
"opacity",
"page",
"parent",
"R",
"rotate",
"rotate_R",
"run_command",
"scale",
"send_to",
"side_",
"stack",
"sx",
"sy",
"sz",
"type",
"view",
"visible",
"visible_",
"with_name",
"x",
"y",
"z",
"_create_command",
"_delete_command",
"_material_command",
"_move_command",
"_rotate_command",
"_scale_command",
"_visible_command",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__enter__",
"__eq__",
"__exit__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot). | (0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-286-41 | inproject | move | [
"args",
"color",
"delete",
"id",
"material",
"move",
"name",
"opacity",
"page",
"parent",
"R",
"rotate",
"rotate_R",
"run_command",
"scale",
"send_to",
"side_",
"stack",
"sx",
"sy",
"sz",
"type",
"view",
"visible",
"visible_",
"with_name",
"x",
"y",
"z",
"_create_command",
"_delete_command",
"_material_command",
"_move_command",
"_rotate_command",
"_scale_command",
"_visible_command",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__enter__",
"__eq__",
"__exit__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2). | (-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-289-18 | inproject | text3d | [
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"box",
"classes",
"curve",
"cylinder",
"extrusion",
"group",
"line",
"move_camera",
"page",
"parent_view",
"props",
"quadratic_bezier_tube",
"ring",
"sphere",
"spot_light",
"stl",
"style",
"text",
"text3d",
"texture",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__enter__",
"__eq__",
"__exit__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene. | ('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-289-99 | inproject | move | [
"args",
"color",
"delete",
"id",
"material",
"move",
"name",
"opacity",
"page",
"parent",
"R",
"rotate",
"rotate_R",
"run_command",
"scale",
"send_to",
"side_",
"stack",
"sx",
"sy",
"sz",
"type",
"view",
"visible",
"visible_",
"with_name",
"x",
"y",
"z",
"_create_command",
"_delete_command",
"_material_command",
"_move_command",
"_rotate_command",
"_scale_command",
"_visible_command",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__enter__",
"__eq__",
"__exit__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px'). | (y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-289-110 | inproject | scale | [
"args",
"color",
"delete",
"id",
"material",
"move",
"name",
"opacity",
"page",
"parent",
"R",
"rotate",
"rotate_R",
"run_command",
"scale",
"send_to",
"side_",
"stack",
"sx",
"sy",
"sz",
"type",
"view",
"visible",
"visible_",
"with_name",
"x",
"y",
"z",
"_create_command",
"_delete_command",
"_material_command",
"_move_command",
"_rotate_command",
"_scale_command",
"_visible_command",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__enter__",
"__eq__",
"__exit__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2). | (.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-291-20 | infile | tree | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui. | ):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-297-20 | infile | log | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui. | ):
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-308-20 | random | card_section | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui. | ():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-317-20 | infile | row | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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. | ):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-335-11 | infile | button | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui. | ('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-338-20 | infile | expansion | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui. | ):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-344-16 | inproject | menu | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui. | () 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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-345-15 | inproject | menu_item | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui. | ('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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-345-55 | inproject | set_text | [
"bind_text",
"bind_text_from",
"bind_text_to",
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"page",
"parent_view",
"props",
"set_text",
"style",
"text",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice. | ('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-358-11 | inproject | label | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui. | ('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-358-32 | inproject | tooltip | [
"bind_text",
"bind_text_from",
"bind_text_to",
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"page",
"parent_view",
"props",
"set_text",
"style",
"text",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...'). | ('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-361-20 | infile | notify | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui. | ):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-364-20 | infile | dialog | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui. | ):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-367-15 | inproject | button | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui. | ('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-367-47 | inproject | close | [
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"clear",
"close",
"open",
"page",
"parent_view",
"props",
"style",
"submit",
"tight",
"tooltip",
"update",
"view",
"visible",
"_child_count_on_enter",
"_on_input",
"_result",
"_submitted",
"__annotations__",
"__await__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__enter__",
"__eq__",
"__exit__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog. | )
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-388-11 | infile | button | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui. | ('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-405-11 | inproject | button | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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. | ().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-405-20 | inproject | props | [
"bind_text",
"bind_text_from",
"bind_text_to",
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"page",
"parent_view",
"props",
"set_text",
"style",
"text",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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(). | ('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-405-58 | inproject | classes | [
"bind_text",
"bind_text_from",
"bind_text_to",
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"page",
"parent_view",
"props",
"set_text",
"style",
"text",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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'). | ('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-437-11 | inproject | on_startup | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui. | (run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-438-11 | inproject | on_connect | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui. | (lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-438-32 | inproject | set_text | [
"bind_text",
"bind_text_from",
"bind_text_to",
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"page",
"parent_view",
"props",
"set_text",
"style",
"text",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l. | ('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-440-20 | infile | timer | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui. | ):
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-466-17 | inproject | modifiers | [
"action",
"key",
"modifiers",
"sender",
"socket",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e. | .shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-466-27 | inproject | shift | [
"alt",
"ctrl",
"meta",
"shift",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers. | and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-466-39 | inproject | action | [
"action",
"key",
"modifiers",
"sender",
"socket",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e. | .keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-466-46 | inproject | keydown | [
"keydown",
"keyup",
"repeat",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action. | :
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-471-23 | inproject | key | [
"action",
"key",
"modifiers",
"sender",
"socket",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e. | .arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-471-27 | inproject | arrow_up | [
"alt",
"arrow_down",
"arrow_left",
"arrow_right",
"arrow_up",
"backspace",
"caps_lock",
"code",
"control",
"delete",
"end",
"enter",
"escape",
"f1",
"f10",
"f11",
"f12",
"f2",
"f3",
"f4",
"f5",
"f6",
"f7",
"f8",
"f9",
"home",
"insert",
"is_cursorkey",
"location",
"meta",
"name",
"number",
"page_down",
"page_up",
"pause",
"print_screen",
"shift",
"space",
"tab",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key. | :
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-473-23 | inproject | key | [
"action",
"key",
"modifiers",
"sender",
"socket",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e. | .arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-473-27 | inproject | arrow_down | [
"alt",
"arrow_down",
"arrow_left",
"arrow_right",
"arrow_up",
"backspace",
"caps_lock",
"code",
"control",
"delete",
"end",
"enter",
"escape",
"f1",
"f10",
"f11",
"f12",
"f2",
"f3",
"f4",
"f5",
"f6",
"f7",
"f8",
"f9",
"home",
"insert",
"is_cursorkey",
"location",
"meta",
"name",
"number",
"page_down",
"page_up",
"pause",
"print_screen",
"shift",
"space",
"tab",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key. | :
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-478-11 | inproject | checkbox | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui. | ('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-478-40 | inproject | bind_value_to | [
"bind_value",
"bind_value_from",
"bind_value_to",
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"change_handler",
"classes",
"handle_change",
"page",
"parent_view",
"props",
"set_value",
"style",
"tooltip",
"update",
"value",
"value_to_view",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events'). | (keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-496-16 | inproject | column | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui. | ().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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-496-25 | inproject | bind_visibility_from | [
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"clear",
"page",
"parent_view",
"props",
"style",
"tight",
"tooltip",
"update",
"view",
"visible",
"_child_count_on_enter",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__enter__",
"__eq__",
"__exit__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column(). | (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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-512-20 | commited | update | [
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"options",
"page",
"parent_view",
"props",
"style",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers. | ()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-515-20 | infile | options | [
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"options",
"page",
"parent_view",
"props",
"style",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers. | .rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-516-15 | commited | update | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui. | (numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-519-11 | infile | button | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui. | ('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-534-11 | infile | button | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui. | ('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-539-12 | inproject | page | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui. | ('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-544-12 | inproject | page | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui. | ('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-579-11 | infile | link | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui. | ('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-581-20 | inproject | open | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui. | ):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-582-12 | inproject | page | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui. | ('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-597-11 | inproject | add_route | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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. | (starlette.routing.Route(
'/new/route', lambda _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-597-31 | inproject | routing | [
"applications",
"authentication",
"background",
"concurrency",
"config",
"convertors",
"datastructures",
"endpoints",
"exceptions",
"formparsers",
"middleware",
"requests",
"responses",
"routing",
"schemas",
"staticfiles",
"status",
"templating",
"testclient",
"types",
"websockets",
"_compat",
"_exception_handler",
"_utils",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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. | .Route(
'/new/route', lambda _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-597-39 | inproject | Route | [
"annotations",
"ASGIApp",
"asynccontextmanager",
"BaseRoute",
"compile_path",
"contextlib",
"Convertor",
"CONVERTOR_TYPES",
"Enum",
"functools",
"get_name",
"get_route_path",
"Headers",
"Host",
"HTTPException",
"inspect",
"is_async_callable",
"iscoroutinefunction_or_partial",
"Lifespan",
"Match",
"Middleware",
"Mount",
"NoMatchFound",
"PARAM_REGEX",
"PlainTextResponse",
"re",
"Receive",
"RedirectResponse",
"replace_params",
"Request",
"request_response",
"Response",
"Route",
"Router",
"run_in_threadpool",
"Scope",
"Send",
"traceback",
"types",
"typing",
"URL",
"URLPath",
"warnings",
"WebSocket",
"websocket_session",
"WebSocketClose",
"WebSocketRoute",
"wrap_app_handling_exceptions",
"_AsyncLiftContextManager",
"_DefaultLifespan",
"_T",
"_wrap_gen_lifespan_context",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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. | (
'/new/route', lambda _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-615-12 | common | get | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui. | ('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-640-19 | inproject | set_text | [
"bind_text",
"bind_text_from",
"bind_text_to",
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"page",
"parent_view",
"props",
"set_text",
"style",
"text",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits. | (f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-640-78 | inproject | values | [
"clear",
"copy",
"elements",
"fromkeys",
"get",
"items",
"keys",
"most_common",
"pop",
"popitem",
"setdefault",
"subtract",
"total",
"update",
"values",
"_keep_positive",
"__add__",
"__and__",
"__annotations__",
"__class__",
"__class_getitem__",
"__contains__",
"__delattr__",
"__delitem__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__ge__",
"__getattribute__",
"__getitem__",
"__gt__",
"__hash__",
"__iadd__",
"__iand__",
"__init__",
"__init_subclass__",
"__ior__",
"__isub__",
"__iter__",
"__le__",
"__len__",
"__lt__",
"__missing__",
"__module__",
"__ne__",
"__neg__",
"__new__",
"__or__",
"__pos__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__reversed__",
"__setattr__",
"__setitem__",
"__sizeof__",
"__slots__",
"__str__",
"__sub__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter. | ())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-642-12 | inproject | page | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui. | ('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-662-32 | infile | await_javascript | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
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.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 msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
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):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
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, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 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)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
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]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
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')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
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_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 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')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
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() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
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(bindings):
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')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
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 _: 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/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui. | ('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
54 | 54-40-24 | inproject | serialized | [
"bind",
"bindings",
"chars",
"contains",
"copy",
"debug",
"execute_binding",
"get_lines",
"handle_key",
"handle_mouse",
"id",
"is_bindable",
"is_selectable",
"keys",
"mro",
"parent_align",
"print",
"select",
"selectables",
"selectables_length",
"serialize",
"serialized",
"set_char",
"set_style",
"size_policy",
"static_width",
"styles",
"_get_char",
"_get_style",
"_id_manager",
"__annotations__",
"__base__",
"__bases__",
"__basicsize__",
"__call__",
"__class__",
"__delattr__",
"__dict__",
"__dictoffset__",
"__dir__",
"__doc__",
"__eq__",
"__flags__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__instancecheck__",
"__itemsize__",
"__iter__",
"__module__",
"__mro__",
"__name__",
"__ne__",
"__new__",
"__prepare__",
"__qualname__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__",
"__subclasscheck__",
"__subclasses__",
"__text_signature__",
"__weakrefoffset__"
] | """The module containing all of the layout-related widgets."""
# These widgets have more than the 7 allowed instance attributes.
# pylint: disable=too-many-instance-attributes
from __future__ import annotations
from itertools import zip_longest
from typing import Any, Callable, Iterator, cast
from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal
from ..context_managers import cursor_at
from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment
from ..exceptions import WidthExceededError
from ..helpers import real_length
from ..input import keys
from . import boxes
from . import styles as w_styles
from .base import Widget
class Container(Widget):
"""A widget that displays other widgets, stacked vertically."""
chars: dict[str, w_styles.CharType] = {
"border": ["| ", "-", " |", "-"],
"corner": [""] * 4,
}
styles = {
"border": w_styles.MARKUP,
"corner": w_styles.MARKUP,
"fill": w_styles.BACKGROUND,
}
keys = {
"next": {keys.DOWN, keys.CTRL_N, "j"},
"previous": {keys.UP, keys.CTRL_P, "k"},
}
serialized = Widget. | + ["_centered_axis"]
vertical_align = VerticalAlignment.CENTER
allow_fullscreen = True
# TODO: Add `WidgetConvertible`? type instead of Any
def __init__(self, *widgets: Any, **attrs: Any) -> None:
"""Initialize Container data"""
super().__init__(**attrs)
# TODO: This is just a band-aid.
if "width" not in attrs:
self.width = 40
self._widgets: list[Widget] = []
self._centered_axis: CenteringPolicy | None = None
self._prev_screen: tuple[int, int] = (0, 0)
self._has_printed = False
self.styles = type(self).styles.copy()
self.chars = type(self).chars.copy()
for widget in widgets:
self._add_widget(widget)
self._drag_target: Widget | None = None
terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis))
@property
def sidelength(self) -> int:
"""Gets the length of left and right borders combined.
Returns:
An integer equal to the `pytermgui.helpers.real_length` of the concatenation of
the left and right borders of this widget, both with their respective styles
applied.
"""
chars = self._get_char("border")
style = self._get_style("border")
if not isinstance(chars, list):
return 0
left_border, _, right_border, _ = chars
return real_length(style(left_border) + style(right_border))
@property
def selectables(self) -> list[tuple[Widget, int]]:
"""Gets all selectable widgets and their inner indices.
This is used in order to have a constant reference to all selectable indices within this
widget.
Returns:
A list of tuples containing a widget and an integer each. For each widget that is
withing this one, it is added to this list as many times as it has selectables. Each
of the integers correspond to a selectable_index within the widget.
For example, a Container with a Button, InputField and an inner Container containing
3 selectables might return something like this:
```
[
(Button(...), 0),
(InputField(...), 0),
(Container(...), 0),
(Container(...), 1),
(Container(...), 2),
]
```
"""
_selectables: list[tuple[Widget, int]] = []
for widget in self._widgets:
if not widget.is_selectable:
continue
for i, (inner, _) in enumerate(widget.selectables):
_selectables.append((inner, i))
return _selectables
@property
def selectables_length(self) -> int:
"""Gets the length of the selectables list.
Returns:
An integer equal to the length of `self.selectables`.
"""
return len(self.selectables)
@property
def selected(self) -> Widget | None:
"""Returns the currently selected object
Returns:
The currently selected widget if selected_index is not None,
otherwise None.
"""
# TODO: Add deeper selection
if self.selected_index is None:
return None
if self.selected_index >= len(self.selectables):
return None
return self.selectables[self.selected_index][0]
@property
def box(self) -> boxes.Box:
"""Returns current box setting
Returns:
The currently set box instance.
"""
return self._box
@box.setter
def box(self, new: str | boxes.Box) -> None:
"""Applies a new box.
Args:
new: Either a `pytermgui.boxes.Box` instance or a string
analogous to one of the default box names.
"""
if isinstance(new, str):
from_module = vars(boxes).get(new)
if from_module is None:
raise ValueError(f"Unknown box type {new}.")
new = from_module
assert isinstance(new, boxes.Box)
self._box = new
new.set_chars_of(self)
def __iadd__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self._add_widget(other)
return self
def __add__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
This method is analogous to `Container.__iadd__`.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self.__iadd__(other)
return self
def __iter__(self) -> Iterator[Widget]:
"""Gets an iterator of self._widgets.
Yields:
The next widget.
"""
for widget in self._widgets:
yield widget
def __len__(self) -> int:
"""Gets the length of the widgets list.
Returns:
An integer describing len(self._widgets).
"""
return len(self._widgets)
def __getitem__(self, sli: int | slice) -> Widget | list[Widget]:
"""Gets an item from self._widgets.
Args:
sli: Slice of the list.
Returns:
The slice in the list.
"""
return self._widgets[sli]
def __setitem__(self, index: int, value: Any) -> None:
"""Sets an item in self._widgets.
Args:
index: The index to be set.
value: The new widget at this index.
"""
self._widgets[index] = value
def __contains__(self, other: object) -> bool:
"""Determines if self._widgets contains other widget.
Args:
other: Any widget-like.
Returns:
A boolean describing whether `other` is in `self.widgets`
"""
return other in self._widgets
def _add_widget(self, other: object, run_get_lines: bool = True) -> None:
"""Adds other to this widget.
Args:
other: Any widget-like object.
run_get_lines: Boolean controlling whether the self.get_lines is ran.
"""
if not isinstance(other, Widget):
to_widget = Widget.from_data(other)
if to_widget is None:
raise ValueError(
f"Could not convert {other} of type {type(other)} to a Widget!"
)
other = to_widget
# This is safe to do, as it would've raised an exception above already
assert isinstance(other, Widget)
self._widgets.append(other)
if isinstance(other, Container):
other.set_recursive_depth(self.depth + 2)
else:
other.depth = self.depth + 1
other.get_lines()
other.parent = self
if run_get_lines:
self.get_lines()
def _get_aligners(
self, widget: Widget, borders: tuple[str, str]
) -> tuple[Callable[[str], str], int]:
"""Gets an aligning method and position offset.
Args:
widget: The widget to align.
borders: The left and right borders to put the widget within.
Returns:
A tuple of a method that, when called with a line, will return that line
centered using the passed in widget's parent_align and width, as well as
the horizontal offset resulting from the widget being aligned.
"""
left, right = borders
char = self._get_style("fill")(" ")
def _align_left(text: str) -> str:
"""Align line to the left"""
padding = self.width - real_length(left + right) - real_length(text)
return left + text + padding * char + right
def _align_center(text: str) -> str:
"""Align line to the center"""
total = self.width - real_length(left + right) - real_length(text)
padding, offset = divmod(total, 2)
return left + (padding + offset) * char + text + padding * char + right
def _align_right(text: str) -> str:
"""Align line to the right"""
padding = self.width - real_length(left + right) - real_length(text)
return left + padding * char + text + right
if widget.parent_align == HorizontalAlignment.CENTER:
total = self.width - real_length(left + right) - widget.width
padding, offset = divmod(total, 2)
return _align_center, real_length(left) + padding + offset
if widget.parent_align == HorizontalAlignment.RIGHT:
return _align_right, self.width - real_length(left) - widget.width
# Default to left-aligned
return _align_left, real_length(left)
def _update_width(self, widget: Widget) -> None:
"""Updates the width of widget or self.
This method respects widget.size_policy.
Args:
widget: The widget to update/base updates on.
"""
available = (
self.width - self.sidelength - (0 if isinstance(widget, Container) else 1)
)
if widget.size_policy == SizePolicy.FILL:
widget.width = available
return
if widget.size_policy == SizePolicy.RELATIVE:
widget.width = widget.relative_width * available
return
if widget.width > available:
if widget.size_policy == SizePolicy.STATIC:
raise WidthExceededError(
f"Widget {widget}'s static width of {widget.width}"
+ f" exceeds its parent's available width {available}."
""
)
widget.width = available
def _apply_vertalign(
self, lines: list[str], diff: int, padder: str
) -> tuple[int, list[str]]:
"""Insert padder line into lines diff times, depending on self.vertical_align.
Args:
lines: The list of lines to align.
diff: The available height.
padder: The line to use to pad.
Returns:
A tuple containing the vertical offset as well as the padded list of lines.
Raises:
NotImplementedError: The given vertical alignment is not implemented.
"""
if self.vertical_align == VerticalAlignment.BOTTOM:
for _ in range(diff):
lines.insert(0, padder)
return diff, lines
if self.vertical_align == VerticalAlignment.TOP:
for _ in range(diff):
lines.append(padder)
return 0, lines
if self.vertical_align == VerticalAlignment.CENTER:
top, extra = divmod(diff, 2)
bottom = top + extra
for _ in range(top):
lines.insert(0, padder)
for _ in range(bottom):
lines.append(padder)
return top, lines
raise NotImplementedError(
f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}."
)
def get_lines(self) -> list[str]:
"""Gets all lines by spacing out inner widgets.
This method reflects & applies both width settings, as well as
the `parent_align` field.
Returns:
A list of all lines that represent this Container.
"""
def _get_border(left: str, char: str, right: str) -> str:
"""Gets a top or bottom border.
Args:
left: Left corner character.
char: Border character filling between left & right.
right: Right corner character.
Returns:
The border line.
"""
offset = real_length(left + right)
return left + char * (self.width - offset) + right
lines = []
style = self._get_style("border")
borders = [style(char) for char in self._get_char("border")]
style = self._get_style("corner")
corners = [style(char) for char in self._get_char("corner")]
has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0)
align = lambda item: item
for widget in self._widgets:
align, offset = self._get_aligners(widget, (borders[0], borders[2]))
self._update_width(widget)
widget.pos = (
self.pos[0] + offset,
self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0),
)
widget_lines = []
for line in widget.get_lines():
widget_lines.append(align(line))
lines.extend(widget_lines)
vertical_offset, lines = self._apply_vertalign(
lines, self.height - len(lines) - sum(has_top_bottom), align("")
)
for widget in self._widgets:
widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset)
# TODO: This is wasteful.
widget.get_lines()
if has_top_bottom[0]:
lines.insert(0, _get_border(corners[0], borders[1], corners[1]))
if has_top_bottom[1]:
lines.append(_get_border(corners[3], borders[3], corners[2]))
self.height = len(lines)
return lines
def set_widgets(self, new: list[Widget]) -> None:
"""Sets new list in place of self._widgets.
Args:
new: The new widget list.
"""
self._widgets = []
for widget in new:
self._add_widget(widget)
def serialize(self) -> dict[str, Any]:
"""Serializes this Container, adding in serializations of all widgets.
See `pytermgui.widgets.base.Widget.serialize` for more info.
Returns:
The dictionary containing all serialized data.
"""
out = super().serialize()
out["_widgets"] = []
for widget in self._widgets:
out["_widgets"].append(widget.serialize())
return out
def pop(self, index: int = -1) -> Widget:
"""Pops widget from self._widgets.
Analogous to self._widgets.pop(index).
Args:
index: The index to operate on.
Returns:
The widget that was popped off the list.
"""
return self._widgets.pop(index)
def remove(self, other: Widget) -> None:
"""Remove widget from self._widgets
Analogous to self._widgets.remove(other).
Args:
widget: The widget to remove.
"""
return self._widgets.remove(other)
def set_recursive_depth(self, value: int) -> None:
"""Set depth for this Container and all its children.
All inner widgets will receive value+1 as their new depth.
Args:
value: The new depth to use as the base depth.
"""
self.depth = value
for widget in self._widgets:
if isinstance(widget, Container):
widget.set_recursive_depth(value + 1)
else:
widget.depth = value
def select(self, index: int | None = None) -> None:
"""Selects inner subwidget.
Args:
index: The index to select.
Raises:
IndexError: The index provided was beyond len(self.selectables).
"""
# Unselect all sub-elements
for other in self._widgets:
if other.selectables_length > 0:
other.select(None)
if index is not None:
if index >= len(self.selectables) is None:
raise IndexError("Container selection index out of range")
widget, inner_index = self.selectables[index]
widget.select(inner_index)
self.selected_index = index
def center(
self, where: CenteringPolicy | None = None, store: bool = True
) -> Container:
"""Centers this object to the given axis.
Args:
where: A CenteringPolicy describing the place to center to
store: When set, this centering will be reapplied during every
print, as well as when calling this method with no arguments.
Returns:
This Container.
"""
# Refresh in case changes happened
self.get_lines()
if where is None:
# See `enums.py` for explanation about this ignore.
where = CenteringPolicy.get_default() # type: ignore
centerx = centery = where is CenteringPolicy.ALL
centerx |= where is CenteringPolicy.HORIZONTAL
centery |= where is CenteringPolicy.VERTICAL
pos = list(self.pos)
if centerx:
pos[0] = (terminal.width - self.width + 2) // 2
if centery:
pos[1] = (terminal.height - self.height + 2) // 2
self.pos = (pos[0], pos[1])
if store:
self._centered_axis = where
self._prev_screen = terminal.size
return self
def handle_mouse(self, event: MouseEvent) -> bool:
"""Applies a mouse event on all children.
Args:
event: The event to handle
Returns:
A boolean showing whether the event was handled.
"""
if event.action is MouseAction.RELEASE:
# Force RELEASE event to be sent
if self._drag_target is not None:
self._drag_target.handle_mouse(
MouseEvent(MouseAction.RELEASE, event.position)
)
self._drag_target = None
if self._drag_target is not None:
return self._drag_target.handle_mouse(event)
selectables_index = 0
for widget in self._widgets:
if widget.contains(event.position):
handled = widget.handle_mouse(event)
if widget.selected_index is not None:
selectables_index += widget.selected_index
if event.action is MouseAction.LEFT_CLICK:
self._drag_target = widget
if handled:
self.select(selectables_index)
return handled
if widget.is_selectable:
selectables_index += widget.selectables_length
return False
def handle_key(self, key: str) -> bool:
"""Handles a keypress, returns its success.
Args:
key: A key str.
Returns:
A boolean showing whether the key was handled.
"""
def _is_nav(key: str) -> bool:
"""Determine if a key is in the navigation sets"""
return key in self.keys["next"] | self.keys["previous"]
if self.selected is not None and self.selected.handle_key(key):
return True
# Only use navigation when there is more than one selectable
if self.selectables_length > 1 and _is_nav(key):
handled = False
if self.selected_index is None:
self.select(0)
assert isinstance(self.selected_index, int)
if key in self.keys["previous"]:
# No more selectables left, user wants to exit Container
# upwards.
if self.selected_index == 0:
return False
self.select(self.selected_index - 1)
handled = True
elif key in self.keys["next"]:
# Stop selection at last element, return as unhandled
new = self.selected_index + 1
if new == len(self.selectables):
return False
self.select(new)
handled = True
if handled:
return True
if key == keys.ENTER and self.selected is not None:
if self.selected.selected_index is not None:
self.selected.handle_key(key)
return True
return False
def wipe(self) -> None:
"""Wipes the characters occupied by the object"""
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(real_length(line) * " ")
def print(self) -> None:
"""Prints this Container.
If the screen size has changed since last `print` call, the object
will be centered based on its `_centered_axis`.
"""
if not terminal.size == self._prev_screen:
clear()
self.center(self._centered_axis)
self._prev_screen = terminal.size
if self.allow_fullscreen:
self.pos = terminal.origin
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(line)
self._has_printed = True
def debug(self) -> str:
"""Returns a string with identifiable information on this widget.
Returns:
A str in the form of a class construction. This string is in a form that
__could have been__ used to create this Container.
"""
out = "Container("
for widget in self._widgets:
out += widget.debug() + ", "
out = out.strip(", ")
out += ", **attrs)"
return out
class Splitter(Container):
"""A widget that displays other widgets, stacked horizontally."""
chars: dict[str, list[str] | str] = {"separator": " | "}
styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND}
keys = {
"previous": {keys.LEFT, "h", keys.CTRL_B},
"next": {keys.RIGHT, "l", keys.CTRL_F},
}
parent_align = HorizontalAlignment.RIGHT
def _align(
self, alignment: HorizontalAlignment, target_width: int, line: str
) -> tuple[int, str]:
"""Align a line
r/wordavalanches"""
available = target_width - real_length(line)
fill_style = self._get_style("fill")
char = fill_style(" ")
line = fill_style(line)
if alignment == HorizontalAlignment.CENTER:
padding, offset = divmod(available, 2)
return padding, padding * char + line + (padding + offset) * char
if alignment == HorizontalAlignment.RIGHT:
return available, available * char + line
return 0, line + available * char
def get_lines(self) -> list[str]:
"""Join all widgets horizontally."""
# An error will be raised if `separator` is not the correct type (str).
separator = self._get_style("separator")(self._get_char("separator")) # type: ignore
separator_length = real_length(separator)
target_width, error = divmod(
self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets)
)
vertical_lines = []
total_offset = 0
for widget in self._widgets:
inner = []
if widget.size_policy is SizePolicy.STATIC:
target_width += target_width - widget.width
width = target_width
else:
widget.width = target_width + error
width = widget.width
error = 0
aligned: str | None = None
for line in widget.get_lines():
# See `enums.py` for information about this ignore
padding, aligned = self._align(
cast(HorizontalAlignment, widget.parent_align), width, line
)
inner.append(aligned)
widget.pos = (
self.pos[0] + padding + total_offset,
self.pos[1] + (1 if type(widget).__name__ == "Container" else 0),
)
if aligned is not None:
total_offset += real_length(inner[-1]) + separator_length
vertical_lines.append(inner)
lines = []
for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width):
lines.append((reset() + separator).join(horizontal))
return lines
def debug(self) -> str:
"""Return identifiable information"""
return super().debug().replace("Container", "Splitter", 1)
| bczsalba__pytermgui |
54 | 54-41-39 | inproject | CENTER | [
"as_integer_ratio",
"bit_length",
"BOTTOM",
"CENTER",
"conjugate",
"denominator",
"from_bytes",
"get_default",
"imag",
"mro",
"name",
"numerator",
"real",
"to_bytes",
"TOP",
"value",
"_generate_next_value_",
"_ignore_",
"_member_map_",
"_member_names_",
"_missing_",
"_name_",
"_order_",
"_value2member_map_",
"_value_",
"__abs__",
"__add__",
"__and__",
"__annotations__",
"__base__",
"__bases__",
"__basicsize__",
"__bool__",
"__call__",
"__ceil__",
"__class__",
"__delattr__",
"__dict__",
"__dictoffset__",
"__dir__",
"__divmod__",
"__doc__",
"__eq__",
"__flags__",
"__float__",
"__floor__",
"__floordiv__",
"__format__",
"__ge__",
"__getattribute__",
"__getnewargs__",
"__gt__",
"__hash__",
"__index__",
"__init__",
"__init_subclass__",
"__instancecheck__",
"__int__",
"__invert__",
"__itemsize__",
"__le__",
"__lshift__",
"__lt__",
"__mod__",
"__module__",
"__mro__",
"__mul__",
"__name__",
"__ne__",
"__neg__",
"__new__",
"__or__",
"__order__",
"__pos__",
"__pow__",
"__prepare__",
"__qualname__",
"__radd__",
"__rand__",
"__rdivmod__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__rfloordiv__",
"__rlshift__",
"__rmod__",
"__rmul__",
"__ror__",
"__round__",
"__rpow__",
"__rrshift__",
"__rshift__",
"__rsub__",
"__rtruediv__",
"__rxor__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__",
"__sub__",
"__subclasscheck__",
"__subclasses__",
"__text_signature__",
"__truediv__",
"__trunc__",
"__weakrefoffset__",
"__xor__"
] | """The module containing all of the layout-related widgets."""
# These widgets have more than the 7 allowed instance attributes.
# pylint: disable=too-many-instance-attributes
from __future__ import annotations
from itertools import zip_longest
from typing import Any, Callable, Iterator, cast
from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal
from ..context_managers import cursor_at
from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment
from ..exceptions import WidthExceededError
from ..helpers import real_length
from ..input import keys
from . import boxes
from . import styles as w_styles
from .base import Widget
class Container(Widget):
"""A widget that displays other widgets, stacked vertically."""
chars: dict[str, w_styles.CharType] = {
"border": ["| ", "-", " |", "-"],
"corner": [""] * 4,
}
styles = {
"border": w_styles.MARKUP,
"corner": w_styles.MARKUP,
"fill": w_styles.BACKGROUND,
}
keys = {
"next": {keys.DOWN, keys.CTRL_N, "j"},
"previous": {keys.UP, keys.CTRL_P, "k"},
}
serialized = Widget.serialized + ["_centered_axis"]
vertical_align = VerticalAlignment. |
allow_fullscreen = True
# TODO: Add `WidgetConvertible`? type instead of Any
def __init__(self, *widgets: Any, **attrs: Any) -> None:
"""Initialize Container data"""
super().__init__(**attrs)
# TODO: This is just a band-aid.
if "width" not in attrs:
self.width = 40
self._widgets: list[Widget] = []
self._centered_axis: CenteringPolicy | None = None
self._prev_screen: tuple[int, int] = (0, 0)
self._has_printed = False
self.styles = type(self).styles.copy()
self.chars = type(self).chars.copy()
for widget in widgets:
self._add_widget(widget)
self._drag_target: Widget | None = None
terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis))
@property
def sidelength(self) -> int:
"""Gets the length of left and right borders combined.
Returns:
An integer equal to the `pytermgui.helpers.real_length` of the concatenation of
the left and right borders of this widget, both with their respective styles
applied.
"""
chars = self._get_char("border")
style = self._get_style("border")
if not isinstance(chars, list):
return 0
left_border, _, right_border, _ = chars
return real_length(style(left_border) + style(right_border))
@property
def selectables(self) -> list[tuple[Widget, int]]:
"""Gets all selectable widgets and their inner indices.
This is used in order to have a constant reference to all selectable indices within this
widget.
Returns:
A list of tuples containing a widget and an integer each. For each widget that is
withing this one, it is added to this list as many times as it has selectables. Each
of the integers correspond to a selectable_index within the widget.
For example, a Container with a Button, InputField and an inner Container containing
3 selectables might return something like this:
```
[
(Button(...), 0),
(InputField(...), 0),
(Container(...), 0),
(Container(...), 1),
(Container(...), 2),
]
```
"""
_selectables: list[tuple[Widget, int]] = []
for widget in self._widgets:
if not widget.is_selectable:
continue
for i, (inner, _) in enumerate(widget.selectables):
_selectables.append((inner, i))
return _selectables
@property
def selectables_length(self) -> int:
"""Gets the length of the selectables list.
Returns:
An integer equal to the length of `self.selectables`.
"""
return len(self.selectables)
@property
def selected(self) -> Widget | None:
"""Returns the currently selected object
Returns:
The currently selected widget if selected_index is not None,
otherwise None.
"""
# TODO: Add deeper selection
if self.selected_index is None:
return None
if self.selected_index >= len(self.selectables):
return None
return self.selectables[self.selected_index][0]
@property
def box(self) -> boxes.Box:
"""Returns current box setting
Returns:
The currently set box instance.
"""
return self._box
@box.setter
def box(self, new: str | boxes.Box) -> None:
"""Applies a new box.
Args:
new: Either a `pytermgui.boxes.Box` instance or a string
analogous to one of the default box names.
"""
if isinstance(new, str):
from_module = vars(boxes).get(new)
if from_module is None:
raise ValueError(f"Unknown box type {new}.")
new = from_module
assert isinstance(new, boxes.Box)
self._box = new
new.set_chars_of(self)
def __iadd__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self._add_widget(other)
return self
def __add__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
This method is analogous to `Container.__iadd__`.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self.__iadd__(other)
return self
def __iter__(self) -> Iterator[Widget]:
"""Gets an iterator of self._widgets.
Yields:
The next widget.
"""
for widget in self._widgets:
yield widget
def __len__(self) -> int:
"""Gets the length of the widgets list.
Returns:
An integer describing len(self._widgets).
"""
return len(self._widgets)
def __getitem__(self, sli: int | slice) -> Widget | list[Widget]:
"""Gets an item from self._widgets.
Args:
sli: Slice of the list.
Returns:
The slice in the list.
"""
return self._widgets[sli]
def __setitem__(self, index: int, value: Any) -> None:
"""Sets an item in self._widgets.
Args:
index: The index to be set.
value: The new widget at this index.
"""
self._widgets[index] = value
def __contains__(self, other: object) -> bool:
"""Determines if self._widgets contains other widget.
Args:
other: Any widget-like.
Returns:
A boolean describing whether `other` is in `self.widgets`
"""
return other in self._widgets
def _add_widget(self, other: object, run_get_lines: bool = True) -> None:
"""Adds other to this widget.
Args:
other: Any widget-like object.
run_get_lines: Boolean controlling whether the self.get_lines is ran.
"""
if not isinstance(other, Widget):
to_widget = Widget.from_data(other)
if to_widget is None:
raise ValueError(
f"Could not convert {other} of type {type(other)} to a Widget!"
)
other = to_widget
# This is safe to do, as it would've raised an exception above already
assert isinstance(other, Widget)
self._widgets.append(other)
if isinstance(other, Container):
other.set_recursive_depth(self.depth + 2)
else:
other.depth = self.depth + 1
other.get_lines()
other.parent = self
if run_get_lines:
self.get_lines()
def _get_aligners(
self, widget: Widget, borders: tuple[str, str]
) -> tuple[Callable[[str], str], int]:
"""Gets an aligning method and position offset.
Args:
widget: The widget to align.
borders: The left and right borders to put the widget within.
Returns:
A tuple of a method that, when called with a line, will return that line
centered using the passed in widget's parent_align and width, as well as
the horizontal offset resulting from the widget being aligned.
"""
left, right = borders
char = self._get_style("fill")(" ")
def _align_left(text: str) -> str:
"""Align line to the left"""
padding = self.width - real_length(left + right) - real_length(text)
return left + text + padding * char + right
def _align_center(text: str) -> str:
"""Align line to the center"""
total = self.width - real_length(left + right) - real_length(text)
padding, offset = divmod(total, 2)
return left + (padding + offset) * char + text + padding * char + right
def _align_right(text: str) -> str:
"""Align line to the right"""
padding = self.width - real_length(left + right) - real_length(text)
return left + padding * char + text + right
if widget.parent_align == HorizontalAlignment.CENTER:
total = self.width - real_length(left + right) - widget.width
padding, offset = divmod(total, 2)
return _align_center, real_length(left) + padding + offset
if widget.parent_align == HorizontalAlignment.RIGHT:
return _align_right, self.width - real_length(left) - widget.width
# Default to left-aligned
return _align_left, real_length(left)
def _update_width(self, widget: Widget) -> None:
"""Updates the width of widget or self.
This method respects widget.size_policy.
Args:
widget: The widget to update/base updates on.
"""
available = (
self.width - self.sidelength - (0 if isinstance(widget, Container) else 1)
)
if widget.size_policy == SizePolicy.FILL:
widget.width = available
return
if widget.size_policy == SizePolicy.RELATIVE:
widget.width = widget.relative_width * available
return
if widget.width > available:
if widget.size_policy == SizePolicy.STATIC:
raise WidthExceededError(
f"Widget {widget}'s static width of {widget.width}"
+ f" exceeds its parent's available width {available}."
""
)
widget.width = available
def _apply_vertalign(
self, lines: list[str], diff: int, padder: str
) -> tuple[int, list[str]]:
"""Insert padder line into lines diff times, depending on self.vertical_align.
Args:
lines: The list of lines to align.
diff: The available height.
padder: The line to use to pad.
Returns:
A tuple containing the vertical offset as well as the padded list of lines.
Raises:
NotImplementedError: The given vertical alignment is not implemented.
"""
if self.vertical_align == VerticalAlignment.BOTTOM:
for _ in range(diff):
lines.insert(0, padder)
return diff, lines
if self.vertical_align == VerticalAlignment.TOP:
for _ in range(diff):
lines.append(padder)
return 0, lines
if self.vertical_align == VerticalAlignment.CENTER:
top, extra = divmod(diff, 2)
bottom = top + extra
for _ in range(top):
lines.insert(0, padder)
for _ in range(bottom):
lines.append(padder)
return top, lines
raise NotImplementedError(
f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}."
)
def get_lines(self) -> list[str]:
"""Gets all lines by spacing out inner widgets.
This method reflects & applies both width settings, as well as
the `parent_align` field.
Returns:
A list of all lines that represent this Container.
"""
def _get_border(left: str, char: str, right: str) -> str:
"""Gets a top or bottom border.
Args:
left: Left corner character.
char: Border character filling between left & right.
right: Right corner character.
Returns:
The border line.
"""
offset = real_length(left + right)
return left + char * (self.width - offset) + right
lines = []
style = self._get_style("border")
borders = [style(char) for char in self._get_char("border")]
style = self._get_style("corner")
corners = [style(char) for char in self._get_char("corner")]
has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0)
align = lambda item: item
for widget in self._widgets:
align, offset = self._get_aligners(widget, (borders[0], borders[2]))
self._update_width(widget)
widget.pos = (
self.pos[0] + offset,
self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0),
)
widget_lines = []
for line in widget.get_lines():
widget_lines.append(align(line))
lines.extend(widget_lines)
vertical_offset, lines = self._apply_vertalign(
lines, self.height - len(lines) - sum(has_top_bottom), align("")
)
for widget in self._widgets:
widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset)
# TODO: This is wasteful.
widget.get_lines()
if has_top_bottom[0]:
lines.insert(0, _get_border(corners[0], borders[1], corners[1]))
if has_top_bottom[1]:
lines.append(_get_border(corners[3], borders[3], corners[2]))
self.height = len(lines)
return lines
def set_widgets(self, new: list[Widget]) -> None:
"""Sets new list in place of self._widgets.
Args:
new: The new widget list.
"""
self._widgets = []
for widget in new:
self._add_widget(widget)
def serialize(self) -> dict[str, Any]:
"""Serializes this Container, adding in serializations of all widgets.
See `pytermgui.widgets.base.Widget.serialize` for more info.
Returns:
The dictionary containing all serialized data.
"""
out = super().serialize()
out["_widgets"] = []
for widget in self._widgets:
out["_widgets"].append(widget.serialize())
return out
def pop(self, index: int = -1) -> Widget:
"""Pops widget from self._widgets.
Analogous to self._widgets.pop(index).
Args:
index: The index to operate on.
Returns:
The widget that was popped off the list.
"""
return self._widgets.pop(index)
def remove(self, other: Widget) -> None:
"""Remove widget from self._widgets
Analogous to self._widgets.remove(other).
Args:
widget: The widget to remove.
"""
return self._widgets.remove(other)
def set_recursive_depth(self, value: int) -> None:
"""Set depth for this Container and all its children.
All inner widgets will receive value+1 as their new depth.
Args:
value: The new depth to use as the base depth.
"""
self.depth = value
for widget in self._widgets:
if isinstance(widget, Container):
widget.set_recursive_depth(value + 1)
else:
widget.depth = value
def select(self, index: int | None = None) -> None:
"""Selects inner subwidget.
Args:
index: The index to select.
Raises:
IndexError: The index provided was beyond len(self.selectables).
"""
# Unselect all sub-elements
for other in self._widgets:
if other.selectables_length > 0:
other.select(None)
if index is not None:
if index >= len(self.selectables) is None:
raise IndexError("Container selection index out of range")
widget, inner_index = self.selectables[index]
widget.select(inner_index)
self.selected_index = index
def center(
self, where: CenteringPolicy | None = None, store: bool = True
) -> Container:
"""Centers this object to the given axis.
Args:
where: A CenteringPolicy describing the place to center to
store: When set, this centering will be reapplied during every
print, as well as when calling this method with no arguments.
Returns:
This Container.
"""
# Refresh in case changes happened
self.get_lines()
if where is None:
# See `enums.py` for explanation about this ignore.
where = CenteringPolicy.get_default() # type: ignore
centerx = centery = where is CenteringPolicy.ALL
centerx |= where is CenteringPolicy.HORIZONTAL
centery |= where is CenteringPolicy.VERTICAL
pos = list(self.pos)
if centerx:
pos[0] = (terminal.width - self.width + 2) // 2
if centery:
pos[1] = (terminal.height - self.height + 2) // 2
self.pos = (pos[0], pos[1])
if store:
self._centered_axis = where
self._prev_screen = terminal.size
return self
def handle_mouse(self, event: MouseEvent) -> bool:
"""Applies a mouse event on all children.
Args:
event: The event to handle
Returns:
A boolean showing whether the event was handled.
"""
if event.action is MouseAction.RELEASE:
# Force RELEASE event to be sent
if self._drag_target is not None:
self._drag_target.handle_mouse(
MouseEvent(MouseAction.RELEASE, event.position)
)
self._drag_target = None
if self._drag_target is not None:
return self._drag_target.handle_mouse(event)
selectables_index = 0
for widget in self._widgets:
if widget.contains(event.position):
handled = widget.handle_mouse(event)
if widget.selected_index is not None:
selectables_index += widget.selected_index
if event.action is MouseAction.LEFT_CLICK:
self._drag_target = widget
if handled:
self.select(selectables_index)
return handled
if widget.is_selectable:
selectables_index += widget.selectables_length
return False
def handle_key(self, key: str) -> bool:
"""Handles a keypress, returns its success.
Args:
key: A key str.
Returns:
A boolean showing whether the key was handled.
"""
def _is_nav(key: str) -> bool:
"""Determine if a key is in the navigation sets"""
return key in self.keys["next"] | self.keys["previous"]
if self.selected is not None and self.selected.handle_key(key):
return True
# Only use navigation when there is more than one selectable
if self.selectables_length > 1 and _is_nav(key):
handled = False
if self.selected_index is None:
self.select(0)
assert isinstance(self.selected_index, int)
if key in self.keys["previous"]:
# No more selectables left, user wants to exit Container
# upwards.
if self.selected_index == 0:
return False
self.select(self.selected_index - 1)
handled = True
elif key in self.keys["next"]:
# Stop selection at last element, return as unhandled
new = self.selected_index + 1
if new == len(self.selectables):
return False
self.select(new)
handled = True
if handled:
return True
if key == keys.ENTER and self.selected is not None:
if self.selected.selected_index is not None:
self.selected.handle_key(key)
return True
return False
def wipe(self) -> None:
"""Wipes the characters occupied by the object"""
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(real_length(line) * " ")
def print(self) -> None:
"""Prints this Container.
If the screen size has changed since last `print` call, the object
will be centered based on its `_centered_axis`.
"""
if not terminal.size == self._prev_screen:
clear()
self.center(self._centered_axis)
self._prev_screen = terminal.size
if self.allow_fullscreen:
self.pos = terminal.origin
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(line)
self._has_printed = True
def debug(self) -> str:
"""Returns a string with identifiable information on this widget.
Returns:
A str in the form of a class construction. This string is in a form that
__could have been__ used to create this Container.
"""
out = "Container("
for widget in self._widgets:
out += widget.debug() + ", "
out = out.strip(", ")
out += ", **attrs)"
return out
class Splitter(Container):
"""A widget that displays other widgets, stacked horizontally."""
chars: dict[str, list[str] | str] = {"separator": " | "}
styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND}
keys = {
"previous": {keys.LEFT, "h", keys.CTRL_B},
"next": {keys.RIGHT, "l", keys.CTRL_F},
}
parent_align = HorizontalAlignment.RIGHT
def _align(
self, alignment: HorizontalAlignment, target_width: int, line: str
) -> tuple[int, str]:
"""Align a line
r/wordavalanches"""
available = target_width - real_length(line)
fill_style = self._get_style("fill")
char = fill_style(" ")
line = fill_style(line)
if alignment == HorizontalAlignment.CENTER:
padding, offset = divmod(available, 2)
return padding, padding * char + line + (padding + offset) * char
if alignment == HorizontalAlignment.RIGHT:
return available, available * char + line
return 0, line + available * char
def get_lines(self) -> list[str]:
"""Join all widgets horizontally."""
# An error will be raised if `separator` is not the correct type (str).
separator = self._get_style("separator")(self._get_char("separator")) # type: ignore
separator_length = real_length(separator)
target_width, error = divmod(
self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets)
)
vertical_lines = []
total_offset = 0
for widget in self._widgets:
inner = []
if widget.size_policy is SizePolicy.STATIC:
target_width += target_width - widget.width
width = target_width
else:
widget.width = target_width + error
width = widget.width
error = 0
aligned: str | None = None
for line in widget.get_lines():
# See `enums.py` for information about this ignore
padding, aligned = self._align(
cast(HorizontalAlignment, widget.parent_align), width, line
)
inner.append(aligned)
widget.pos = (
self.pos[0] + padding + total_offset,
self.pos[1] + (1 if type(widget).__name__ == "Container" else 0),
)
if aligned is not None:
total_offset += real_length(inner[-1]) + separator_length
vertical_lines.append(inner)
lines = []
for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width):
lines.append((reset() + separator).join(horizontal))
return lines
def debug(self) -> str:
"""Return identifiable information"""
return super().debug().replace("Container", "Splitter", 1)
| bczsalba__pytermgui |
54 | 54-48-16 | commited | __init__ | [
"bind",
"bindings",
"chars",
"contains",
"copy",
"debug",
"depth",
"execute_binding",
"get_lines",
"handle_key",
"handle_mouse",
"height",
"id",
"is_bindable",
"is_selectable",
"keys",
"parent",
"parent_align",
"pos",
"print",
"select",
"selectables",
"selectables_length",
"selected_index",
"serialize",
"serialized",
"set_char",
"set_style",
"size_policy",
"static_width",
"styles",
"width",
"_bindings",
"_get_char",
"_get_style",
"_id",
"_id_manager",
"_selectables_length",
"_serialized_fields",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__iter__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """The module containing all of the layout-related widgets."""
# These widgets have more than the 7 allowed instance attributes.
# pylint: disable=too-many-instance-attributes
from __future__ import annotations
from itertools import zip_longest
from typing import Any, Callable, Iterator, cast
from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal
from ..context_managers import cursor_at
from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment
from ..exceptions import WidthExceededError
from ..helpers import real_length
from ..input import keys
from . import boxes
from . import styles as w_styles
from .base import Widget
class Container(Widget):
"""A widget that displays other widgets, stacked vertically."""
chars: dict[str, w_styles.CharType] = {
"border": ["| ", "-", " |", "-"],
"corner": [""] * 4,
}
styles = {
"border": w_styles.MARKUP,
"corner": w_styles.MARKUP,
"fill": w_styles.BACKGROUND,
}
keys = {
"next": {keys.DOWN, keys.CTRL_N, "j"},
"previous": {keys.UP, keys.CTRL_P, "k"},
}
serialized = Widget.serialized + ["_centered_axis"]
vertical_align = VerticalAlignment.CENTER
allow_fullscreen = True
# TODO: Add `WidgetConvertible`? type instead of Any
def __init__(self, *widgets: Any, **attrs: Any) -> None:
"""Initialize Container data"""
super(). | (**attrs)
# TODO: This is just a band-aid.
if "width" not in attrs:
self.width = 40
self._widgets: list[Widget] = []
self._centered_axis: CenteringPolicy | None = None
self._prev_screen: tuple[int, int] = (0, 0)
self._has_printed = False
self.styles = type(self).styles.copy()
self.chars = type(self).chars.copy()
for widget in widgets:
self._add_widget(widget)
self._drag_target: Widget | None = None
terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis))
@property
def sidelength(self) -> int:
"""Gets the length of left and right borders combined.
Returns:
An integer equal to the `pytermgui.helpers.real_length` of the concatenation of
the left and right borders of this widget, both with their respective styles
applied.
"""
chars = self._get_char("border")
style = self._get_style("border")
if not isinstance(chars, list):
return 0
left_border, _, right_border, _ = chars
return real_length(style(left_border) + style(right_border))
@property
def selectables(self) -> list[tuple[Widget, int]]:
"""Gets all selectable widgets and their inner indices.
This is used in order to have a constant reference to all selectable indices within this
widget.
Returns:
A list of tuples containing a widget and an integer each. For each widget that is
withing this one, it is added to this list as many times as it has selectables. Each
of the integers correspond to a selectable_index within the widget.
For example, a Container with a Button, InputField and an inner Container containing
3 selectables might return something like this:
```
[
(Button(...), 0),
(InputField(...), 0),
(Container(...), 0),
(Container(...), 1),
(Container(...), 2),
]
```
"""
_selectables: list[tuple[Widget, int]] = []
for widget in self._widgets:
if not widget.is_selectable:
continue
for i, (inner, _) in enumerate(widget.selectables):
_selectables.append((inner, i))
return _selectables
@property
def selectables_length(self) -> int:
"""Gets the length of the selectables list.
Returns:
An integer equal to the length of `self.selectables`.
"""
return len(self.selectables)
@property
def selected(self) -> Widget | None:
"""Returns the currently selected object
Returns:
The currently selected widget if selected_index is not None,
otherwise None.
"""
# TODO: Add deeper selection
if self.selected_index is None:
return None
if self.selected_index >= len(self.selectables):
return None
return self.selectables[self.selected_index][0]
@property
def box(self) -> boxes.Box:
"""Returns current box setting
Returns:
The currently set box instance.
"""
return self._box
@box.setter
def box(self, new: str | boxes.Box) -> None:
"""Applies a new box.
Args:
new: Either a `pytermgui.boxes.Box` instance or a string
analogous to one of the default box names.
"""
if isinstance(new, str):
from_module = vars(boxes).get(new)
if from_module is None:
raise ValueError(f"Unknown box type {new}.")
new = from_module
assert isinstance(new, boxes.Box)
self._box = new
new.set_chars_of(self)
def __iadd__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self._add_widget(other)
return self
def __add__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
This method is analogous to `Container.__iadd__`.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self.__iadd__(other)
return self
def __iter__(self) -> Iterator[Widget]:
"""Gets an iterator of self._widgets.
Yields:
The next widget.
"""
for widget in self._widgets:
yield widget
def __len__(self) -> int:
"""Gets the length of the widgets list.
Returns:
An integer describing len(self._widgets).
"""
return len(self._widgets)
def __getitem__(self, sli: int | slice) -> Widget | list[Widget]:
"""Gets an item from self._widgets.
Args:
sli: Slice of the list.
Returns:
The slice in the list.
"""
return self._widgets[sli]
def __setitem__(self, index: int, value: Any) -> None:
"""Sets an item in self._widgets.
Args:
index: The index to be set.
value: The new widget at this index.
"""
self._widgets[index] = value
def __contains__(self, other: object) -> bool:
"""Determines if self._widgets contains other widget.
Args:
other: Any widget-like.
Returns:
A boolean describing whether `other` is in `self.widgets`
"""
return other in self._widgets
def _add_widget(self, other: object, run_get_lines: bool = True) -> None:
"""Adds other to this widget.
Args:
other: Any widget-like object.
run_get_lines: Boolean controlling whether the self.get_lines is ran.
"""
if not isinstance(other, Widget):
to_widget = Widget.from_data(other)
if to_widget is None:
raise ValueError(
f"Could not convert {other} of type {type(other)} to a Widget!"
)
other = to_widget
# This is safe to do, as it would've raised an exception above already
assert isinstance(other, Widget)
self._widgets.append(other)
if isinstance(other, Container):
other.set_recursive_depth(self.depth + 2)
else:
other.depth = self.depth + 1
other.get_lines()
other.parent = self
if run_get_lines:
self.get_lines()
def _get_aligners(
self, widget: Widget, borders: tuple[str, str]
) -> tuple[Callable[[str], str], int]:
"""Gets an aligning method and position offset.
Args:
widget: The widget to align.
borders: The left and right borders to put the widget within.
Returns:
A tuple of a method that, when called with a line, will return that line
centered using the passed in widget's parent_align and width, as well as
the horizontal offset resulting from the widget being aligned.
"""
left, right = borders
char = self._get_style("fill")(" ")
def _align_left(text: str) -> str:
"""Align line to the left"""
padding = self.width - real_length(left + right) - real_length(text)
return left + text + padding * char + right
def _align_center(text: str) -> str:
"""Align line to the center"""
total = self.width - real_length(left + right) - real_length(text)
padding, offset = divmod(total, 2)
return left + (padding + offset) * char + text + padding * char + right
def _align_right(text: str) -> str:
"""Align line to the right"""
padding = self.width - real_length(left + right) - real_length(text)
return left + padding * char + text + right
if widget.parent_align == HorizontalAlignment.CENTER:
total = self.width - real_length(left + right) - widget.width
padding, offset = divmod(total, 2)
return _align_center, real_length(left) + padding + offset
if widget.parent_align == HorizontalAlignment.RIGHT:
return _align_right, self.width - real_length(left) - widget.width
# Default to left-aligned
return _align_left, real_length(left)
def _update_width(self, widget: Widget) -> None:
"""Updates the width of widget or self.
This method respects widget.size_policy.
Args:
widget: The widget to update/base updates on.
"""
available = (
self.width - self.sidelength - (0 if isinstance(widget, Container) else 1)
)
if widget.size_policy == SizePolicy.FILL:
widget.width = available
return
if widget.size_policy == SizePolicy.RELATIVE:
widget.width = widget.relative_width * available
return
if widget.width > available:
if widget.size_policy == SizePolicy.STATIC:
raise WidthExceededError(
f"Widget {widget}'s static width of {widget.width}"
+ f" exceeds its parent's available width {available}."
""
)
widget.width = available
def _apply_vertalign(
self, lines: list[str], diff: int, padder: str
) -> tuple[int, list[str]]:
"""Insert padder line into lines diff times, depending on self.vertical_align.
Args:
lines: The list of lines to align.
diff: The available height.
padder: The line to use to pad.
Returns:
A tuple containing the vertical offset as well as the padded list of lines.
Raises:
NotImplementedError: The given vertical alignment is not implemented.
"""
if self.vertical_align == VerticalAlignment.BOTTOM:
for _ in range(diff):
lines.insert(0, padder)
return diff, lines
if self.vertical_align == VerticalAlignment.TOP:
for _ in range(diff):
lines.append(padder)
return 0, lines
if self.vertical_align == VerticalAlignment.CENTER:
top, extra = divmod(diff, 2)
bottom = top + extra
for _ in range(top):
lines.insert(0, padder)
for _ in range(bottom):
lines.append(padder)
return top, lines
raise NotImplementedError(
f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}."
)
def get_lines(self) -> list[str]:
"""Gets all lines by spacing out inner widgets.
This method reflects & applies both width settings, as well as
the `parent_align` field.
Returns:
A list of all lines that represent this Container.
"""
def _get_border(left: str, char: str, right: str) -> str:
"""Gets a top or bottom border.
Args:
left: Left corner character.
char: Border character filling between left & right.
right: Right corner character.
Returns:
The border line.
"""
offset = real_length(left + right)
return left + char * (self.width - offset) + right
lines = []
style = self._get_style("border")
borders = [style(char) for char in self._get_char("border")]
style = self._get_style("corner")
corners = [style(char) for char in self._get_char("corner")]
has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0)
align = lambda item: item
for widget in self._widgets:
align, offset = self._get_aligners(widget, (borders[0], borders[2]))
self._update_width(widget)
widget.pos = (
self.pos[0] + offset,
self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0),
)
widget_lines = []
for line in widget.get_lines():
widget_lines.append(align(line))
lines.extend(widget_lines)
vertical_offset, lines = self._apply_vertalign(
lines, self.height - len(lines) - sum(has_top_bottom), align("")
)
for widget in self._widgets:
widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset)
# TODO: This is wasteful.
widget.get_lines()
if has_top_bottom[0]:
lines.insert(0, _get_border(corners[0], borders[1], corners[1]))
if has_top_bottom[1]:
lines.append(_get_border(corners[3], borders[3], corners[2]))
self.height = len(lines)
return lines
def set_widgets(self, new: list[Widget]) -> None:
"""Sets new list in place of self._widgets.
Args:
new: The new widget list.
"""
self._widgets = []
for widget in new:
self._add_widget(widget)
def serialize(self) -> dict[str, Any]:
"""Serializes this Container, adding in serializations of all widgets.
See `pytermgui.widgets.base.Widget.serialize` for more info.
Returns:
The dictionary containing all serialized data.
"""
out = super().serialize()
out["_widgets"] = []
for widget in self._widgets:
out["_widgets"].append(widget.serialize())
return out
def pop(self, index: int = -1) -> Widget:
"""Pops widget from self._widgets.
Analogous to self._widgets.pop(index).
Args:
index: The index to operate on.
Returns:
The widget that was popped off the list.
"""
return self._widgets.pop(index)
def remove(self, other: Widget) -> None:
"""Remove widget from self._widgets
Analogous to self._widgets.remove(other).
Args:
widget: The widget to remove.
"""
return self._widgets.remove(other)
def set_recursive_depth(self, value: int) -> None:
"""Set depth for this Container and all its children.
All inner widgets will receive value+1 as their new depth.
Args:
value: The new depth to use as the base depth.
"""
self.depth = value
for widget in self._widgets:
if isinstance(widget, Container):
widget.set_recursive_depth(value + 1)
else:
widget.depth = value
def select(self, index: int | None = None) -> None:
"""Selects inner subwidget.
Args:
index: The index to select.
Raises:
IndexError: The index provided was beyond len(self.selectables).
"""
# Unselect all sub-elements
for other in self._widgets:
if other.selectables_length > 0:
other.select(None)
if index is not None:
if index >= len(self.selectables) is None:
raise IndexError("Container selection index out of range")
widget, inner_index = self.selectables[index]
widget.select(inner_index)
self.selected_index = index
def center(
self, where: CenteringPolicy | None = None, store: bool = True
) -> Container:
"""Centers this object to the given axis.
Args:
where: A CenteringPolicy describing the place to center to
store: When set, this centering will be reapplied during every
print, as well as when calling this method with no arguments.
Returns:
This Container.
"""
# Refresh in case changes happened
self.get_lines()
if where is None:
# See `enums.py` for explanation about this ignore.
where = CenteringPolicy.get_default() # type: ignore
centerx = centery = where is CenteringPolicy.ALL
centerx |= where is CenteringPolicy.HORIZONTAL
centery |= where is CenteringPolicy.VERTICAL
pos = list(self.pos)
if centerx:
pos[0] = (terminal.width - self.width + 2) // 2
if centery:
pos[1] = (terminal.height - self.height + 2) // 2
self.pos = (pos[0], pos[1])
if store:
self._centered_axis = where
self._prev_screen = terminal.size
return self
def handle_mouse(self, event: MouseEvent) -> bool:
"""Applies a mouse event on all children.
Args:
event: The event to handle
Returns:
A boolean showing whether the event was handled.
"""
if event.action is MouseAction.RELEASE:
# Force RELEASE event to be sent
if self._drag_target is not None:
self._drag_target.handle_mouse(
MouseEvent(MouseAction.RELEASE, event.position)
)
self._drag_target = None
if self._drag_target is not None:
return self._drag_target.handle_mouse(event)
selectables_index = 0
for widget in self._widgets:
if widget.contains(event.position):
handled = widget.handle_mouse(event)
if widget.selected_index is not None:
selectables_index += widget.selected_index
if event.action is MouseAction.LEFT_CLICK:
self._drag_target = widget
if handled:
self.select(selectables_index)
return handled
if widget.is_selectable:
selectables_index += widget.selectables_length
return False
def handle_key(self, key: str) -> bool:
"""Handles a keypress, returns its success.
Args:
key: A key str.
Returns:
A boolean showing whether the key was handled.
"""
def _is_nav(key: str) -> bool:
"""Determine if a key is in the navigation sets"""
return key in self.keys["next"] | self.keys["previous"]
if self.selected is not None and self.selected.handle_key(key):
return True
# Only use navigation when there is more than one selectable
if self.selectables_length > 1 and _is_nav(key):
handled = False
if self.selected_index is None:
self.select(0)
assert isinstance(self.selected_index, int)
if key in self.keys["previous"]:
# No more selectables left, user wants to exit Container
# upwards.
if self.selected_index == 0:
return False
self.select(self.selected_index - 1)
handled = True
elif key in self.keys["next"]:
# Stop selection at last element, return as unhandled
new = self.selected_index + 1
if new == len(self.selectables):
return False
self.select(new)
handled = True
if handled:
return True
if key == keys.ENTER and self.selected is not None:
if self.selected.selected_index is not None:
self.selected.handle_key(key)
return True
return False
def wipe(self) -> None:
"""Wipes the characters occupied by the object"""
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(real_length(line) * " ")
def print(self) -> None:
"""Prints this Container.
If the screen size has changed since last `print` call, the object
will be centered based on its `_centered_axis`.
"""
if not terminal.size == self._prev_screen:
clear()
self.center(self._centered_axis)
self._prev_screen = terminal.size
if self.allow_fullscreen:
self.pos = terminal.origin
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(line)
self._has_printed = True
def debug(self) -> str:
"""Returns a string with identifiable information on this widget.
Returns:
A str in the form of a class construction. This string is in a form that
__could have been__ used to create this Container.
"""
out = "Container("
for widget in self._widgets:
out += widget.debug() + ", "
out = out.strip(", ")
out += ", **attrs)"
return out
class Splitter(Container):
"""A widget that displays other widgets, stacked horizontally."""
chars: dict[str, list[str] | str] = {"separator": " | "}
styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND}
keys = {
"previous": {keys.LEFT, "h", keys.CTRL_B},
"next": {keys.RIGHT, "l", keys.CTRL_F},
}
parent_align = HorizontalAlignment.RIGHT
def _align(
self, alignment: HorizontalAlignment, target_width: int, line: str
) -> tuple[int, str]:
"""Align a line
r/wordavalanches"""
available = target_width - real_length(line)
fill_style = self._get_style("fill")
char = fill_style(" ")
line = fill_style(line)
if alignment == HorizontalAlignment.CENTER:
padding, offset = divmod(available, 2)
return padding, padding * char + line + (padding + offset) * char
if alignment == HorizontalAlignment.RIGHT:
return available, available * char + line
return 0, line + available * char
def get_lines(self) -> list[str]:
"""Join all widgets horizontally."""
# An error will be raised if `separator` is not the correct type (str).
separator = self._get_style("separator")(self._get_char("separator")) # type: ignore
separator_length = real_length(separator)
target_width, error = divmod(
self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets)
)
vertical_lines = []
total_offset = 0
for widget in self._widgets:
inner = []
if widget.size_policy is SizePolicy.STATIC:
target_width += target_width - widget.width
width = target_width
else:
widget.width = target_width + error
width = widget.width
error = 0
aligned: str | None = None
for line in widget.get_lines():
# See `enums.py` for information about this ignore
padding, aligned = self._align(
cast(HorizontalAlignment, widget.parent_align), width, line
)
inner.append(aligned)
widget.pos = (
self.pos[0] + padding + total_offset,
self.pos[1] + (1 if type(widget).__name__ == "Container" else 0),
)
if aligned is not None:
total_offset += real_length(inner[-1]) + separator_length
vertical_lines.append(inner)
lines = []
for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width):
lines.append((reset() + separator).join(horizontal))
return lines
def debug(self) -> str:
"""Return identifiable information"""
return super().debug().replace("Container", "Splitter", 1)
| bczsalba__pytermgui |
54 | 54-52-17 | inproject | width | [
"allow_fullscreen",
"bind",
"bindings",
"box",
"center",
"chars",
"contains",
"copy",
"debug",
"depth",
"execute_binding",
"get_lines",
"handle_key",
"handle_mouse",
"height",
"id",
"is_bindable",
"is_selectable",
"keys",
"parent",
"parent_align",
"pop",
"pos",
"print",
"remove",
"select",
"selectables",
"selectables_length",
"selected",
"selected_index",
"serialize",
"serialized",
"set_char",
"set_recursive_depth",
"set_style",
"set_widgets",
"sidelength",
"size_policy",
"static_width",
"styles",
"vertical_align",
"width",
"wipe",
"_add_widget",
"_apply_vertalign",
"_bindings",
"_box",
"_centered_axis",
"_drag_target",
"_get_aligners",
"_get_char",
"_get_style",
"_has_printed",
"_id",
"_id_manager",
"_prev_screen",
"_selectables_length",
"_serialized_fields",
"_update_width",
"_widgets",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__getitem__",
"__hash__",
"__iadd__",
"__init__",
"__init_subclass__",
"__iter__",
"__len__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__setitem__",
"__sizeof__",
"__slots__",
"__str__"
] | """The module containing all of the layout-related widgets."""
# These widgets have more than the 7 allowed instance attributes.
# pylint: disable=too-many-instance-attributes
from __future__ import annotations
from itertools import zip_longest
from typing import Any, Callable, Iterator, cast
from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal
from ..context_managers import cursor_at
from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment
from ..exceptions import WidthExceededError
from ..helpers import real_length
from ..input import keys
from . import boxes
from . import styles as w_styles
from .base import Widget
class Container(Widget):
"""A widget that displays other widgets, stacked vertically."""
chars: dict[str, w_styles.CharType] = {
"border": ["| ", "-", " |", "-"],
"corner": [""] * 4,
}
styles = {
"border": w_styles.MARKUP,
"corner": w_styles.MARKUP,
"fill": w_styles.BACKGROUND,
}
keys = {
"next": {keys.DOWN, keys.CTRL_N, "j"},
"previous": {keys.UP, keys.CTRL_P, "k"},
}
serialized = Widget.serialized + ["_centered_axis"]
vertical_align = VerticalAlignment.CENTER
allow_fullscreen = True
# TODO: Add `WidgetConvertible`? type instead of Any
def __init__(self, *widgets: Any, **attrs: Any) -> None:
"""Initialize Container data"""
super().__init__(**attrs)
# TODO: This is just a band-aid.
if "width" not in attrs:
self. | = 40
self._widgets: list[Widget] = []
self._centered_axis: CenteringPolicy | None = None
self._prev_screen: tuple[int, int] = (0, 0)
self._has_printed = False
self.styles = type(self).styles.copy()
self.chars = type(self).chars.copy()
for widget in widgets:
self._add_widget(widget)
self._drag_target: Widget | None = None
terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis))
@property
def sidelength(self) -> int:
"""Gets the length of left and right borders combined.
Returns:
An integer equal to the `pytermgui.helpers.real_length` of the concatenation of
the left and right borders of this widget, both with their respective styles
applied.
"""
chars = self._get_char("border")
style = self._get_style("border")
if not isinstance(chars, list):
return 0
left_border, _, right_border, _ = chars
return real_length(style(left_border) + style(right_border))
@property
def selectables(self) -> list[tuple[Widget, int]]:
"""Gets all selectable widgets and their inner indices.
This is used in order to have a constant reference to all selectable indices within this
widget.
Returns:
A list of tuples containing a widget and an integer each. For each widget that is
withing this one, it is added to this list as many times as it has selectables. Each
of the integers correspond to a selectable_index within the widget.
For example, a Container with a Button, InputField and an inner Container containing
3 selectables might return something like this:
```
[
(Button(...), 0),
(InputField(...), 0),
(Container(...), 0),
(Container(...), 1),
(Container(...), 2),
]
```
"""
_selectables: list[tuple[Widget, int]] = []
for widget in self._widgets:
if not widget.is_selectable:
continue
for i, (inner, _) in enumerate(widget.selectables):
_selectables.append((inner, i))
return _selectables
@property
def selectables_length(self) -> int:
"""Gets the length of the selectables list.
Returns:
An integer equal to the length of `self.selectables`.
"""
return len(self.selectables)
@property
def selected(self) -> Widget | None:
"""Returns the currently selected object
Returns:
The currently selected widget if selected_index is not None,
otherwise None.
"""
# TODO: Add deeper selection
if self.selected_index is None:
return None
if self.selected_index >= len(self.selectables):
return None
return self.selectables[self.selected_index][0]
@property
def box(self) -> boxes.Box:
"""Returns current box setting
Returns:
The currently set box instance.
"""
return self._box
@box.setter
def box(self, new: str | boxes.Box) -> None:
"""Applies a new box.
Args:
new: Either a `pytermgui.boxes.Box` instance or a string
analogous to one of the default box names.
"""
if isinstance(new, str):
from_module = vars(boxes).get(new)
if from_module is None:
raise ValueError(f"Unknown box type {new}.")
new = from_module
assert isinstance(new, boxes.Box)
self._box = new
new.set_chars_of(self)
def __iadd__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self._add_widget(other)
return self
def __add__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
This method is analogous to `Container.__iadd__`.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self.__iadd__(other)
return self
def __iter__(self) -> Iterator[Widget]:
"""Gets an iterator of self._widgets.
Yields:
The next widget.
"""
for widget in self._widgets:
yield widget
def __len__(self) -> int:
"""Gets the length of the widgets list.
Returns:
An integer describing len(self._widgets).
"""
return len(self._widgets)
def __getitem__(self, sli: int | slice) -> Widget | list[Widget]:
"""Gets an item from self._widgets.
Args:
sli: Slice of the list.
Returns:
The slice in the list.
"""
return self._widgets[sli]
def __setitem__(self, index: int, value: Any) -> None:
"""Sets an item in self._widgets.
Args:
index: The index to be set.
value: The new widget at this index.
"""
self._widgets[index] = value
def __contains__(self, other: object) -> bool:
"""Determines if self._widgets contains other widget.
Args:
other: Any widget-like.
Returns:
A boolean describing whether `other` is in `self.widgets`
"""
return other in self._widgets
def _add_widget(self, other: object, run_get_lines: bool = True) -> None:
"""Adds other to this widget.
Args:
other: Any widget-like object.
run_get_lines: Boolean controlling whether the self.get_lines is ran.
"""
if not isinstance(other, Widget):
to_widget = Widget.from_data(other)
if to_widget is None:
raise ValueError(
f"Could not convert {other} of type {type(other)} to a Widget!"
)
other = to_widget
# This is safe to do, as it would've raised an exception above already
assert isinstance(other, Widget)
self._widgets.append(other)
if isinstance(other, Container):
other.set_recursive_depth(self.depth + 2)
else:
other.depth = self.depth + 1
other.get_lines()
other.parent = self
if run_get_lines:
self.get_lines()
def _get_aligners(
self, widget: Widget, borders: tuple[str, str]
) -> tuple[Callable[[str], str], int]:
"""Gets an aligning method and position offset.
Args:
widget: The widget to align.
borders: The left and right borders to put the widget within.
Returns:
A tuple of a method that, when called with a line, will return that line
centered using the passed in widget's parent_align and width, as well as
the horizontal offset resulting from the widget being aligned.
"""
left, right = borders
char = self._get_style("fill")(" ")
def _align_left(text: str) -> str:
"""Align line to the left"""
padding = self.width - real_length(left + right) - real_length(text)
return left + text + padding * char + right
def _align_center(text: str) -> str:
"""Align line to the center"""
total = self.width - real_length(left + right) - real_length(text)
padding, offset = divmod(total, 2)
return left + (padding + offset) * char + text + padding * char + right
def _align_right(text: str) -> str:
"""Align line to the right"""
padding = self.width - real_length(left + right) - real_length(text)
return left + padding * char + text + right
if widget.parent_align == HorizontalAlignment.CENTER:
total = self.width - real_length(left + right) - widget.width
padding, offset = divmod(total, 2)
return _align_center, real_length(left) + padding + offset
if widget.parent_align == HorizontalAlignment.RIGHT:
return _align_right, self.width - real_length(left) - widget.width
# Default to left-aligned
return _align_left, real_length(left)
def _update_width(self, widget: Widget) -> None:
"""Updates the width of widget or self.
This method respects widget.size_policy.
Args:
widget: The widget to update/base updates on.
"""
available = (
self.width - self.sidelength - (0 if isinstance(widget, Container) else 1)
)
if widget.size_policy == SizePolicy.FILL:
widget.width = available
return
if widget.size_policy == SizePolicy.RELATIVE:
widget.width = widget.relative_width * available
return
if widget.width > available:
if widget.size_policy == SizePolicy.STATIC:
raise WidthExceededError(
f"Widget {widget}'s static width of {widget.width}"
+ f" exceeds its parent's available width {available}."
""
)
widget.width = available
def _apply_vertalign(
self, lines: list[str], diff: int, padder: str
) -> tuple[int, list[str]]:
"""Insert padder line into lines diff times, depending on self.vertical_align.
Args:
lines: The list of lines to align.
diff: The available height.
padder: The line to use to pad.
Returns:
A tuple containing the vertical offset as well as the padded list of lines.
Raises:
NotImplementedError: The given vertical alignment is not implemented.
"""
if self.vertical_align == VerticalAlignment.BOTTOM:
for _ in range(diff):
lines.insert(0, padder)
return diff, lines
if self.vertical_align == VerticalAlignment.TOP:
for _ in range(diff):
lines.append(padder)
return 0, lines
if self.vertical_align == VerticalAlignment.CENTER:
top, extra = divmod(diff, 2)
bottom = top + extra
for _ in range(top):
lines.insert(0, padder)
for _ in range(bottom):
lines.append(padder)
return top, lines
raise NotImplementedError(
f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}."
)
def get_lines(self) -> list[str]:
"""Gets all lines by spacing out inner widgets.
This method reflects & applies both width settings, as well as
the `parent_align` field.
Returns:
A list of all lines that represent this Container.
"""
def _get_border(left: str, char: str, right: str) -> str:
"""Gets a top or bottom border.
Args:
left: Left corner character.
char: Border character filling between left & right.
right: Right corner character.
Returns:
The border line.
"""
offset = real_length(left + right)
return left + char * (self.width - offset) + right
lines = []
style = self._get_style("border")
borders = [style(char) for char in self._get_char("border")]
style = self._get_style("corner")
corners = [style(char) for char in self._get_char("corner")]
has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0)
align = lambda item: item
for widget in self._widgets:
align, offset = self._get_aligners(widget, (borders[0], borders[2]))
self._update_width(widget)
widget.pos = (
self.pos[0] + offset,
self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0),
)
widget_lines = []
for line in widget.get_lines():
widget_lines.append(align(line))
lines.extend(widget_lines)
vertical_offset, lines = self._apply_vertalign(
lines, self.height - len(lines) - sum(has_top_bottom), align("")
)
for widget in self._widgets:
widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset)
# TODO: This is wasteful.
widget.get_lines()
if has_top_bottom[0]:
lines.insert(0, _get_border(corners[0], borders[1], corners[1]))
if has_top_bottom[1]:
lines.append(_get_border(corners[3], borders[3], corners[2]))
self.height = len(lines)
return lines
def set_widgets(self, new: list[Widget]) -> None:
"""Sets new list in place of self._widgets.
Args:
new: The new widget list.
"""
self._widgets = []
for widget in new:
self._add_widget(widget)
def serialize(self) -> dict[str, Any]:
"""Serializes this Container, adding in serializations of all widgets.
See `pytermgui.widgets.base.Widget.serialize` for more info.
Returns:
The dictionary containing all serialized data.
"""
out = super().serialize()
out["_widgets"] = []
for widget in self._widgets:
out["_widgets"].append(widget.serialize())
return out
def pop(self, index: int = -1) -> Widget:
"""Pops widget from self._widgets.
Analogous to self._widgets.pop(index).
Args:
index: The index to operate on.
Returns:
The widget that was popped off the list.
"""
return self._widgets.pop(index)
def remove(self, other: Widget) -> None:
"""Remove widget from self._widgets
Analogous to self._widgets.remove(other).
Args:
widget: The widget to remove.
"""
return self._widgets.remove(other)
def set_recursive_depth(self, value: int) -> None:
"""Set depth for this Container and all its children.
All inner widgets will receive value+1 as their new depth.
Args:
value: The new depth to use as the base depth.
"""
self.depth = value
for widget in self._widgets:
if isinstance(widget, Container):
widget.set_recursive_depth(value + 1)
else:
widget.depth = value
def select(self, index: int | None = None) -> None:
"""Selects inner subwidget.
Args:
index: The index to select.
Raises:
IndexError: The index provided was beyond len(self.selectables).
"""
# Unselect all sub-elements
for other in self._widgets:
if other.selectables_length > 0:
other.select(None)
if index is not None:
if index >= len(self.selectables) is None:
raise IndexError("Container selection index out of range")
widget, inner_index = self.selectables[index]
widget.select(inner_index)
self.selected_index = index
def center(
self, where: CenteringPolicy | None = None, store: bool = True
) -> Container:
"""Centers this object to the given axis.
Args:
where: A CenteringPolicy describing the place to center to
store: When set, this centering will be reapplied during every
print, as well as when calling this method with no arguments.
Returns:
This Container.
"""
# Refresh in case changes happened
self.get_lines()
if where is None:
# See `enums.py` for explanation about this ignore.
where = CenteringPolicy.get_default() # type: ignore
centerx = centery = where is CenteringPolicy.ALL
centerx |= where is CenteringPolicy.HORIZONTAL
centery |= where is CenteringPolicy.VERTICAL
pos = list(self.pos)
if centerx:
pos[0] = (terminal.width - self.width + 2) // 2
if centery:
pos[1] = (terminal.height - self.height + 2) // 2
self.pos = (pos[0], pos[1])
if store:
self._centered_axis = where
self._prev_screen = terminal.size
return self
def handle_mouse(self, event: MouseEvent) -> bool:
"""Applies a mouse event on all children.
Args:
event: The event to handle
Returns:
A boolean showing whether the event was handled.
"""
if event.action is MouseAction.RELEASE:
# Force RELEASE event to be sent
if self._drag_target is not None:
self._drag_target.handle_mouse(
MouseEvent(MouseAction.RELEASE, event.position)
)
self._drag_target = None
if self._drag_target is not None:
return self._drag_target.handle_mouse(event)
selectables_index = 0
for widget in self._widgets:
if widget.contains(event.position):
handled = widget.handle_mouse(event)
if widget.selected_index is not None:
selectables_index += widget.selected_index
if event.action is MouseAction.LEFT_CLICK:
self._drag_target = widget
if handled:
self.select(selectables_index)
return handled
if widget.is_selectable:
selectables_index += widget.selectables_length
return False
def handle_key(self, key: str) -> bool:
"""Handles a keypress, returns its success.
Args:
key: A key str.
Returns:
A boolean showing whether the key was handled.
"""
def _is_nav(key: str) -> bool:
"""Determine if a key is in the navigation sets"""
return key in self.keys["next"] | self.keys["previous"]
if self.selected is not None and self.selected.handle_key(key):
return True
# Only use navigation when there is more than one selectable
if self.selectables_length > 1 and _is_nav(key):
handled = False
if self.selected_index is None:
self.select(0)
assert isinstance(self.selected_index, int)
if key in self.keys["previous"]:
# No more selectables left, user wants to exit Container
# upwards.
if self.selected_index == 0:
return False
self.select(self.selected_index - 1)
handled = True
elif key in self.keys["next"]:
# Stop selection at last element, return as unhandled
new = self.selected_index + 1
if new == len(self.selectables):
return False
self.select(new)
handled = True
if handled:
return True
if key == keys.ENTER and self.selected is not None:
if self.selected.selected_index is not None:
self.selected.handle_key(key)
return True
return False
def wipe(self) -> None:
"""Wipes the characters occupied by the object"""
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(real_length(line) * " ")
def print(self) -> None:
"""Prints this Container.
If the screen size has changed since last `print` call, the object
will be centered based on its `_centered_axis`.
"""
if not terminal.size == self._prev_screen:
clear()
self.center(self._centered_axis)
self._prev_screen = terminal.size
if self.allow_fullscreen:
self.pos = terminal.origin
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(line)
self._has_printed = True
def debug(self) -> str:
"""Returns a string with identifiable information on this widget.
Returns:
A str in the form of a class construction. This string is in a form that
__could have been__ used to create this Container.
"""
out = "Container("
for widget in self._widgets:
out += widget.debug() + ", "
out = out.strip(", ")
out += ", **attrs)"
return out
class Splitter(Container):
"""A widget that displays other widgets, stacked horizontally."""
chars: dict[str, list[str] | str] = {"separator": " | "}
styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND}
keys = {
"previous": {keys.LEFT, "h", keys.CTRL_B},
"next": {keys.RIGHT, "l", keys.CTRL_F},
}
parent_align = HorizontalAlignment.RIGHT
def _align(
self, alignment: HorizontalAlignment, target_width: int, line: str
) -> tuple[int, str]:
"""Align a line
r/wordavalanches"""
available = target_width - real_length(line)
fill_style = self._get_style("fill")
char = fill_style(" ")
line = fill_style(line)
if alignment == HorizontalAlignment.CENTER:
padding, offset = divmod(available, 2)
return padding, padding * char + line + (padding + offset) * char
if alignment == HorizontalAlignment.RIGHT:
return available, available * char + line
return 0, line + available * char
def get_lines(self) -> list[str]:
"""Join all widgets horizontally."""
# An error will be raised if `separator` is not the correct type (str).
separator = self._get_style("separator")(self._get_char("separator")) # type: ignore
separator_length = real_length(separator)
target_width, error = divmod(
self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets)
)
vertical_lines = []
total_offset = 0
for widget in self._widgets:
inner = []
if widget.size_policy is SizePolicy.STATIC:
target_width += target_width - widget.width
width = target_width
else:
widget.width = target_width + error
width = widget.width
error = 0
aligned: str | None = None
for line in widget.get_lines():
# See `enums.py` for information about this ignore
padding, aligned = self._align(
cast(HorizontalAlignment, widget.parent_align), width, line
)
inner.append(aligned)
widget.pos = (
self.pos[0] + padding + total_offset,
self.pos[1] + (1 if type(widget).__name__ == "Container" else 0),
)
if aligned is not None:
total_offset += real_length(inner[-1]) + separator_length
vertical_lines.append(inner)
lines = []
for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width):
lines.append((reset() + separator).join(horizontal))
return lines
def debug(self) -> str:
"""Return identifiable information"""
return super().debug().replace("Container", "Splitter", 1)
| bczsalba__pytermgui |
54 | 54-54-13 | inproject | _widgets | [
"allow_fullscreen",
"bind",
"bindings",
"box",
"center",
"chars",
"contains",
"copy",
"debug",
"depth",
"execute_binding",
"get_lines",
"handle_key",
"handle_mouse",
"height",
"id",
"is_bindable",
"is_selectable",
"keys",
"parent",
"parent_align",
"pop",
"pos",
"print",
"remove",
"select",
"selectables",
"selectables_length",
"selected",
"selected_index",
"serialize",
"serialized",
"set_char",
"set_recursive_depth",
"set_style",
"set_widgets",
"sidelength",
"size_policy",
"static_width",
"styles",
"vertical_align",
"width",
"wipe",
"_add_widget",
"_apply_vertalign",
"_bindings",
"_box",
"_centered_axis",
"_drag_target",
"_get_aligners",
"_get_char",
"_get_style",
"_has_printed",
"_id",
"_id_manager",
"_prev_screen",
"_selectables_length",
"_serialized_fields",
"_update_width",
"_widgets",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__getitem__",
"__hash__",
"__iadd__",
"__init__",
"__init_subclass__",
"__iter__",
"__len__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__setitem__",
"__sizeof__",
"__slots__",
"__str__"
] | """The module containing all of the layout-related widgets."""
# These widgets have more than the 7 allowed instance attributes.
# pylint: disable=too-many-instance-attributes
from __future__ import annotations
from itertools import zip_longest
from typing import Any, Callable, Iterator, cast
from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal
from ..context_managers import cursor_at
from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment
from ..exceptions import WidthExceededError
from ..helpers import real_length
from ..input import keys
from . import boxes
from . import styles as w_styles
from .base import Widget
class Container(Widget):
"""A widget that displays other widgets, stacked vertically."""
chars: dict[str, w_styles.CharType] = {
"border": ["| ", "-", " |", "-"],
"corner": [""] * 4,
}
styles = {
"border": w_styles.MARKUP,
"corner": w_styles.MARKUP,
"fill": w_styles.BACKGROUND,
}
keys = {
"next": {keys.DOWN, keys.CTRL_N, "j"},
"previous": {keys.UP, keys.CTRL_P, "k"},
}
serialized = Widget.serialized + ["_centered_axis"]
vertical_align = VerticalAlignment.CENTER
allow_fullscreen = True
# TODO: Add `WidgetConvertible`? type instead of Any
def __init__(self, *widgets: Any, **attrs: Any) -> None:
"""Initialize Container data"""
super().__init__(**attrs)
# TODO: This is just a band-aid.
if "width" not in attrs:
self.width = 40
self. | : list[Widget] = []
self._centered_axis: CenteringPolicy | None = None
self._prev_screen: tuple[int, int] = (0, 0)
self._has_printed = False
self.styles = type(self).styles.copy()
self.chars = type(self).chars.copy()
for widget in widgets:
self._add_widget(widget)
self._drag_target: Widget | None = None
terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis))
@property
def sidelength(self) -> int:
"""Gets the length of left and right borders combined.
Returns:
An integer equal to the `pytermgui.helpers.real_length` of the concatenation of
the left and right borders of this widget, both with their respective styles
applied.
"""
chars = self._get_char("border")
style = self._get_style("border")
if not isinstance(chars, list):
return 0
left_border, _, right_border, _ = chars
return real_length(style(left_border) + style(right_border))
@property
def selectables(self) -> list[tuple[Widget, int]]:
"""Gets all selectable widgets and their inner indices.
This is used in order to have a constant reference to all selectable indices within this
widget.
Returns:
A list of tuples containing a widget and an integer each. For each widget that is
withing this one, it is added to this list as many times as it has selectables. Each
of the integers correspond to a selectable_index within the widget.
For example, a Container with a Button, InputField and an inner Container containing
3 selectables might return something like this:
```
[
(Button(...), 0),
(InputField(...), 0),
(Container(...), 0),
(Container(...), 1),
(Container(...), 2),
]
```
"""
_selectables: list[tuple[Widget, int]] = []
for widget in self._widgets:
if not widget.is_selectable:
continue
for i, (inner, _) in enumerate(widget.selectables):
_selectables.append((inner, i))
return _selectables
@property
def selectables_length(self) -> int:
"""Gets the length of the selectables list.
Returns:
An integer equal to the length of `self.selectables`.
"""
return len(self.selectables)
@property
def selected(self) -> Widget | None:
"""Returns the currently selected object
Returns:
The currently selected widget if selected_index is not None,
otherwise None.
"""
# TODO: Add deeper selection
if self.selected_index is None:
return None
if self.selected_index >= len(self.selectables):
return None
return self.selectables[self.selected_index][0]
@property
def box(self) -> boxes.Box:
"""Returns current box setting
Returns:
The currently set box instance.
"""
return self._box
@box.setter
def box(self, new: str | boxes.Box) -> None:
"""Applies a new box.
Args:
new: Either a `pytermgui.boxes.Box` instance or a string
analogous to one of the default box names.
"""
if isinstance(new, str):
from_module = vars(boxes).get(new)
if from_module is None:
raise ValueError(f"Unknown box type {new}.")
new = from_module
assert isinstance(new, boxes.Box)
self._box = new
new.set_chars_of(self)
def __iadd__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self._add_widget(other)
return self
def __add__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
This method is analogous to `Container.__iadd__`.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self.__iadd__(other)
return self
def __iter__(self) -> Iterator[Widget]:
"""Gets an iterator of self._widgets.
Yields:
The next widget.
"""
for widget in self._widgets:
yield widget
def __len__(self) -> int:
"""Gets the length of the widgets list.
Returns:
An integer describing len(self._widgets).
"""
return len(self._widgets)
def __getitem__(self, sli: int | slice) -> Widget | list[Widget]:
"""Gets an item from self._widgets.
Args:
sli: Slice of the list.
Returns:
The slice in the list.
"""
return self._widgets[sli]
def __setitem__(self, index: int, value: Any) -> None:
"""Sets an item in self._widgets.
Args:
index: The index to be set.
value: The new widget at this index.
"""
self._widgets[index] = value
def __contains__(self, other: object) -> bool:
"""Determines if self._widgets contains other widget.
Args:
other: Any widget-like.
Returns:
A boolean describing whether `other` is in `self.widgets`
"""
return other in self._widgets
def _add_widget(self, other: object, run_get_lines: bool = True) -> None:
"""Adds other to this widget.
Args:
other: Any widget-like object.
run_get_lines: Boolean controlling whether the self.get_lines is ran.
"""
if not isinstance(other, Widget):
to_widget = Widget.from_data(other)
if to_widget is None:
raise ValueError(
f"Could not convert {other} of type {type(other)} to a Widget!"
)
other = to_widget
# This is safe to do, as it would've raised an exception above already
assert isinstance(other, Widget)
self._widgets.append(other)
if isinstance(other, Container):
other.set_recursive_depth(self.depth + 2)
else:
other.depth = self.depth + 1
other.get_lines()
other.parent = self
if run_get_lines:
self.get_lines()
def _get_aligners(
self, widget: Widget, borders: tuple[str, str]
) -> tuple[Callable[[str], str], int]:
"""Gets an aligning method and position offset.
Args:
widget: The widget to align.
borders: The left and right borders to put the widget within.
Returns:
A tuple of a method that, when called with a line, will return that line
centered using the passed in widget's parent_align and width, as well as
the horizontal offset resulting from the widget being aligned.
"""
left, right = borders
char = self._get_style("fill")(" ")
def _align_left(text: str) -> str:
"""Align line to the left"""
padding = self.width - real_length(left + right) - real_length(text)
return left + text + padding * char + right
def _align_center(text: str) -> str:
"""Align line to the center"""
total = self.width - real_length(left + right) - real_length(text)
padding, offset = divmod(total, 2)
return left + (padding + offset) * char + text + padding * char + right
def _align_right(text: str) -> str:
"""Align line to the right"""
padding = self.width - real_length(left + right) - real_length(text)
return left + padding * char + text + right
if widget.parent_align == HorizontalAlignment.CENTER:
total = self.width - real_length(left + right) - widget.width
padding, offset = divmod(total, 2)
return _align_center, real_length(left) + padding + offset
if widget.parent_align == HorizontalAlignment.RIGHT:
return _align_right, self.width - real_length(left) - widget.width
# Default to left-aligned
return _align_left, real_length(left)
def _update_width(self, widget: Widget) -> None:
"""Updates the width of widget or self.
This method respects widget.size_policy.
Args:
widget: The widget to update/base updates on.
"""
available = (
self.width - self.sidelength - (0 if isinstance(widget, Container) else 1)
)
if widget.size_policy == SizePolicy.FILL:
widget.width = available
return
if widget.size_policy == SizePolicy.RELATIVE:
widget.width = widget.relative_width * available
return
if widget.width > available:
if widget.size_policy == SizePolicy.STATIC:
raise WidthExceededError(
f"Widget {widget}'s static width of {widget.width}"
+ f" exceeds its parent's available width {available}."
""
)
widget.width = available
def _apply_vertalign(
self, lines: list[str], diff: int, padder: str
) -> tuple[int, list[str]]:
"""Insert padder line into lines diff times, depending on self.vertical_align.
Args:
lines: The list of lines to align.
diff: The available height.
padder: The line to use to pad.
Returns:
A tuple containing the vertical offset as well as the padded list of lines.
Raises:
NotImplementedError: The given vertical alignment is not implemented.
"""
if self.vertical_align == VerticalAlignment.BOTTOM:
for _ in range(diff):
lines.insert(0, padder)
return diff, lines
if self.vertical_align == VerticalAlignment.TOP:
for _ in range(diff):
lines.append(padder)
return 0, lines
if self.vertical_align == VerticalAlignment.CENTER:
top, extra = divmod(diff, 2)
bottom = top + extra
for _ in range(top):
lines.insert(0, padder)
for _ in range(bottom):
lines.append(padder)
return top, lines
raise NotImplementedError(
f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}."
)
def get_lines(self) -> list[str]:
"""Gets all lines by spacing out inner widgets.
This method reflects & applies both width settings, as well as
the `parent_align` field.
Returns:
A list of all lines that represent this Container.
"""
def _get_border(left: str, char: str, right: str) -> str:
"""Gets a top or bottom border.
Args:
left: Left corner character.
char: Border character filling between left & right.
right: Right corner character.
Returns:
The border line.
"""
offset = real_length(left + right)
return left + char * (self.width - offset) + right
lines = []
style = self._get_style("border")
borders = [style(char) for char in self._get_char("border")]
style = self._get_style("corner")
corners = [style(char) for char in self._get_char("corner")]
has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0)
align = lambda item: item
for widget in self._widgets:
align, offset = self._get_aligners(widget, (borders[0], borders[2]))
self._update_width(widget)
widget.pos = (
self.pos[0] + offset,
self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0),
)
widget_lines = []
for line in widget.get_lines():
widget_lines.append(align(line))
lines.extend(widget_lines)
vertical_offset, lines = self._apply_vertalign(
lines, self.height - len(lines) - sum(has_top_bottom), align("")
)
for widget in self._widgets:
widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset)
# TODO: This is wasteful.
widget.get_lines()
if has_top_bottom[0]:
lines.insert(0, _get_border(corners[0], borders[1], corners[1]))
if has_top_bottom[1]:
lines.append(_get_border(corners[3], borders[3], corners[2]))
self.height = len(lines)
return lines
def set_widgets(self, new: list[Widget]) -> None:
"""Sets new list in place of self._widgets.
Args:
new: The new widget list.
"""
self._widgets = []
for widget in new:
self._add_widget(widget)
def serialize(self) -> dict[str, Any]:
"""Serializes this Container, adding in serializations of all widgets.
See `pytermgui.widgets.base.Widget.serialize` for more info.
Returns:
The dictionary containing all serialized data.
"""
out = super().serialize()
out["_widgets"] = []
for widget in self._widgets:
out["_widgets"].append(widget.serialize())
return out
def pop(self, index: int = -1) -> Widget:
"""Pops widget from self._widgets.
Analogous to self._widgets.pop(index).
Args:
index: The index to operate on.
Returns:
The widget that was popped off the list.
"""
return self._widgets.pop(index)
def remove(self, other: Widget) -> None:
"""Remove widget from self._widgets
Analogous to self._widgets.remove(other).
Args:
widget: The widget to remove.
"""
return self._widgets.remove(other)
def set_recursive_depth(self, value: int) -> None:
"""Set depth for this Container and all its children.
All inner widgets will receive value+1 as their new depth.
Args:
value: The new depth to use as the base depth.
"""
self.depth = value
for widget in self._widgets:
if isinstance(widget, Container):
widget.set_recursive_depth(value + 1)
else:
widget.depth = value
def select(self, index: int | None = None) -> None:
"""Selects inner subwidget.
Args:
index: The index to select.
Raises:
IndexError: The index provided was beyond len(self.selectables).
"""
# Unselect all sub-elements
for other in self._widgets:
if other.selectables_length > 0:
other.select(None)
if index is not None:
if index >= len(self.selectables) is None:
raise IndexError("Container selection index out of range")
widget, inner_index = self.selectables[index]
widget.select(inner_index)
self.selected_index = index
def center(
self, where: CenteringPolicy | None = None, store: bool = True
) -> Container:
"""Centers this object to the given axis.
Args:
where: A CenteringPolicy describing the place to center to
store: When set, this centering will be reapplied during every
print, as well as when calling this method with no arguments.
Returns:
This Container.
"""
# Refresh in case changes happened
self.get_lines()
if where is None:
# See `enums.py` for explanation about this ignore.
where = CenteringPolicy.get_default() # type: ignore
centerx = centery = where is CenteringPolicy.ALL
centerx |= where is CenteringPolicy.HORIZONTAL
centery |= where is CenteringPolicy.VERTICAL
pos = list(self.pos)
if centerx:
pos[0] = (terminal.width - self.width + 2) // 2
if centery:
pos[1] = (terminal.height - self.height + 2) // 2
self.pos = (pos[0], pos[1])
if store:
self._centered_axis = where
self._prev_screen = terminal.size
return self
def handle_mouse(self, event: MouseEvent) -> bool:
"""Applies a mouse event on all children.
Args:
event: The event to handle
Returns:
A boolean showing whether the event was handled.
"""
if event.action is MouseAction.RELEASE:
# Force RELEASE event to be sent
if self._drag_target is not None:
self._drag_target.handle_mouse(
MouseEvent(MouseAction.RELEASE, event.position)
)
self._drag_target = None
if self._drag_target is not None:
return self._drag_target.handle_mouse(event)
selectables_index = 0
for widget in self._widgets:
if widget.contains(event.position):
handled = widget.handle_mouse(event)
if widget.selected_index is not None:
selectables_index += widget.selected_index
if event.action is MouseAction.LEFT_CLICK:
self._drag_target = widget
if handled:
self.select(selectables_index)
return handled
if widget.is_selectable:
selectables_index += widget.selectables_length
return False
def handle_key(self, key: str) -> bool:
"""Handles a keypress, returns its success.
Args:
key: A key str.
Returns:
A boolean showing whether the key was handled.
"""
def _is_nav(key: str) -> bool:
"""Determine if a key is in the navigation sets"""
return key in self.keys["next"] | self.keys["previous"]
if self.selected is not None and self.selected.handle_key(key):
return True
# Only use navigation when there is more than one selectable
if self.selectables_length > 1 and _is_nav(key):
handled = False
if self.selected_index is None:
self.select(0)
assert isinstance(self.selected_index, int)
if key in self.keys["previous"]:
# No more selectables left, user wants to exit Container
# upwards.
if self.selected_index == 0:
return False
self.select(self.selected_index - 1)
handled = True
elif key in self.keys["next"]:
# Stop selection at last element, return as unhandled
new = self.selected_index + 1
if new == len(self.selectables):
return False
self.select(new)
handled = True
if handled:
return True
if key == keys.ENTER and self.selected is not None:
if self.selected.selected_index is not None:
self.selected.handle_key(key)
return True
return False
def wipe(self) -> None:
"""Wipes the characters occupied by the object"""
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(real_length(line) * " ")
def print(self) -> None:
"""Prints this Container.
If the screen size has changed since last `print` call, the object
will be centered based on its `_centered_axis`.
"""
if not terminal.size == self._prev_screen:
clear()
self.center(self._centered_axis)
self._prev_screen = terminal.size
if self.allow_fullscreen:
self.pos = terminal.origin
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(line)
self._has_printed = True
def debug(self) -> str:
"""Returns a string with identifiable information on this widget.
Returns:
A str in the form of a class construction. This string is in a form that
__could have been__ used to create this Container.
"""
out = "Container("
for widget in self._widgets:
out += widget.debug() + ", "
out = out.strip(", ")
out += ", **attrs)"
return out
class Splitter(Container):
"""A widget that displays other widgets, stacked horizontally."""
chars: dict[str, list[str] | str] = {"separator": " | "}
styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND}
keys = {
"previous": {keys.LEFT, "h", keys.CTRL_B},
"next": {keys.RIGHT, "l", keys.CTRL_F},
}
parent_align = HorizontalAlignment.RIGHT
def _align(
self, alignment: HorizontalAlignment, target_width: int, line: str
) -> tuple[int, str]:
"""Align a line
r/wordavalanches"""
available = target_width - real_length(line)
fill_style = self._get_style("fill")
char = fill_style(" ")
line = fill_style(line)
if alignment == HorizontalAlignment.CENTER:
padding, offset = divmod(available, 2)
return padding, padding * char + line + (padding + offset) * char
if alignment == HorizontalAlignment.RIGHT:
return available, available * char + line
return 0, line + available * char
def get_lines(self) -> list[str]:
"""Join all widgets horizontally."""
# An error will be raised if `separator` is not the correct type (str).
separator = self._get_style("separator")(self._get_char("separator")) # type: ignore
separator_length = real_length(separator)
target_width, error = divmod(
self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets)
)
vertical_lines = []
total_offset = 0
for widget in self._widgets:
inner = []
if widget.size_policy is SizePolicy.STATIC:
target_width += target_width - widget.width
width = target_width
else:
widget.width = target_width + error
width = widget.width
error = 0
aligned: str | None = None
for line in widget.get_lines():
# See `enums.py` for information about this ignore
padding, aligned = self._align(
cast(HorizontalAlignment, widget.parent_align), width, line
)
inner.append(aligned)
widget.pos = (
self.pos[0] + padding + total_offset,
self.pos[1] + (1 if type(widget).__name__ == "Container" else 0),
)
if aligned is not None:
total_offset += real_length(inner[-1]) + separator_length
vertical_lines.append(inner)
lines = []
for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width):
lines.append((reset() + separator).join(horizontal))
return lines
def debug(self) -> str:
"""Return identifiable information"""
return super().debug().replace("Container", "Splitter", 1)
| bczsalba__pytermgui |
54 | 54-55-13 | inproject | _centered_axis | [
"allow_fullscreen",
"bind",
"bindings",
"box",
"center",
"chars",
"contains",
"copy",
"debug",
"depth",
"execute_binding",
"get_lines",
"handle_key",
"handle_mouse",
"height",
"id",
"is_bindable",
"is_selectable",
"keys",
"parent",
"parent_align",
"pop",
"pos",
"print",
"remove",
"select",
"selectables",
"selectables_length",
"selected",
"selected_index",
"serialize",
"serialized",
"set_char",
"set_recursive_depth",
"set_style",
"set_widgets",
"sidelength",
"size_policy",
"static_width",
"styles",
"vertical_align",
"width",
"wipe",
"_add_widget",
"_apply_vertalign",
"_bindings",
"_box",
"_centered_axis",
"_drag_target",
"_get_aligners",
"_get_char",
"_get_style",
"_has_printed",
"_id",
"_id_manager",
"_prev_screen",
"_selectables_length",
"_serialized_fields",
"_update_width",
"_widgets",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__getitem__",
"__hash__",
"__iadd__",
"__init__",
"__init_subclass__",
"__iter__",
"__len__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__setitem__",
"__sizeof__",
"__slots__",
"__str__"
] | """The module containing all of the layout-related widgets."""
# These widgets have more than the 7 allowed instance attributes.
# pylint: disable=too-many-instance-attributes
from __future__ import annotations
from itertools import zip_longest
from typing import Any, Callable, Iterator, cast
from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal
from ..context_managers import cursor_at
from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment
from ..exceptions import WidthExceededError
from ..helpers import real_length
from ..input import keys
from . import boxes
from . import styles as w_styles
from .base import Widget
class Container(Widget):
"""A widget that displays other widgets, stacked vertically."""
chars: dict[str, w_styles.CharType] = {
"border": ["| ", "-", " |", "-"],
"corner": [""] * 4,
}
styles = {
"border": w_styles.MARKUP,
"corner": w_styles.MARKUP,
"fill": w_styles.BACKGROUND,
}
keys = {
"next": {keys.DOWN, keys.CTRL_N, "j"},
"previous": {keys.UP, keys.CTRL_P, "k"},
}
serialized = Widget.serialized + ["_centered_axis"]
vertical_align = VerticalAlignment.CENTER
allow_fullscreen = True
# TODO: Add `WidgetConvertible`? type instead of Any
def __init__(self, *widgets: Any, **attrs: Any) -> None:
"""Initialize Container data"""
super().__init__(**attrs)
# TODO: This is just a band-aid.
if "width" not in attrs:
self.width = 40
self._widgets: list[Widget] = []
self. | : CenteringPolicy | None = None
self._prev_screen: tuple[int, int] = (0, 0)
self._has_printed = False
self.styles = type(self).styles.copy()
self.chars = type(self).chars.copy()
for widget in widgets:
self._add_widget(widget)
self._drag_target: Widget | None = None
terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis))
@property
def sidelength(self) -> int:
"""Gets the length of left and right borders combined.
Returns:
An integer equal to the `pytermgui.helpers.real_length` of the concatenation of
the left and right borders of this widget, both with their respective styles
applied.
"""
chars = self._get_char("border")
style = self._get_style("border")
if not isinstance(chars, list):
return 0
left_border, _, right_border, _ = chars
return real_length(style(left_border) + style(right_border))
@property
def selectables(self) -> list[tuple[Widget, int]]:
"""Gets all selectable widgets and their inner indices.
This is used in order to have a constant reference to all selectable indices within this
widget.
Returns:
A list of tuples containing a widget and an integer each. For each widget that is
withing this one, it is added to this list as many times as it has selectables. Each
of the integers correspond to a selectable_index within the widget.
For example, a Container with a Button, InputField and an inner Container containing
3 selectables might return something like this:
```
[
(Button(...), 0),
(InputField(...), 0),
(Container(...), 0),
(Container(...), 1),
(Container(...), 2),
]
```
"""
_selectables: list[tuple[Widget, int]] = []
for widget in self._widgets:
if not widget.is_selectable:
continue
for i, (inner, _) in enumerate(widget.selectables):
_selectables.append((inner, i))
return _selectables
@property
def selectables_length(self) -> int:
"""Gets the length of the selectables list.
Returns:
An integer equal to the length of `self.selectables`.
"""
return len(self.selectables)
@property
def selected(self) -> Widget | None:
"""Returns the currently selected object
Returns:
The currently selected widget if selected_index is not None,
otherwise None.
"""
# TODO: Add deeper selection
if self.selected_index is None:
return None
if self.selected_index >= len(self.selectables):
return None
return self.selectables[self.selected_index][0]
@property
def box(self) -> boxes.Box:
"""Returns current box setting
Returns:
The currently set box instance.
"""
return self._box
@box.setter
def box(self, new: str | boxes.Box) -> None:
"""Applies a new box.
Args:
new: Either a `pytermgui.boxes.Box` instance or a string
analogous to one of the default box names.
"""
if isinstance(new, str):
from_module = vars(boxes).get(new)
if from_module is None:
raise ValueError(f"Unknown box type {new}.")
new = from_module
assert isinstance(new, boxes.Box)
self._box = new
new.set_chars_of(self)
def __iadd__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self._add_widget(other)
return self
def __add__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
This method is analogous to `Container.__iadd__`.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self.__iadd__(other)
return self
def __iter__(self) -> Iterator[Widget]:
"""Gets an iterator of self._widgets.
Yields:
The next widget.
"""
for widget in self._widgets:
yield widget
def __len__(self) -> int:
"""Gets the length of the widgets list.
Returns:
An integer describing len(self._widgets).
"""
return len(self._widgets)
def __getitem__(self, sli: int | slice) -> Widget | list[Widget]:
"""Gets an item from self._widgets.
Args:
sli: Slice of the list.
Returns:
The slice in the list.
"""
return self._widgets[sli]
def __setitem__(self, index: int, value: Any) -> None:
"""Sets an item in self._widgets.
Args:
index: The index to be set.
value: The new widget at this index.
"""
self._widgets[index] = value
def __contains__(self, other: object) -> bool:
"""Determines if self._widgets contains other widget.
Args:
other: Any widget-like.
Returns:
A boolean describing whether `other` is in `self.widgets`
"""
return other in self._widgets
def _add_widget(self, other: object, run_get_lines: bool = True) -> None:
"""Adds other to this widget.
Args:
other: Any widget-like object.
run_get_lines: Boolean controlling whether the self.get_lines is ran.
"""
if not isinstance(other, Widget):
to_widget = Widget.from_data(other)
if to_widget is None:
raise ValueError(
f"Could not convert {other} of type {type(other)} to a Widget!"
)
other = to_widget
# This is safe to do, as it would've raised an exception above already
assert isinstance(other, Widget)
self._widgets.append(other)
if isinstance(other, Container):
other.set_recursive_depth(self.depth + 2)
else:
other.depth = self.depth + 1
other.get_lines()
other.parent = self
if run_get_lines:
self.get_lines()
def _get_aligners(
self, widget: Widget, borders: tuple[str, str]
) -> tuple[Callable[[str], str], int]:
"""Gets an aligning method and position offset.
Args:
widget: The widget to align.
borders: The left and right borders to put the widget within.
Returns:
A tuple of a method that, when called with a line, will return that line
centered using the passed in widget's parent_align and width, as well as
the horizontal offset resulting from the widget being aligned.
"""
left, right = borders
char = self._get_style("fill")(" ")
def _align_left(text: str) -> str:
"""Align line to the left"""
padding = self.width - real_length(left + right) - real_length(text)
return left + text + padding * char + right
def _align_center(text: str) -> str:
"""Align line to the center"""
total = self.width - real_length(left + right) - real_length(text)
padding, offset = divmod(total, 2)
return left + (padding + offset) * char + text + padding * char + right
def _align_right(text: str) -> str:
"""Align line to the right"""
padding = self.width - real_length(left + right) - real_length(text)
return left + padding * char + text + right
if widget.parent_align == HorizontalAlignment.CENTER:
total = self.width - real_length(left + right) - widget.width
padding, offset = divmod(total, 2)
return _align_center, real_length(left) + padding + offset
if widget.parent_align == HorizontalAlignment.RIGHT:
return _align_right, self.width - real_length(left) - widget.width
# Default to left-aligned
return _align_left, real_length(left)
def _update_width(self, widget: Widget) -> None:
"""Updates the width of widget or self.
This method respects widget.size_policy.
Args:
widget: The widget to update/base updates on.
"""
available = (
self.width - self.sidelength - (0 if isinstance(widget, Container) else 1)
)
if widget.size_policy == SizePolicy.FILL:
widget.width = available
return
if widget.size_policy == SizePolicy.RELATIVE:
widget.width = widget.relative_width * available
return
if widget.width > available:
if widget.size_policy == SizePolicy.STATIC:
raise WidthExceededError(
f"Widget {widget}'s static width of {widget.width}"
+ f" exceeds its parent's available width {available}."
""
)
widget.width = available
def _apply_vertalign(
self, lines: list[str], diff: int, padder: str
) -> tuple[int, list[str]]:
"""Insert padder line into lines diff times, depending on self.vertical_align.
Args:
lines: The list of lines to align.
diff: The available height.
padder: The line to use to pad.
Returns:
A tuple containing the vertical offset as well as the padded list of lines.
Raises:
NotImplementedError: The given vertical alignment is not implemented.
"""
if self.vertical_align == VerticalAlignment.BOTTOM:
for _ in range(diff):
lines.insert(0, padder)
return diff, lines
if self.vertical_align == VerticalAlignment.TOP:
for _ in range(diff):
lines.append(padder)
return 0, lines
if self.vertical_align == VerticalAlignment.CENTER:
top, extra = divmod(diff, 2)
bottom = top + extra
for _ in range(top):
lines.insert(0, padder)
for _ in range(bottom):
lines.append(padder)
return top, lines
raise NotImplementedError(
f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}."
)
def get_lines(self) -> list[str]:
"""Gets all lines by spacing out inner widgets.
This method reflects & applies both width settings, as well as
the `parent_align` field.
Returns:
A list of all lines that represent this Container.
"""
def _get_border(left: str, char: str, right: str) -> str:
"""Gets a top or bottom border.
Args:
left: Left corner character.
char: Border character filling between left & right.
right: Right corner character.
Returns:
The border line.
"""
offset = real_length(left + right)
return left + char * (self.width - offset) + right
lines = []
style = self._get_style("border")
borders = [style(char) for char in self._get_char("border")]
style = self._get_style("corner")
corners = [style(char) for char in self._get_char("corner")]
has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0)
align = lambda item: item
for widget in self._widgets:
align, offset = self._get_aligners(widget, (borders[0], borders[2]))
self._update_width(widget)
widget.pos = (
self.pos[0] + offset,
self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0),
)
widget_lines = []
for line in widget.get_lines():
widget_lines.append(align(line))
lines.extend(widget_lines)
vertical_offset, lines = self._apply_vertalign(
lines, self.height - len(lines) - sum(has_top_bottom), align("")
)
for widget in self._widgets:
widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset)
# TODO: This is wasteful.
widget.get_lines()
if has_top_bottom[0]:
lines.insert(0, _get_border(corners[0], borders[1], corners[1]))
if has_top_bottom[1]:
lines.append(_get_border(corners[3], borders[3], corners[2]))
self.height = len(lines)
return lines
def set_widgets(self, new: list[Widget]) -> None:
"""Sets new list in place of self._widgets.
Args:
new: The new widget list.
"""
self._widgets = []
for widget in new:
self._add_widget(widget)
def serialize(self) -> dict[str, Any]:
"""Serializes this Container, adding in serializations of all widgets.
See `pytermgui.widgets.base.Widget.serialize` for more info.
Returns:
The dictionary containing all serialized data.
"""
out = super().serialize()
out["_widgets"] = []
for widget in self._widgets:
out["_widgets"].append(widget.serialize())
return out
def pop(self, index: int = -1) -> Widget:
"""Pops widget from self._widgets.
Analogous to self._widgets.pop(index).
Args:
index: The index to operate on.
Returns:
The widget that was popped off the list.
"""
return self._widgets.pop(index)
def remove(self, other: Widget) -> None:
"""Remove widget from self._widgets
Analogous to self._widgets.remove(other).
Args:
widget: The widget to remove.
"""
return self._widgets.remove(other)
def set_recursive_depth(self, value: int) -> None:
"""Set depth for this Container and all its children.
All inner widgets will receive value+1 as their new depth.
Args:
value: The new depth to use as the base depth.
"""
self.depth = value
for widget in self._widgets:
if isinstance(widget, Container):
widget.set_recursive_depth(value + 1)
else:
widget.depth = value
def select(self, index: int | None = None) -> None:
"""Selects inner subwidget.
Args:
index: The index to select.
Raises:
IndexError: The index provided was beyond len(self.selectables).
"""
# Unselect all sub-elements
for other in self._widgets:
if other.selectables_length > 0:
other.select(None)
if index is not None:
if index >= len(self.selectables) is None:
raise IndexError("Container selection index out of range")
widget, inner_index = self.selectables[index]
widget.select(inner_index)
self.selected_index = index
def center(
self, where: CenteringPolicy | None = None, store: bool = True
) -> Container:
"""Centers this object to the given axis.
Args:
where: A CenteringPolicy describing the place to center to
store: When set, this centering will be reapplied during every
print, as well as when calling this method with no arguments.
Returns:
This Container.
"""
# Refresh in case changes happened
self.get_lines()
if where is None:
# See `enums.py` for explanation about this ignore.
where = CenteringPolicy.get_default() # type: ignore
centerx = centery = where is CenteringPolicy.ALL
centerx |= where is CenteringPolicy.HORIZONTAL
centery |= where is CenteringPolicy.VERTICAL
pos = list(self.pos)
if centerx:
pos[0] = (terminal.width - self.width + 2) // 2
if centery:
pos[1] = (terminal.height - self.height + 2) // 2
self.pos = (pos[0], pos[1])
if store:
self._centered_axis = where
self._prev_screen = terminal.size
return self
def handle_mouse(self, event: MouseEvent) -> bool:
"""Applies a mouse event on all children.
Args:
event: The event to handle
Returns:
A boolean showing whether the event was handled.
"""
if event.action is MouseAction.RELEASE:
# Force RELEASE event to be sent
if self._drag_target is not None:
self._drag_target.handle_mouse(
MouseEvent(MouseAction.RELEASE, event.position)
)
self._drag_target = None
if self._drag_target is not None:
return self._drag_target.handle_mouse(event)
selectables_index = 0
for widget in self._widgets:
if widget.contains(event.position):
handled = widget.handle_mouse(event)
if widget.selected_index is not None:
selectables_index += widget.selected_index
if event.action is MouseAction.LEFT_CLICK:
self._drag_target = widget
if handled:
self.select(selectables_index)
return handled
if widget.is_selectable:
selectables_index += widget.selectables_length
return False
def handle_key(self, key: str) -> bool:
"""Handles a keypress, returns its success.
Args:
key: A key str.
Returns:
A boolean showing whether the key was handled.
"""
def _is_nav(key: str) -> bool:
"""Determine if a key is in the navigation sets"""
return key in self.keys["next"] | self.keys["previous"]
if self.selected is not None and self.selected.handle_key(key):
return True
# Only use navigation when there is more than one selectable
if self.selectables_length > 1 and _is_nav(key):
handled = False
if self.selected_index is None:
self.select(0)
assert isinstance(self.selected_index, int)
if key in self.keys["previous"]:
# No more selectables left, user wants to exit Container
# upwards.
if self.selected_index == 0:
return False
self.select(self.selected_index - 1)
handled = True
elif key in self.keys["next"]:
# Stop selection at last element, return as unhandled
new = self.selected_index + 1
if new == len(self.selectables):
return False
self.select(new)
handled = True
if handled:
return True
if key == keys.ENTER and self.selected is not None:
if self.selected.selected_index is not None:
self.selected.handle_key(key)
return True
return False
def wipe(self) -> None:
"""Wipes the characters occupied by the object"""
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(real_length(line) * " ")
def print(self) -> None:
"""Prints this Container.
If the screen size has changed since last `print` call, the object
will be centered based on its `_centered_axis`.
"""
if not terminal.size == self._prev_screen:
clear()
self.center(self._centered_axis)
self._prev_screen = terminal.size
if self.allow_fullscreen:
self.pos = terminal.origin
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(line)
self._has_printed = True
def debug(self) -> str:
"""Returns a string with identifiable information on this widget.
Returns:
A str in the form of a class construction. This string is in a form that
__could have been__ used to create this Container.
"""
out = "Container("
for widget in self._widgets:
out += widget.debug() + ", "
out = out.strip(", ")
out += ", **attrs)"
return out
class Splitter(Container):
"""A widget that displays other widgets, stacked horizontally."""
chars: dict[str, list[str] | str] = {"separator": " | "}
styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND}
keys = {
"previous": {keys.LEFT, "h", keys.CTRL_B},
"next": {keys.RIGHT, "l", keys.CTRL_F},
}
parent_align = HorizontalAlignment.RIGHT
def _align(
self, alignment: HorizontalAlignment, target_width: int, line: str
) -> tuple[int, str]:
"""Align a line
r/wordavalanches"""
available = target_width - real_length(line)
fill_style = self._get_style("fill")
char = fill_style(" ")
line = fill_style(line)
if alignment == HorizontalAlignment.CENTER:
padding, offset = divmod(available, 2)
return padding, padding * char + line + (padding + offset) * char
if alignment == HorizontalAlignment.RIGHT:
return available, available * char + line
return 0, line + available * char
def get_lines(self) -> list[str]:
"""Join all widgets horizontally."""
# An error will be raised if `separator` is not the correct type (str).
separator = self._get_style("separator")(self._get_char("separator")) # type: ignore
separator_length = real_length(separator)
target_width, error = divmod(
self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets)
)
vertical_lines = []
total_offset = 0
for widget in self._widgets:
inner = []
if widget.size_policy is SizePolicy.STATIC:
target_width += target_width - widget.width
width = target_width
else:
widget.width = target_width + error
width = widget.width
error = 0
aligned: str | None = None
for line in widget.get_lines():
# See `enums.py` for information about this ignore
padding, aligned = self._align(
cast(HorizontalAlignment, widget.parent_align), width, line
)
inner.append(aligned)
widget.pos = (
self.pos[0] + padding + total_offset,
self.pos[1] + (1 if type(widget).__name__ == "Container" else 0),
)
if aligned is not None:
total_offset += real_length(inner[-1]) + separator_length
vertical_lines.append(inner)
lines = []
for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width):
lines.append((reset() + separator).join(horizontal))
return lines
def debug(self) -> str:
"""Return identifiable information"""
return super().debug().replace("Container", "Splitter", 1)
| bczsalba__pytermgui |
54 | 54-60-13 | inproject | styles | [
"allow_fullscreen",
"bind",
"bindings",
"box",
"center",
"chars",
"contains",
"copy",
"debug",
"depth",
"execute_binding",
"get_lines",
"handle_key",
"handle_mouse",
"height",
"id",
"is_bindable",
"is_selectable",
"keys",
"parent",
"parent_align",
"pop",
"pos",
"print",
"remove",
"select",
"selectables",
"selectables_length",
"selected",
"selected_index",
"serialize",
"serialized",
"set_char",
"set_recursive_depth",
"set_style",
"set_widgets",
"sidelength",
"size_policy",
"static_width",
"styles",
"vertical_align",
"width",
"wipe",
"_add_widget",
"_apply_vertalign",
"_bindings",
"_box",
"_centered_axis",
"_drag_target",
"_get_aligners",
"_get_char",
"_get_style",
"_has_printed",
"_id",
"_id_manager",
"_prev_screen",
"_selectables_length",
"_serialized_fields",
"_update_width",
"_widgets",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__getitem__",
"__hash__",
"__iadd__",
"__init__",
"__init_subclass__",
"__iter__",
"__len__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__setitem__",
"__sizeof__",
"__slots__",
"__str__"
] | """The module containing all of the layout-related widgets."""
# These widgets have more than the 7 allowed instance attributes.
# pylint: disable=too-many-instance-attributes
from __future__ import annotations
from itertools import zip_longest
from typing import Any, Callable, Iterator, cast
from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal
from ..context_managers import cursor_at
from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment
from ..exceptions import WidthExceededError
from ..helpers import real_length
from ..input import keys
from . import boxes
from . import styles as w_styles
from .base import Widget
class Container(Widget):
"""A widget that displays other widgets, stacked vertically."""
chars: dict[str, w_styles.CharType] = {
"border": ["| ", "-", " |", "-"],
"corner": [""] * 4,
}
styles = {
"border": w_styles.MARKUP,
"corner": w_styles.MARKUP,
"fill": w_styles.BACKGROUND,
}
keys = {
"next": {keys.DOWN, keys.CTRL_N, "j"},
"previous": {keys.UP, keys.CTRL_P, "k"},
}
serialized = Widget.serialized + ["_centered_axis"]
vertical_align = VerticalAlignment.CENTER
allow_fullscreen = True
# TODO: Add `WidgetConvertible`? type instead of Any
def __init__(self, *widgets: Any, **attrs: Any) -> None:
"""Initialize Container data"""
super().__init__(**attrs)
# TODO: This is just a band-aid.
if "width" not in attrs:
self.width = 40
self._widgets: list[Widget] = []
self._centered_axis: CenteringPolicy | None = None
self._prev_screen: tuple[int, int] = (0, 0)
self._has_printed = False
self. | = type(self).styles.copy()
self.chars = type(self).chars.copy()
for widget in widgets:
self._add_widget(widget)
self._drag_target: Widget | None = None
terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis))
@property
def sidelength(self) -> int:
"""Gets the length of left and right borders combined.
Returns:
An integer equal to the `pytermgui.helpers.real_length` of the concatenation of
the left and right borders of this widget, both with their respective styles
applied.
"""
chars = self._get_char("border")
style = self._get_style("border")
if not isinstance(chars, list):
return 0
left_border, _, right_border, _ = chars
return real_length(style(left_border) + style(right_border))
@property
def selectables(self) -> list[tuple[Widget, int]]:
"""Gets all selectable widgets and their inner indices.
This is used in order to have a constant reference to all selectable indices within this
widget.
Returns:
A list of tuples containing a widget and an integer each. For each widget that is
withing this one, it is added to this list as many times as it has selectables. Each
of the integers correspond to a selectable_index within the widget.
For example, a Container with a Button, InputField and an inner Container containing
3 selectables might return something like this:
```
[
(Button(...), 0),
(InputField(...), 0),
(Container(...), 0),
(Container(...), 1),
(Container(...), 2),
]
```
"""
_selectables: list[tuple[Widget, int]] = []
for widget in self._widgets:
if not widget.is_selectable:
continue
for i, (inner, _) in enumerate(widget.selectables):
_selectables.append((inner, i))
return _selectables
@property
def selectables_length(self) -> int:
"""Gets the length of the selectables list.
Returns:
An integer equal to the length of `self.selectables`.
"""
return len(self.selectables)
@property
def selected(self) -> Widget | None:
"""Returns the currently selected object
Returns:
The currently selected widget if selected_index is not None,
otherwise None.
"""
# TODO: Add deeper selection
if self.selected_index is None:
return None
if self.selected_index >= len(self.selectables):
return None
return self.selectables[self.selected_index][0]
@property
def box(self) -> boxes.Box:
"""Returns current box setting
Returns:
The currently set box instance.
"""
return self._box
@box.setter
def box(self, new: str | boxes.Box) -> None:
"""Applies a new box.
Args:
new: Either a `pytermgui.boxes.Box` instance or a string
analogous to one of the default box names.
"""
if isinstance(new, str):
from_module = vars(boxes).get(new)
if from_module is None:
raise ValueError(f"Unknown box type {new}.")
new = from_module
assert isinstance(new, boxes.Box)
self._box = new
new.set_chars_of(self)
def __iadd__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self._add_widget(other)
return self
def __add__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
This method is analogous to `Container.__iadd__`.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self.__iadd__(other)
return self
def __iter__(self) -> Iterator[Widget]:
"""Gets an iterator of self._widgets.
Yields:
The next widget.
"""
for widget in self._widgets:
yield widget
def __len__(self) -> int:
"""Gets the length of the widgets list.
Returns:
An integer describing len(self._widgets).
"""
return len(self._widgets)
def __getitem__(self, sli: int | slice) -> Widget | list[Widget]:
"""Gets an item from self._widgets.
Args:
sli: Slice of the list.
Returns:
The slice in the list.
"""
return self._widgets[sli]
def __setitem__(self, index: int, value: Any) -> None:
"""Sets an item in self._widgets.
Args:
index: The index to be set.
value: The new widget at this index.
"""
self._widgets[index] = value
def __contains__(self, other: object) -> bool:
"""Determines if self._widgets contains other widget.
Args:
other: Any widget-like.
Returns:
A boolean describing whether `other` is in `self.widgets`
"""
return other in self._widgets
def _add_widget(self, other: object, run_get_lines: bool = True) -> None:
"""Adds other to this widget.
Args:
other: Any widget-like object.
run_get_lines: Boolean controlling whether the self.get_lines is ran.
"""
if not isinstance(other, Widget):
to_widget = Widget.from_data(other)
if to_widget is None:
raise ValueError(
f"Could not convert {other} of type {type(other)} to a Widget!"
)
other = to_widget
# This is safe to do, as it would've raised an exception above already
assert isinstance(other, Widget)
self._widgets.append(other)
if isinstance(other, Container):
other.set_recursive_depth(self.depth + 2)
else:
other.depth = self.depth + 1
other.get_lines()
other.parent = self
if run_get_lines:
self.get_lines()
def _get_aligners(
self, widget: Widget, borders: tuple[str, str]
) -> tuple[Callable[[str], str], int]:
"""Gets an aligning method and position offset.
Args:
widget: The widget to align.
borders: The left and right borders to put the widget within.
Returns:
A tuple of a method that, when called with a line, will return that line
centered using the passed in widget's parent_align and width, as well as
the horizontal offset resulting from the widget being aligned.
"""
left, right = borders
char = self._get_style("fill")(" ")
def _align_left(text: str) -> str:
"""Align line to the left"""
padding = self.width - real_length(left + right) - real_length(text)
return left + text + padding * char + right
def _align_center(text: str) -> str:
"""Align line to the center"""
total = self.width - real_length(left + right) - real_length(text)
padding, offset = divmod(total, 2)
return left + (padding + offset) * char + text + padding * char + right
def _align_right(text: str) -> str:
"""Align line to the right"""
padding = self.width - real_length(left + right) - real_length(text)
return left + padding * char + text + right
if widget.parent_align == HorizontalAlignment.CENTER:
total = self.width - real_length(left + right) - widget.width
padding, offset = divmod(total, 2)
return _align_center, real_length(left) + padding + offset
if widget.parent_align == HorizontalAlignment.RIGHT:
return _align_right, self.width - real_length(left) - widget.width
# Default to left-aligned
return _align_left, real_length(left)
def _update_width(self, widget: Widget) -> None:
"""Updates the width of widget or self.
This method respects widget.size_policy.
Args:
widget: The widget to update/base updates on.
"""
available = (
self.width - self.sidelength - (0 if isinstance(widget, Container) else 1)
)
if widget.size_policy == SizePolicy.FILL:
widget.width = available
return
if widget.size_policy == SizePolicy.RELATIVE:
widget.width = widget.relative_width * available
return
if widget.width > available:
if widget.size_policy == SizePolicy.STATIC:
raise WidthExceededError(
f"Widget {widget}'s static width of {widget.width}"
+ f" exceeds its parent's available width {available}."
""
)
widget.width = available
def _apply_vertalign(
self, lines: list[str], diff: int, padder: str
) -> tuple[int, list[str]]:
"""Insert padder line into lines diff times, depending on self.vertical_align.
Args:
lines: The list of lines to align.
diff: The available height.
padder: The line to use to pad.
Returns:
A tuple containing the vertical offset as well as the padded list of lines.
Raises:
NotImplementedError: The given vertical alignment is not implemented.
"""
if self.vertical_align == VerticalAlignment.BOTTOM:
for _ in range(diff):
lines.insert(0, padder)
return diff, lines
if self.vertical_align == VerticalAlignment.TOP:
for _ in range(diff):
lines.append(padder)
return 0, lines
if self.vertical_align == VerticalAlignment.CENTER:
top, extra = divmod(diff, 2)
bottom = top + extra
for _ in range(top):
lines.insert(0, padder)
for _ in range(bottom):
lines.append(padder)
return top, lines
raise NotImplementedError(
f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}."
)
def get_lines(self) -> list[str]:
"""Gets all lines by spacing out inner widgets.
This method reflects & applies both width settings, as well as
the `parent_align` field.
Returns:
A list of all lines that represent this Container.
"""
def _get_border(left: str, char: str, right: str) -> str:
"""Gets a top or bottom border.
Args:
left: Left corner character.
char: Border character filling between left & right.
right: Right corner character.
Returns:
The border line.
"""
offset = real_length(left + right)
return left + char * (self.width - offset) + right
lines = []
style = self._get_style("border")
borders = [style(char) for char in self._get_char("border")]
style = self._get_style("corner")
corners = [style(char) for char in self._get_char("corner")]
has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0)
align = lambda item: item
for widget in self._widgets:
align, offset = self._get_aligners(widget, (borders[0], borders[2]))
self._update_width(widget)
widget.pos = (
self.pos[0] + offset,
self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0),
)
widget_lines = []
for line in widget.get_lines():
widget_lines.append(align(line))
lines.extend(widget_lines)
vertical_offset, lines = self._apply_vertalign(
lines, self.height - len(lines) - sum(has_top_bottom), align("")
)
for widget in self._widgets:
widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset)
# TODO: This is wasteful.
widget.get_lines()
if has_top_bottom[0]:
lines.insert(0, _get_border(corners[0], borders[1], corners[1]))
if has_top_bottom[1]:
lines.append(_get_border(corners[3], borders[3], corners[2]))
self.height = len(lines)
return lines
def set_widgets(self, new: list[Widget]) -> None:
"""Sets new list in place of self._widgets.
Args:
new: The new widget list.
"""
self._widgets = []
for widget in new:
self._add_widget(widget)
def serialize(self) -> dict[str, Any]:
"""Serializes this Container, adding in serializations of all widgets.
See `pytermgui.widgets.base.Widget.serialize` for more info.
Returns:
The dictionary containing all serialized data.
"""
out = super().serialize()
out["_widgets"] = []
for widget in self._widgets:
out["_widgets"].append(widget.serialize())
return out
def pop(self, index: int = -1) -> Widget:
"""Pops widget from self._widgets.
Analogous to self._widgets.pop(index).
Args:
index: The index to operate on.
Returns:
The widget that was popped off the list.
"""
return self._widgets.pop(index)
def remove(self, other: Widget) -> None:
"""Remove widget from self._widgets
Analogous to self._widgets.remove(other).
Args:
widget: The widget to remove.
"""
return self._widgets.remove(other)
def set_recursive_depth(self, value: int) -> None:
"""Set depth for this Container and all its children.
All inner widgets will receive value+1 as their new depth.
Args:
value: The new depth to use as the base depth.
"""
self.depth = value
for widget in self._widgets:
if isinstance(widget, Container):
widget.set_recursive_depth(value + 1)
else:
widget.depth = value
def select(self, index: int | None = None) -> None:
"""Selects inner subwidget.
Args:
index: The index to select.
Raises:
IndexError: The index provided was beyond len(self.selectables).
"""
# Unselect all sub-elements
for other in self._widgets:
if other.selectables_length > 0:
other.select(None)
if index is not None:
if index >= len(self.selectables) is None:
raise IndexError("Container selection index out of range")
widget, inner_index = self.selectables[index]
widget.select(inner_index)
self.selected_index = index
def center(
self, where: CenteringPolicy | None = None, store: bool = True
) -> Container:
"""Centers this object to the given axis.
Args:
where: A CenteringPolicy describing the place to center to
store: When set, this centering will be reapplied during every
print, as well as when calling this method with no arguments.
Returns:
This Container.
"""
# Refresh in case changes happened
self.get_lines()
if where is None:
# See `enums.py` for explanation about this ignore.
where = CenteringPolicy.get_default() # type: ignore
centerx = centery = where is CenteringPolicy.ALL
centerx |= where is CenteringPolicy.HORIZONTAL
centery |= where is CenteringPolicy.VERTICAL
pos = list(self.pos)
if centerx:
pos[0] = (terminal.width - self.width + 2) // 2
if centery:
pos[1] = (terminal.height - self.height + 2) // 2
self.pos = (pos[0], pos[1])
if store:
self._centered_axis = where
self._prev_screen = terminal.size
return self
def handle_mouse(self, event: MouseEvent) -> bool:
"""Applies a mouse event on all children.
Args:
event: The event to handle
Returns:
A boolean showing whether the event was handled.
"""
if event.action is MouseAction.RELEASE:
# Force RELEASE event to be sent
if self._drag_target is not None:
self._drag_target.handle_mouse(
MouseEvent(MouseAction.RELEASE, event.position)
)
self._drag_target = None
if self._drag_target is not None:
return self._drag_target.handle_mouse(event)
selectables_index = 0
for widget in self._widgets:
if widget.contains(event.position):
handled = widget.handle_mouse(event)
if widget.selected_index is not None:
selectables_index += widget.selected_index
if event.action is MouseAction.LEFT_CLICK:
self._drag_target = widget
if handled:
self.select(selectables_index)
return handled
if widget.is_selectable:
selectables_index += widget.selectables_length
return False
def handle_key(self, key: str) -> bool:
"""Handles a keypress, returns its success.
Args:
key: A key str.
Returns:
A boolean showing whether the key was handled.
"""
def _is_nav(key: str) -> bool:
"""Determine if a key is in the navigation sets"""
return key in self.keys["next"] | self.keys["previous"]
if self.selected is not None and self.selected.handle_key(key):
return True
# Only use navigation when there is more than one selectable
if self.selectables_length > 1 and _is_nav(key):
handled = False
if self.selected_index is None:
self.select(0)
assert isinstance(self.selected_index, int)
if key in self.keys["previous"]:
# No more selectables left, user wants to exit Container
# upwards.
if self.selected_index == 0:
return False
self.select(self.selected_index - 1)
handled = True
elif key in self.keys["next"]:
# Stop selection at last element, return as unhandled
new = self.selected_index + 1
if new == len(self.selectables):
return False
self.select(new)
handled = True
if handled:
return True
if key == keys.ENTER and self.selected is not None:
if self.selected.selected_index is not None:
self.selected.handle_key(key)
return True
return False
def wipe(self) -> None:
"""Wipes the characters occupied by the object"""
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(real_length(line) * " ")
def print(self) -> None:
"""Prints this Container.
If the screen size has changed since last `print` call, the object
will be centered based on its `_centered_axis`.
"""
if not terminal.size == self._prev_screen:
clear()
self.center(self._centered_axis)
self._prev_screen = terminal.size
if self.allow_fullscreen:
self.pos = terminal.origin
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(line)
self._has_printed = True
def debug(self) -> str:
"""Returns a string with identifiable information on this widget.
Returns:
A str in the form of a class construction. This string is in a form that
__could have been__ used to create this Container.
"""
out = "Container("
for widget in self._widgets:
out += widget.debug() + ", "
out = out.strip(", ")
out += ", **attrs)"
return out
class Splitter(Container):
"""A widget that displays other widgets, stacked horizontally."""
chars: dict[str, list[str] | str] = {"separator": " | "}
styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND}
keys = {
"previous": {keys.LEFT, "h", keys.CTRL_B},
"next": {keys.RIGHT, "l", keys.CTRL_F},
}
parent_align = HorizontalAlignment.RIGHT
def _align(
self, alignment: HorizontalAlignment, target_width: int, line: str
) -> tuple[int, str]:
"""Align a line
r/wordavalanches"""
available = target_width - real_length(line)
fill_style = self._get_style("fill")
char = fill_style(" ")
line = fill_style(line)
if alignment == HorizontalAlignment.CENTER:
padding, offset = divmod(available, 2)
return padding, padding * char + line + (padding + offset) * char
if alignment == HorizontalAlignment.RIGHT:
return available, available * char + line
return 0, line + available * char
def get_lines(self) -> list[str]:
"""Join all widgets horizontally."""
# An error will be raised if `separator` is not the correct type (str).
separator = self._get_style("separator")(self._get_char("separator")) # type: ignore
separator_length = real_length(separator)
target_width, error = divmod(
self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets)
)
vertical_lines = []
total_offset = 0
for widget in self._widgets:
inner = []
if widget.size_policy is SizePolicy.STATIC:
target_width += target_width - widget.width
width = target_width
else:
widget.width = target_width + error
width = widget.width
error = 0
aligned: str | None = None
for line in widget.get_lines():
# See `enums.py` for information about this ignore
padding, aligned = self._align(
cast(HorizontalAlignment, widget.parent_align), width, line
)
inner.append(aligned)
widget.pos = (
self.pos[0] + padding + total_offset,
self.pos[1] + (1 if type(widget).__name__ == "Container" else 0),
)
if aligned is not None:
total_offset += real_length(inner[-1]) + separator_length
vertical_lines.append(inner)
lines = []
for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width):
lines.append((reset() + separator).join(horizontal))
return lines
def debug(self) -> str:
"""Return identifiable information"""
return super().debug().replace("Container", "Splitter", 1)
| bczsalba__pytermgui |
54 | 54-60-33 | inproject | styles | [
"allow_fullscreen",
"bind",
"bindings",
"box",
"center",
"chars",
"contains",
"copy",
"debug",
"execute_binding",
"get_lines",
"handle_key",
"handle_mouse",
"id",
"is_bindable",
"is_selectable",
"keys",
"mro",
"parent_align",
"pop",
"print",
"remove",
"select",
"selectables",
"selectables_length",
"selected",
"serialize",
"serialized",
"set_char",
"set_recursive_depth",
"set_style",
"set_widgets",
"sidelength",
"size_policy",
"static_width",
"styles",
"vertical_align",
"wipe",
"_add_widget",
"_apply_vertalign",
"_get_aligners",
"_get_char",
"_get_style",
"_id_manager",
"_update_width",
"__add__",
"__annotations__",
"__base__",
"__bases__",
"__basicsize__",
"__call__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dictoffset__",
"__dir__",
"__doc__",
"__eq__",
"__flags__",
"__format__",
"__getattribute__",
"__getitem__",
"__hash__",
"__iadd__",
"__init__",
"__init_subclass__",
"__instancecheck__",
"__itemsize__",
"__iter__",
"__len__",
"__module__",
"__mro__",
"__name__",
"__ne__",
"__new__",
"__prepare__",
"__qualname__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__setitem__",
"__sizeof__",
"__slots__",
"__str__",
"__subclasscheck__",
"__subclasses__",
"__text_signature__",
"__weakrefoffset__"
] | """The module containing all of the layout-related widgets."""
# These widgets have more than the 7 allowed instance attributes.
# pylint: disable=too-many-instance-attributes
from __future__ import annotations
from itertools import zip_longest
from typing import Any, Callable, Iterator, cast
from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal
from ..context_managers import cursor_at
from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment
from ..exceptions import WidthExceededError
from ..helpers import real_length
from ..input import keys
from . import boxes
from . import styles as w_styles
from .base import Widget
class Container(Widget):
"""A widget that displays other widgets, stacked vertically."""
chars: dict[str, w_styles.CharType] = {
"border": ["| ", "-", " |", "-"],
"corner": [""] * 4,
}
styles = {
"border": w_styles.MARKUP,
"corner": w_styles.MARKUP,
"fill": w_styles.BACKGROUND,
}
keys = {
"next": {keys.DOWN, keys.CTRL_N, "j"},
"previous": {keys.UP, keys.CTRL_P, "k"},
}
serialized = Widget.serialized + ["_centered_axis"]
vertical_align = VerticalAlignment.CENTER
allow_fullscreen = True
# TODO: Add `WidgetConvertible`? type instead of Any
def __init__(self, *widgets: Any, **attrs: Any) -> None:
"""Initialize Container data"""
super().__init__(**attrs)
# TODO: This is just a band-aid.
if "width" not in attrs:
self.width = 40
self._widgets: list[Widget] = []
self._centered_axis: CenteringPolicy | None = None
self._prev_screen: tuple[int, int] = (0, 0)
self._has_printed = False
self.styles = type(self). | .copy()
self.chars = type(self).chars.copy()
for widget in widgets:
self._add_widget(widget)
self._drag_target: Widget | None = None
terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis))
@property
def sidelength(self) -> int:
"""Gets the length of left and right borders combined.
Returns:
An integer equal to the `pytermgui.helpers.real_length` of the concatenation of
the left and right borders of this widget, both with their respective styles
applied.
"""
chars = self._get_char("border")
style = self._get_style("border")
if not isinstance(chars, list):
return 0
left_border, _, right_border, _ = chars
return real_length(style(left_border) + style(right_border))
@property
def selectables(self) -> list[tuple[Widget, int]]:
"""Gets all selectable widgets and their inner indices.
This is used in order to have a constant reference to all selectable indices within this
widget.
Returns:
A list of tuples containing a widget and an integer each. For each widget that is
withing this one, it is added to this list as many times as it has selectables. Each
of the integers correspond to a selectable_index within the widget.
For example, a Container with a Button, InputField and an inner Container containing
3 selectables might return something like this:
```
[
(Button(...), 0),
(InputField(...), 0),
(Container(...), 0),
(Container(...), 1),
(Container(...), 2),
]
```
"""
_selectables: list[tuple[Widget, int]] = []
for widget in self._widgets:
if not widget.is_selectable:
continue
for i, (inner, _) in enumerate(widget.selectables):
_selectables.append((inner, i))
return _selectables
@property
def selectables_length(self) -> int:
"""Gets the length of the selectables list.
Returns:
An integer equal to the length of `self.selectables`.
"""
return len(self.selectables)
@property
def selected(self) -> Widget | None:
"""Returns the currently selected object
Returns:
The currently selected widget if selected_index is not None,
otherwise None.
"""
# TODO: Add deeper selection
if self.selected_index is None:
return None
if self.selected_index >= len(self.selectables):
return None
return self.selectables[self.selected_index][0]
@property
def box(self) -> boxes.Box:
"""Returns current box setting
Returns:
The currently set box instance.
"""
return self._box
@box.setter
def box(self, new: str | boxes.Box) -> None:
"""Applies a new box.
Args:
new: Either a `pytermgui.boxes.Box` instance or a string
analogous to one of the default box names.
"""
if isinstance(new, str):
from_module = vars(boxes).get(new)
if from_module is None:
raise ValueError(f"Unknown box type {new}.")
new = from_module
assert isinstance(new, boxes.Box)
self._box = new
new.set_chars_of(self)
def __iadd__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self._add_widget(other)
return self
def __add__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
This method is analogous to `Container.__iadd__`.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self.__iadd__(other)
return self
def __iter__(self) -> Iterator[Widget]:
"""Gets an iterator of self._widgets.
Yields:
The next widget.
"""
for widget in self._widgets:
yield widget
def __len__(self) -> int:
"""Gets the length of the widgets list.
Returns:
An integer describing len(self._widgets).
"""
return len(self._widgets)
def __getitem__(self, sli: int | slice) -> Widget | list[Widget]:
"""Gets an item from self._widgets.
Args:
sli: Slice of the list.
Returns:
The slice in the list.
"""
return self._widgets[sli]
def __setitem__(self, index: int, value: Any) -> None:
"""Sets an item in self._widgets.
Args:
index: The index to be set.
value: The new widget at this index.
"""
self._widgets[index] = value
def __contains__(self, other: object) -> bool:
"""Determines if self._widgets contains other widget.
Args:
other: Any widget-like.
Returns:
A boolean describing whether `other` is in `self.widgets`
"""
return other in self._widgets
def _add_widget(self, other: object, run_get_lines: bool = True) -> None:
"""Adds other to this widget.
Args:
other: Any widget-like object.
run_get_lines: Boolean controlling whether the self.get_lines is ran.
"""
if not isinstance(other, Widget):
to_widget = Widget.from_data(other)
if to_widget is None:
raise ValueError(
f"Could not convert {other} of type {type(other)} to a Widget!"
)
other = to_widget
# This is safe to do, as it would've raised an exception above already
assert isinstance(other, Widget)
self._widgets.append(other)
if isinstance(other, Container):
other.set_recursive_depth(self.depth + 2)
else:
other.depth = self.depth + 1
other.get_lines()
other.parent = self
if run_get_lines:
self.get_lines()
def _get_aligners(
self, widget: Widget, borders: tuple[str, str]
) -> tuple[Callable[[str], str], int]:
"""Gets an aligning method and position offset.
Args:
widget: The widget to align.
borders: The left and right borders to put the widget within.
Returns:
A tuple of a method that, when called with a line, will return that line
centered using the passed in widget's parent_align and width, as well as
the horizontal offset resulting from the widget being aligned.
"""
left, right = borders
char = self._get_style("fill")(" ")
def _align_left(text: str) -> str:
"""Align line to the left"""
padding = self.width - real_length(left + right) - real_length(text)
return left + text + padding * char + right
def _align_center(text: str) -> str:
"""Align line to the center"""
total = self.width - real_length(left + right) - real_length(text)
padding, offset = divmod(total, 2)
return left + (padding + offset) * char + text + padding * char + right
def _align_right(text: str) -> str:
"""Align line to the right"""
padding = self.width - real_length(left + right) - real_length(text)
return left + padding * char + text + right
if widget.parent_align == HorizontalAlignment.CENTER:
total = self.width - real_length(left + right) - widget.width
padding, offset = divmod(total, 2)
return _align_center, real_length(left) + padding + offset
if widget.parent_align == HorizontalAlignment.RIGHT:
return _align_right, self.width - real_length(left) - widget.width
# Default to left-aligned
return _align_left, real_length(left)
def _update_width(self, widget: Widget) -> None:
"""Updates the width of widget or self.
This method respects widget.size_policy.
Args:
widget: The widget to update/base updates on.
"""
available = (
self.width - self.sidelength - (0 if isinstance(widget, Container) else 1)
)
if widget.size_policy == SizePolicy.FILL:
widget.width = available
return
if widget.size_policy == SizePolicy.RELATIVE:
widget.width = widget.relative_width * available
return
if widget.width > available:
if widget.size_policy == SizePolicy.STATIC:
raise WidthExceededError(
f"Widget {widget}'s static width of {widget.width}"
+ f" exceeds its parent's available width {available}."
""
)
widget.width = available
def _apply_vertalign(
self, lines: list[str], diff: int, padder: str
) -> tuple[int, list[str]]:
"""Insert padder line into lines diff times, depending on self.vertical_align.
Args:
lines: The list of lines to align.
diff: The available height.
padder: The line to use to pad.
Returns:
A tuple containing the vertical offset as well as the padded list of lines.
Raises:
NotImplementedError: The given vertical alignment is not implemented.
"""
if self.vertical_align == VerticalAlignment.BOTTOM:
for _ in range(diff):
lines.insert(0, padder)
return diff, lines
if self.vertical_align == VerticalAlignment.TOP:
for _ in range(diff):
lines.append(padder)
return 0, lines
if self.vertical_align == VerticalAlignment.CENTER:
top, extra = divmod(diff, 2)
bottom = top + extra
for _ in range(top):
lines.insert(0, padder)
for _ in range(bottom):
lines.append(padder)
return top, lines
raise NotImplementedError(
f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}."
)
def get_lines(self) -> list[str]:
"""Gets all lines by spacing out inner widgets.
This method reflects & applies both width settings, as well as
the `parent_align` field.
Returns:
A list of all lines that represent this Container.
"""
def _get_border(left: str, char: str, right: str) -> str:
"""Gets a top or bottom border.
Args:
left: Left corner character.
char: Border character filling between left & right.
right: Right corner character.
Returns:
The border line.
"""
offset = real_length(left + right)
return left + char * (self.width - offset) + right
lines = []
style = self._get_style("border")
borders = [style(char) for char in self._get_char("border")]
style = self._get_style("corner")
corners = [style(char) for char in self._get_char("corner")]
has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0)
align = lambda item: item
for widget in self._widgets:
align, offset = self._get_aligners(widget, (borders[0], borders[2]))
self._update_width(widget)
widget.pos = (
self.pos[0] + offset,
self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0),
)
widget_lines = []
for line in widget.get_lines():
widget_lines.append(align(line))
lines.extend(widget_lines)
vertical_offset, lines = self._apply_vertalign(
lines, self.height - len(lines) - sum(has_top_bottom), align("")
)
for widget in self._widgets:
widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset)
# TODO: This is wasteful.
widget.get_lines()
if has_top_bottom[0]:
lines.insert(0, _get_border(corners[0], borders[1], corners[1]))
if has_top_bottom[1]:
lines.append(_get_border(corners[3], borders[3], corners[2]))
self.height = len(lines)
return lines
def set_widgets(self, new: list[Widget]) -> None:
"""Sets new list in place of self._widgets.
Args:
new: The new widget list.
"""
self._widgets = []
for widget in new:
self._add_widget(widget)
def serialize(self) -> dict[str, Any]:
"""Serializes this Container, adding in serializations of all widgets.
See `pytermgui.widgets.base.Widget.serialize` for more info.
Returns:
The dictionary containing all serialized data.
"""
out = super().serialize()
out["_widgets"] = []
for widget in self._widgets:
out["_widgets"].append(widget.serialize())
return out
def pop(self, index: int = -1) -> Widget:
"""Pops widget from self._widgets.
Analogous to self._widgets.pop(index).
Args:
index: The index to operate on.
Returns:
The widget that was popped off the list.
"""
return self._widgets.pop(index)
def remove(self, other: Widget) -> None:
"""Remove widget from self._widgets
Analogous to self._widgets.remove(other).
Args:
widget: The widget to remove.
"""
return self._widgets.remove(other)
def set_recursive_depth(self, value: int) -> None:
"""Set depth for this Container and all its children.
All inner widgets will receive value+1 as their new depth.
Args:
value: The new depth to use as the base depth.
"""
self.depth = value
for widget in self._widgets:
if isinstance(widget, Container):
widget.set_recursive_depth(value + 1)
else:
widget.depth = value
def select(self, index: int | None = None) -> None:
"""Selects inner subwidget.
Args:
index: The index to select.
Raises:
IndexError: The index provided was beyond len(self.selectables).
"""
# Unselect all sub-elements
for other in self._widgets:
if other.selectables_length > 0:
other.select(None)
if index is not None:
if index >= len(self.selectables) is None:
raise IndexError("Container selection index out of range")
widget, inner_index = self.selectables[index]
widget.select(inner_index)
self.selected_index = index
def center(
self, where: CenteringPolicy | None = None, store: bool = True
) -> Container:
"""Centers this object to the given axis.
Args:
where: A CenteringPolicy describing the place to center to
store: When set, this centering will be reapplied during every
print, as well as when calling this method with no arguments.
Returns:
This Container.
"""
# Refresh in case changes happened
self.get_lines()
if where is None:
# See `enums.py` for explanation about this ignore.
where = CenteringPolicy.get_default() # type: ignore
centerx = centery = where is CenteringPolicy.ALL
centerx |= where is CenteringPolicy.HORIZONTAL
centery |= where is CenteringPolicy.VERTICAL
pos = list(self.pos)
if centerx:
pos[0] = (terminal.width - self.width + 2) // 2
if centery:
pos[1] = (terminal.height - self.height + 2) // 2
self.pos = (pos[0], pos[1])
if store:
self._centered_axis = where
self._prev_screen = terminal.size
return self
def handle_mouse(self, event: MouseEvent) -> bool:
"""Applies a mouse event on all children.
Args:
event: The event to handle
Returns:
A boolean showing whether the event was handled.
"""
if event.action is MouseAction.RELEASE:
# Force RELEASE event to be sent
if self._drag_target is not None:
self._drag_target.handle_mouse(
MouseEvent(MouseAction.RELEASE, event.position)
)
self._drag_target = None
if self._drag_target is not None:
return self._drag_target.handle_mouse(event)
selectables_index = 0
for widget in self._widgets:
if widget.contains(event.position):
handled = widget.handle_mouse(event)
if widget.selected_index is not None:
selectables_index += widget.selected_index
if event.action is MouseAction.LEFT_CLICK:
self._drag_target = widget
if handled:
self.select(selectables_index)
return handled
if widget.is_selectable:
selectables_index += widget.selectables_length
return False
def handle_key(self, key: str) -> bool:
"""Handles a keypress, returns its success.
Args:
key: A key str.
Returns:
A boolean showing whether the key was handled.
"""
def _is_nav(key: str) -> bool:
"""Determine if a key is in the navigation sets"""
return key in self.keys["next"] | self.keys["previous"]
if self.selected is not None and self.selected.handle_key(key):
return True
# Only use navigation when there is more than one selectable
if self.selectables_length > 1 and _is_nav(key):
handled = False
if self.selected_index is None:
self.select(0)
assert isinstance(self.selected_index, int)
if key in self.keys["previous"]:
# No more selectables left, user wants to exit Container
# upwards.
if self.selected_index == 0:
return False
self.select(self.selected_index - 1)
handled = True
elif key in self.keys["next"]:
# Stop selection at last element, return as unhandled
new = self.selected_index + 1
if new == len(self.selectables):
return False
self.select(new)
handled = True
if handled:
return True
if key == keys.ENTER and self.selected is not None:
if self.selected.selected_index is not None:
self.selected.handle_key(key)
return True
return False
def wipe(self) -> None:
"""Wipes the characters occupied by the object"""
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(real_length(line) * " ")
def print(self) -> None:
"""Prints this Container.
If the screen size has changed since last `print` call, the object
will be centered based on its `_centered_axis`.
"""
if not terminal.size == self._prev_screen:
clear()
self.center(self._centered_axis)
self._prev_screen = terminal.size
if self.allow_fullscreen:
self.pos = terminal.origin
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(line)
self._has_printed = True
def debug(self) -> str:
"""Returns a string with identifiable information on this widget.
Returns:
A str in the form of a class construction. This string is in a form that
__could have been__ used to create this Container.
"""
out = "Container("
for widget in self._widgets:
out += widget.debug() + ", "
out = out.strip(", ")
out += ", **attrs)"
return out
class Splitter(Container):
"""A widget that displays other widgets, stacked horizontally."""
chars: dict[str, list[str] | str] = {"separator": " | "}
styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND}
keys = {
"previous": {keys.LEFT, "h", keys.CTRL_B},
"next": {keys.RIGHT, "l", keys.CTRL_F},
}
parent_align = HorizontalAlignment.RIGHT
def _align(
self, alignment: HorizontalAlignment, target_width: int, line: str
) -> tuple[int, str]:
"""Align a line
r/wordavalanches"""
available = target_width - real_length(line)
fill_style = self._get_style("fill")
char = fill_style(" ")
line = fill_style(line)
if alignment == HorizontalAlignment.CENTER:
padding, offset = divmod(available, 2)
return padding, padding * char + line + (padding + offset) * char
if alignment == HorizontalAlignment.RIGHT:
return available, available * char + line
return 0, line + available * char
def get_lines(self) -> list[str]:
"""Join all widgets horizontally."""
# An error will be raised if `separator` is not the correct type (str).
separator = self._get_style("separator")(self._get_char("separator")) # type: ignore
separator_length = real_length(separator)
target_width, error = divmod(
self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets)
)
vertical_lines = []
total_offset = 0
for widget in self._widgets:
inner = []
if widget.size_policy is SizePolicy.STATIC:
target_width += target_width - widget.width
width = target_width
else:
widget.width = target_width + error
width = widget.width
error = 0
aligned: str | None = None
for line in widget.get_lines():
# See `enums.py` for information about this ignore
padding, aligned = self._align(
cast(HorizontalAlignment, widget.parent_align), width, line
)
inner.append(aligned)
widget.pos = (
self.pos[0] + padding + total_offset,
self.pos[1] + (1 if type(widget).__name__ == "Container" else 0),
)
if aligned is not None:
total_offset += real_length(inner[-1]) + separator_length
vertical_lines.append(inner)
lines = []
for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width):
lines.append((reset() + separator).join(horizontal))
return lines
def debug(self) -> str:
"""Return identifiable information"""
return super().debug().replace("Container", "Splitter", 1)
| bczsalba__pytermgui |
54 | 54-60-40 | inproject | copy | [
"clear",
"copy",
"fromkeys",
"get",
"items",
"keys",
"pop",
"popitem",
"setdefault",
"update",
"values",
"__annotations__",
"__class__",
"__class_getitem__",
"__contains__",
"__delattr__",
"__delitem__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__getitem__",
"__hash__",
"__init__",
"__init_subclass__",
"__ior__",
"__iter__",
"__len__",
"__module__",
"__ne__",
"__new__",
"__or__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__reversed__",
"__setattr__",
"__setitem__",
"__sizeof__",
"__slots__",
"__str__"
] | """The module containing all of the layout-related widgets."""
# These widgets have more than the 7 allowed instance attributes.
# pylint: disable=too-many-instance-attributes
from __future__ import annotations
from itertools import zip_longest
from typing import Any, Callable, Iterator, cast
from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal
from ..context_managers import cursor_at
from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment
from ..exceptions import WidthExceededError
from ..helpers import real_length
from ..input import keys
from . import boxes
from . import styles as w_styles
from .base import Widget
class Container(Widget):
"""A widget that displays other widgets, stacked vertically."""
chars: dict[str, w_styles.CharType] = {
"border": ["| ", "-", " |", "-"],
"corner": [""] * 4,
}
styles = {
"border": w_styles.MARKUP,
"corner": w_styles.MARKUP,
"fill": w_styles.BACKGROUND,
}
keys = {
"next": {keys.DOWN, keys.CTRL_N, "j"},
"previous": {keys.UP, keys.CTRL_P, "k"},
}
serialized = Widget.serialized + ["_centered_axis"]
vertical_align = VerticalAlignment.CENTER
allow_fullscreen = True
# TODO: Add `WidgetConvertible`? type instead of Any
def __init__(self, *widgets: Any, **attrs: Any) -> None:
"""Initialize Container data"""
super().__init__(**attrs)
# TODO: This is just a band-aid.
if "width" not in attrs:
self.width = 40
self._widgets: list[Widget] = []
self._centered_axis: CenteringPolicy | None = None
self._prev_screen: tuple[int, int] = (0, 0)
self._has_printed = False
self.styles = type(self).styles. | ()
self.chars = type(self).chars.copy()
for widget in widgets:
self._add_widget(widget)
self._drag_target: Widget | None = None
terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis))
@property
def sidelength(self) -> int:
"""Gets the length of left and right borders combined.
Returns:
An integer equal to the `pytermgui.helpers.real_length` of the concatenation of
the left and right borders of this widget, both with their respective styles
applied.
"""
chars = self._get_char("border")
style = self._get_style("border")
if not isinstance(chars, list):
return 0
left_border, _, right_border, _ = chars
return real_length(style(left_border) + style(right_border))
@property
def selectables(self) -> list[tuple[Widget, int]]:
"""Gets all selectable widgets and their inner indices.
This is used in order to have a constant reference to all selectable indices within this
widget.
Returns:
A list of tuples containing a widget and an integer each. For each widget that is
withing this one, it is added to this list as many times as it has selectables. Each
of the integers correspond to a selectable_index within the widget.
For example, a Container with a Button, InputField and an inner Container containing
3 selectables might return something like this:
```
[
(Button(...), 0),
(InputField(...), 0),
(Container(...), 0),
(Container(...), 1),
(Container(...), 2),
]
```
"""
_selectables: list[tuple[Widget, int]] = []
for widget in self._widgets:
if not widget.is_selectable:
continue
for i, (inner, _) in enumerate(widget.selectables):
_selectables.append((inner, i))
return _selectables
@property
def selectables_length(self) -> int:
"""Gets the length of the selectables list.
Returns:
An integer equal to the length of `self.selectables`.
"""
return len(self.selectables)
@property
def selected(self) -> Widget | None:
"""Returns the currently selected object
Returns:
The currently selected widget if selected_index is not None,
otherwise None.
"""
# TODO: Add deeper selection
if self.selected_index is None:
return None
if self.selected_index >= len(self.selectables):
return None
return self.selectables[self.selected_index][0]
@property
def box(self) -> boxes.Box:
"""Returns current box setting
Returns:
The currently set box instance.
"""
return self._box
@box.setter
def box(self, new: str | boxes.Box) -> None:
"""Applies a new box.
Args:
new: Either a `pytermgui.boxes.Box` instance or a string
analogous to one of the default box names.
"""
if isinstance(new, str):
from_module = vars(boxes).get(new)
if from_module is None:
raise ValueError(f"Unknown box type {new}.")
new = from_module
assert isinstance(new, boxes.Box)
self._box = new
new.set_chars_of(self)
def __iadd__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self._add_widget(other)
return self
def __add__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
This method is analogous to `Container.__iadd__`.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self.__iadd__(other)
return self
def __iter__(self) -> Iterator[Widget]:
"""Gets an iterator of self._widgets.
Yields:
The next widget.
"""
for widget in self._widgets:
yield widget
def __len__(self) -> int:
"""Gets the length of the widgets list.
Returns:
An integer describing len(self._widgets).
"""
return len(self._widgets)
def __getitem__(self, sli: int | slice) -> Widget | list[Widget]:
"""Gets an item from self._widgets.
Args:
sli: Slice of the list.
Returns:
The slice in the list.
"""
return self._widgets[sli]
def __setitem__(self, index: int, value: Any) -> None:
"""Sets an item in self._widgets.
Args:
index: The index to be set.
value: The new widget at this index.
"""
self._widgets[index] = value
def __contains__(self, other: object) -> bool:
"""Determines if self._widgets contains other widget.
Args:
other: Any widget-like.
Returns:
A boolean describing whether `other` is in `self.widgets`
"""
return other in self._widgets
def _add_widget(self, other: object, run_get_lines: bool = True) -> None:
"""Adds other to this widget.
Args:
other: Any widget-like object.
run_get_lines: Boolean controlling whether the self.get_lines is ran.
"""
if not isinstance(other, Widget):
to_widget = Widget.from_data(other)
if to_widget is None:
raise ValueError(
f"Could not convert {other} of type {type(other)} to a Widget!"
)
other = to_widget
# This is safe to do, as it would've raised an exception above already
assert isinstance(other, Widget)
self._widgets.append(other)
if isinstance(other, Container):
other.set_recursive_depth(self.depth + 2)
else:
other.depth = self.depth + 1
other.get_lines()
other.parent = self
if run_get_lines:
self.get_lines()
def _get_aligners(
self, widget: Widget, borders: tuple[str, str]
) -> tuple[Callable[[str], str], int]:
"""Gets an aligning method and position offset.
Args:
widget: The widget to align.
borders: The left and right borders to put the widget within.
Returns:
A tuple of a method that, when called with a line, will return that line
centered using the passed in widget's parent_align and width, as well as
the horizontal offset resulting from the widget being aligned.
"""
left, right = borders
char = self._get_style("fill")(" ")
def _align_left(text: str) -> str:
"""Align line to the left"""
padding = self.width - real_length(left + right) - real_length(text)
return left + text + padding * char + right
def _align_center(text: str) -> str:
"""Align line to the center"""
total = self.width - real_length(left + right) - real_length(text)
padding, offset = divmod(total, 2)
return left + (padding + offset) * char + text + padding * char + right
def _align_right(text: str) -> str:
"""Align line to the right"""
padding = self.width - real_length(left + right) - real_length(text)
return left + padding * char + text + right
if widget.parent_align == HorizontalAlignment.CENTER:
total = self.width - real_length(left + right) - widget.width
padding, offset = divmod(total, 2)
return _align_center, real_length(left) + padding + offset
if widget.parent_align == HorizontalAlignment.RIGHT:
return _align_right, self.width - real_length(left) - widget.width
# Default to left-aligned
return _align_left, real_length(left)
def _update_width(self, widget: Widget) -> None:
"""Updates the width of widget or self.
This method respects widget.size_policy.
Args:
widget: The widget to update/base updates on.
"""
available = (
self.width - self.sidelength - (0 if isinstance(widget, Container) else 1)
)
if widget.size_policy == SizePolicy.FILL:
widget.width = available
return
if widget.size_policy == SizePolicy.RELATIVE:
widget.width = widget.relative_width * available
return
if widget.width > available:
if widget.size_policy == SizePolicy.STATIC:
raise WidthExceededError(
f"Widget {widget}'s static width of {widget.width}"
+ f" exceeds its parent's available width {available}."
""
)
widget.width = available
def _apply_vertalign(
self, lines: list[str], diff: int, padder: str
) -> tuple[int, list[str]]:
"""Insert padder line into lines diff times, depending on self.vertical_align.
Args:
lines: The list of lines to align.
diff: The available height.
padder: The line to use to pad.
Returns:
A tuple containing the vertical offset as well as the padded list of lines.
Raises:
NotImplementedError: The given vertical alignment is not implemented.
"""
if self.vertical_align == VerticalAlignment.BOTTOM:
for _ in range(diff):
lines.insert(0, padder)
return diff, lines
if self.vertical_align == VerticalAlignment.TOP:
for _ in range(diff):
lines.append(padder)
return 0, lines
if self.vertical_align == VerticalAlignment.CENTER:
top, extra = divmod(diff, 2)
bottom = top + extra
for _ in range(top):
lines.insert(0, padder)
for _ in range(bottom):
lines.append(padder)
return top, lines
raise NotImplementedError(
f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}."
)
def get_lines(self) -> list[str]:
"""Gets all lines by spacing out inner widgets.
This method reflects & applies both width settings, as well as
the `parent_align` field.
Returns:
A list of all lines that represent this Container.
"""
def _get_border(left: str, char: str, right: str) -> str:
"""Gets a top or bottom border.
Args:
left: Left corner character.
char: Border character filling between left & right.
right: Right corner character.
Returns:
The border line.
"""
offset = real_length(left + right)
return left + char * (self.width - offset) + right
lines = []
style = self._get_style("border")
borders = [style(char) for char in self._get_char("border")]
style = self._get_style("corner")
corners = [style(char) for char in self._get_char("corner")]
has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0)
align = lambda item: item
for widget in self._widgets:
align, offset = self._get_aligners(widget, (borders[0], borders[2]))
self._update_width(widget)
widget.pos = (
self.pos[0] + offset,
self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0),
)
widget_lines = []
for line in widget.get_lines():
widget_lines.append(align(line))
lines.extend(widget_lines)
vertical_offset, lines = self._apply_vertalign(
lines, self.height - len(lines) - sum(has_top_bottom), align("")
)
for widget in self._widgets:
widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset)
# TODO: This is wasteful.
widget.get_lines()
if has_top_bottom[0]:
lines.insert(0, _get_border(corners[0], borders[1], corners[1]))
if has_top_bottom[1]:
lines.append(_get_border(corners[3], borders[3], corners[2]))
self.height = len(lines)
return lines
def set_widgets(self, new: list[Widget]) -> None:
"""Sets new list in place of self._widgets.
Args:
new: The new widget list.
"""
self._widgets = []
for widget in new:
self._add_widget(widget)
def serialize(self) -> dict[str, Any]:
"""Serializes this Container, adding in serializations of all widgets.
See `pytermgui.widgets.base.Widget.serialize` for more info.
Returns:
The dictionary containing all serialized data.
"""
out = super().serialize()
out["_widgets"] = []
for widget in self._widgets:
out["_widgets"].append(widget.serialize())
return out
def pop(self, index: int = -1) -> Widget:
"""Pops widget from self._widgets.
Analogous to self._widgets.pop(index).
Args:
index: The index to operate on.
Returns:
The widget that was popped off the list.
"""
return self._widgets.pop(index)
def remove(self, other: Widget) -> None:
"""Remove widget from self._widgets
Analogous to self._widgets.remove(other).
Args:
widget: The widget to remove.
"""
return self._widgets.remove(other)
def set_recursive_depth(self, value: int) -> None:
"""Set depth for this Container and all its children.
All inner widgets will receive value+1 as their new depth.
Args:
value: The new depth to use as the base depth.
"""
self.depth = value
for widget in self._widgets:
if isinstance(widget, Container):
widget.set_recursive_depth(value + 1)
else:
widget.depth = value
def select(self, index: int | None = None) -> None:
"""Selects inner subwidget.
Args:
index: The index to select.
Raises:
IndexError: The index provided was beyond len(self.selectables).
"""
# Unselect all sub-elements
for other in self._widgets:
if other.selectables_length > 0:
other.select(None)
if index is not None:
if index >= len(self.selectables) is None:
raise IndexError("Container selection index out of range")
widget, inner_index = self.selectables[index]
widget.select(inner_index)
self.selected_index = index
def center(
self, where: CenteringPolicy | None = None, store: bool = True
) -> Container:
"""Centers this object to the given axis.
Args:
where: A CenteringPolicy describing the place to center to
store: When set, this centering will be reapplied during every
print, as well as when calling this method with no arguments.
Returns:
This Container.
"""
# Refresh in case changes happened
self.get_lines()
if where is None:
# See `enums.py` for explanation about this ignore.
where = CenteringPolicy.get_default() # type: ignore
centerx = centery = where is CenteringPolicy.ALL
centerx |= where is CenteringPolicy.HORIZONTAL
centery |= where is CenteringPolicy.VERTICAL
pos = list(self.pos)
if centerx:
pos[0] = (terminal.width - self.width + 2) // 2
if centery:
pos[1] = (terminal.height - self.height + 2) // 2
self.pos = (pos[0], pos[1])
if store:
self._centered_axis = where
self._prev_screen = terminal.size
return self
def handle_mouse(self, event: MouseEvent) -> bool:
"""Applies a mouse event on all children.
Args:
event: The event to handle
Returns:
A boolean showing whether the event was handled.
"""
if event.action is MouseAction.RELEASE:
# Force RELEASE event to be sent
if self._drag_target is not None:
self._drag_target.handle_mouse(
MouseEvent(MouseAction.RELEASE, event.position)
)
self._drag_target = None
if self._drag_target is not None:
return self._drag_target.handle_mouse(event)
selectables_index = 0
for widget in self._widgets:
if widget.contains(event.position):
handled = widget.handle_mouse(event)
if widget.selected_index is not None:
selectables_index += widget.selected_index
if event.action is MouseAction.LEFT_CLICK:
self._drag_target = widget
if handled:
self.select(selectables_index)
return handled
if widget.is_selectable:
selectables_index += widget.selectables_length
return False
def handle_key(self, key: str) -> bool:
"""Handles a keypress, returns its success.
Args:
key: A key str.
Returns:
A boolean showing whether the key was handled.
"""
def _is_nav(key: str) -> bool:
"""Determine if a key is in the navigation sets"""
return key in self.keys["next"] | self.keys["previous"]
if self.selected is not None and self.selected.handle_key(key):
return True
# Only use navigation when there is more than one selectable
if self.selectables_length > 1 and _is_nav(key):
handled = False
if self.selected_index is None:
self.select(0)
assert isinstance(self.selected_index, int)
if key in self.keys["previous"]:
# No more selectables left, user wants to exit Container
# upwards.
if self.selected_index == 0:
return False
self.select(self.selected_index - 1)
handled = True
elif key in self.keys["next"]:
# Stop selection at last element, return as unhandled
new = self.selected_index + 1
if new == len(self.selectables):
return False
self.select(new)
handled = True
if handled:
return True
if key == keys.ENTER and self.selected is not None:
if self.selected.selected_index is not None:
self.selected.handle_key(key)
return True
return False
def wipe(self) -> None:
"""Wipes the characters occupied by the object"""
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(real_length(line) * " ")
def print(self) -> None:
"""Prints this Container.
If the screen size has changed since last `print` call, the object
will be centered based on its `_centered_axis`.
"""
if not terminal.size == self._prev_screen:
clear()
self.center(self._centered_axis)
self._prev_screen = terminal.size
if self.allow_fullscreen:
self.pos = terminal.origin
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(line)
self._has_printed = True
def debug(self) -> str:
"""Returns a string with identifiable information on this widget.
Returns:
A str in the form of a class construction. This string is in a form that
__could have been__ used to create this Container.
"""
out = "Container("
for widget in self._widgets:
out += widget.debug() + ", "
out = out.strip(", ")
out += ", **attrs)"
return out
class Splitter(Container):
"""A widget that displays other widgets, stacked horizontally."""
chars: dict[str, list[str] | str] = {"separator": " | "}
styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND}
keys = {
"previous": {keys.LEFT, "h", keys.CTRL_B},
"next": {keys.RIGHT, "l", keys.CTRL_F},
}
parent_align = HorizontalAlignment.RIGHT
def _align(
self, alignment: HorizontalAlignment, target_width: int, line: str
) -> tuple[int, str]:
"""Align a line
r/wordavalanches"""
available = target_width - real_length(line)
fill_style = self._get_style("fill")
char = fill_style(" ")
line = fill_style(line)
if alignment == HorizontalAlignment.CENTER:
padding, offset = divmod(available, 2)
return padding, padding * char + line + (padding + offset) * char
if alignment == HorizontalAlignment.RIGHT:
return available, available * char + line
return 0, line + available * char
def get_lines(self) -> list[str]:
"""Join all widgets horizontally."""
# An error will be raised if `separator` is not the correct type (str).
separator = self._get_style("separator")(self._get_char("separator")) # type: ignore
separator_length = real_length(separator)
target_width, error = divmod(
self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets)
)
vertical_lines = []
total_offset = 0
for widget in self._widgets:
inner = []
if widget.size_policy is SizePolicy.STATIC:
target_width += target_width - widget.width
width = target_width
else:
widget.width = target_width + error
width = widget.width
error = 0
aligned: str | None = None
for line in widget.get_lines():
# See `enums.py` for information about this ignore
padding, aligned = self._align(
cast(HorizontalAlignment, widget.parent_align), width, line
)
inner.append(aligned)
widget.pos = (
self.pos[0] + padding + total_offset,
self.pos[1] + (1 if type(widget).__name__ == "Container" else 0),
)
if aligned is not None:
total_offset += real_length(inner[-1]) + separator_length
vertical_lines.append(inner)
lines = []
for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width):
lines.append((reset() + separator).join(horizontal))
return lines
def debug(self) -> str:
"""Return identifiable information"""
return super().debug().replace("Container", "Splitter", 1)
| bczsalba__pytermgui |
54 | 54-67-17 | inproject | subscribe | [
"fill",
"height",
"margins",
"origin",
"RESIZE",
"size",
"subscribe",
"width",
"_alt_sigwinch",
"_call_listener",
"_get_size",
"_listeners",
"_update_size",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """The module containing all of the layout-related widgets."""
# These widgets have more than the 7 allowed instance attributes.
# pylint: disable=too-many-instance-attributes
from __future__ import annotations
from itertools import zip_longest
from typing import Any, Callable, Iterator, cast
from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal
from ..context_managers import cursor_at
from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment
from ..exceptions import WidthExceededError
from ..helpers import real_length
from ..input import keys
from . import boxes
from . import styles as w_styles
from .base import Widget
class Container(Widget):
"""A widget that displays other widgets, stacked vertically."""
chars: dict[str, w_styles.CharType] = {
"border": ["| ", "-", " |", "-"],
"corner": [""] * 4,
}
styles = {
"border": w_styles.MARKUP,
"corner": w_styles.MARKUP,
"fill": w_styles.BACKGROUND,
}
keys = {
"next": {keys.DOWN, keys.CTRL_N, "j"},
"previous": {keys.UP, keys.CTRL_P, "k"},
}
serialized = Widget.serialized + ["_centered_axis"]
vertical_align = VerticalAlignment.CENTER
allow_fullscreen = True
# TODO: Add `WidgetConvertible`? type instead of Any
def __init__(self, *widgets: Any, **attrs: Any) -> None:
"""Initialize Container data"""
super().__init__(**attrs)
# TODO: This is just a band-aid.
if "width" not in attrs:
self.width = 40
self._widgets: list[Widget] = []
self._centered_axis: CenteringPolicy | None = None
self._prev_screen: tuple[int, int] = (0, 0)
self._has_printed = False
self.styles = type(self).styles.copy()
self.chars = type(self).chars.copy()
for widget in widgets:
self._add_widget(widget)
self._drag_target: Widget | None = None
terminal. | (terminal.RESIZE, lambda *_: self.center(self._centered_axis))
@property
def sidelength(self) -> int:
"""Gets the length of left and right borders combined.
Returns:
An integer equal to the `pytermgui.helpers.real_length` of the concatenation of
the left and right borders of this widget, both with their respective styles
applied.
"""
chars = self._get_char("border")
style = self._get_style("border")
if not isinstance(chars, list):
return 0
left_border, _, right_border, _ = chars
return real_length(style(left_border) + style(right_border))
@property
def selectables(self) -> list[tuple[Widget, int]]:
"""Gets all selectable widgets and their inner indices.
This is used in order to have a constant reference to all selectable indices within this
widget.
Returns:
A list of tuples containing a widget and an integer each. For each widget that is
withing this one, it is added to this list as many times as it has selectables. Each
of the integers correspond to a selectable_index within the widget.
For example, a Container with a Button, InputField and an inner Container containing
3 selectables might return something like this:
```
[
(Button(...), 0),
(InputField(...), 0),
(Container(...), 0),
(Container(...), 1),
(Container(...), 2),
]
```
"""
_selectables: list[tuple[Widget, int]] = []
for widget in self._widgets:
if not widget.is_selectable:
continue
for i, (inner, _) in enumerate(widget.selectables):
_selectables.append((inner, i))
return _selectables
@property
def selectables_length(self) -> int:
"""Gets the length of the selectables list.
Returns:
An integer equal to the length of `self.selectables`.
"""
return len(self.selectables)
@property
def selected(self) -> Widget | None:
"""Returns the currently selected object
Returns:
The currently selected widget if selected_index is not None,
otherwise None.
"""
# TODO: Add deeper selection
if self.selected_index is None:
return None
if self.selected_index >= len(self.selectables):
return None
return self.selectables[self.selected_index][0]
@property
def box(self) -> boxes.Box:
"""Returns current box setting
Returns:
The currently set box instance.
"""
return self._box
@box.setter
def box(self, new: str | boxes.Box) -> None:
"""Applies a new box.
Args:
new: Either a `pytermgui.boxes.Box` instance or a string
analogous to one of the default box names.
"""
if isinstance(new, str):
from_module = vars(boxes).get(new)
if from_module is None:
raise ValueError(f"Unknown box type {new}.")
new = from_module
assert isinstance(new, boxes.Box)
self._box = new
new.set_chars_of(self)
def __iadd__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self._add_widget(other)
return self
def __add__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
This method is analogous to `Container.__iadd__`.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self.__iadd__(other)
return self
def __iter__(self) -> Iterator[Widget]:
"""Gets an iterator of self._widgets.
Yields:
The next widget.
"""
for widget in self._widgets:
yield widget
def __len__(self) -> int:
"""Gets the length of the widgets list.
Returns:
An integer describing len(self._widgets).
"""
return len(self._widgets)
def __getitem__(self, sli: int | slice) -> Widget | list[Widget]:
"""Gets an item from self._widgets.
Args:
sli: Slice of the list.
Returns:
The slice in the list.
"""
return self._widgets[sli]
def __setitem__(self, index: int, value: Any) -> None:
"""Sets an item in self._widgets.
Args:
index: The index to be set.
value: The new widget at this index.
"""
self._widgets[index] = value
def __contains__(self, other: object) -> bool:
"""Determines if self._widgets contains other widget.
Args:
other: Any widget-like.
Returns:
A boolean describing whether `other` is in `self.widgets`
"""
return other in self._widgets
def _add_widget(self, other: object, run_get_lines: bool = True) -> None:
"""Adds other to this widget.
Args:
other: Any widget-like object.
run_get_lines: Boolean controlling whether the self.get_lines is ran.
"""
if not isinstance(other, Widget):
to_widget = Widget.from_data(other)
if to_widget is None:
raise ValueError(
f"Could not convert {other} of type {type(other)} to a Widget!"
)
other = to_widget
# This is safe to do, as it would've raised an exception above already
assert isinstance(other, Widget)
self._widgets.append(other)
if isinstance(other, Container):
other.set_recursive_depth(self.depth + 2)
else:
other.depth = self.depth + 1
other.get_lines()
other.parent = self
if run_get_lines:
self.get_lines()
def _get_aligners(
self, widget: Widget, borders: tuple[str, str]
) -> tuple[Callable[[str], str], int]:
"""Gets an aligning method and position offset.
Args:
widget: The widget to align.
borders: The left and right borders to put the widget within.
Returns:
A tuple of a method that, when called with a line, will return that line
centered using the passed in widget's parent_align and width, as well as
the horizontal offset resulting from the widget being aligned.
"""
left, right = borders
char = self._get_style("fill")(" ")
def _align_left(text: str) -> str:
"""Align line to the left"""
padding = self.width - real_length(left + right) - real_length(text)
return left + text + padding * char + right
def _align_center(text: str) -> str:
"""Align line to the center"""
total = self.width - real_length(left + right) - real_length(text)
padding, offset = divmod(total, 2)
return left + (padding + offset) * char + text + padding * char + right
def _align_right(text: str) -> str:
"""Align line to the right"""
padding = self.width - real_length(left + right) - real_length(text)
return left + padding * char + text + right
if widget.parent_align == HorizontalAlignment.CENTER:
total = self.width - real_length(left + right) - widget.width
padding, offset = divmod(total, 2)
return _align_center, real_length(left) + padding + offset
if widget.parent_align == HorizontalAlignment.RIGHT:
return _align_right, self.width - real_length(left) - widget.width
# Default to left-aligned
return _align_left, real_length(left)
def _update_width(self, widget: Widget) -> None:
"""Updates the width of widget or self.
This method respects widget.size_policy.
Args:
widget: The widget to update/base updates on.
"""
available = (
self.width - self.sidelength - (0 if isinstance(widget, Container) else 1)
)
if widget.size_policy == SizePolicy.FILL:
widget.width = available
return
if widget.size_policy == SizePolicy.RELATIVE:
widget.width = widget.relative_width * available
return
if widget.width > available:
if widget.size_policy == SizePolicy.STATIC:
raise WidthExceededError(
f"Widget {widget}'s static width of {widget.width}"
+ f" exceeds its parent's available width {available}."
""
)
widget.width = available
def _apply_vertalign(
self, lines: list[str], diff: int, padder: str
) -> tuple[int, list[str]]:
"""Insert padder line into lines diff times, depending on self.vertical_align.
Args:
lines: The list of lines to align.
diff: The available height.
padder: The line to use to pad.
Returns:
A tuple containing the vertical offset as well as the padded list of lines.
Raises:
NotImplementedError: The given vertical alignment is not implemented.
"""
if self.vertical_align == VerticalAlignment.BOTTOM:
for _ in range(diff):
lines.insert(0, padder)
return diff, lines
if self.vertical_align == VerticalAlignment.TOP:
for _ in range(diff):
lines.append(padder)
return 0, lines
if self.vertical_align == VerticalAlignment.CENTER:
top, extra = divmod(diff, 2)
bottom = top + extra
for _ in range(top):
lines.insert(0, padder)
for _ in range(bottom):
lines.append(padder)
return top, lines
raise NotImplementedError(
f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}."
)
def get_lines(self) -> list[str]:
"""Gets all lines by spacing out inner widgets.
This method reflects & applies both width settings, as well as
the `parent_align` field.
Returns:
A list of all lines that represent this Container.
"""
def _get_border(left: str, char: str, right: str) -> str:
"""Gets a top or bottom border.
Args:
left: Left corner character.
char: Border character filling between left & right.
right: Right corner character.
Returns:
The border line.
"""
offset = real_length(left + right)
return left + char * (self.width - offset) + right
lines = []
style = self._get_style("border")
borders = [style(char) for char in self._get_char("border")]
style = self._get_style("corner")
corners = [style(char) for char in self._get_char("corner")]
has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0)
align = lambda item: item
for widget in self._widgets:
align, offset = self._get_aligners(widget, (borders[0], borders[2]))
self._update_width(widget)
widget.pos = (
self.pos[0] + offset,
self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0),
)
widget_lines = []
for line in widget.get_lines():
widget_lines.append(align(line))
lines.extend(widget_lines)
vertical_offset, lines = self._apply_vertalign(
lines, self.height - len(lines) - sum(has_top_bottom), align("")
)
for widget in self._widgets:
widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset)
# TODO: This is wasteful.
widget.get_lines()
if has_top_bottom[0]:
lines.insert(0, _get_border(corners[0], borders[1], corners[1]))
if has_top_bottom[1]:
lines.append(_get_border(corners[3], borders[3], corners[2]))
self.height = len(lines)
return lines
def set_widgets(self, new: list[Widget]) -> None:
"""Sets new list in place of self._widgets.
Args:
new: The new widget list.
"""
self._widgets = []
for widget in new:
self._add_widget(widget)
def serialize(self) -> dict[str, Any]:
"""Serializes this Container, adding in serializations of all widgets.
See `pytermgui.widgets.base.Widget.serialize` for more info.
Returns:
The dictionary containing all serialized data.
"""
out = super().serialize()
out["_widgets"] = []
for widget in self._widgets:
out["_widgets"].append(widget.serialize())
return out
def pop(self, index: int = -1) -> Widget:
"""Pops widget from self._widgets.
Analogous to self._widgets.pop(index).
Args:
index: The index to operate on.
Returns:
The widget that was popped off the list.
"""
return self._widgets.pop(index)
def remove(self, other: Widget) -> None:
"""Remove widget from self._widgets
Analogous to self._widgets.remove(other).
Args:
widget: The widget to remove.
"""
return self._widgets.remove(other)
def set_recursive_depth(self, value: int) -> None:
"""Set depth for this Container and all its children.
All inner widgets will receive value+1 as their new depth.
Args:
value: The new depth to use as the base depth.
"""
self.depth = value
for widget in self._widgets:
if isinstance(widget, Container):
widget.set_recursive_depth(value + 1)
else:
widget.depth = value
def select(self, index: int | None = None) -> None:
"""Selects inner subwidget.
Args:
index: The index to select.
Raises:
IndexError: The index provided was beyond len(self.selectables).
"""
# Unselect all sub-elements
for other in self._widgets:
if other.selectables_length > 0:
other.select(None)
if index is not None:
if index >= len(self.selectables) is None:
raise IndexError("Container selection index out of range")
widget, inner_index = self.selectables[index]
widget.select(inner_index)
self.selected_index = index
def center(
self, where: CenteringPolicy | None = None, store: bool = True
) -> Container:
"""Centers this object to the given axis.
Args:
where: A CenteringPolicy describing the place to center to
store: When set, this centering will be reapplied during every
print, as well as when calling this method with no arguments.
Returns:
This Container.
"""
# Refresh in case changes happened
self.get_lines()
if where is None:
# See `enums.py` for explanation about this ignore.
where = CenteringPolicy.get_default() # type: ignore
centerx = centery = where is CenteringPolicy.ALL
centerx |= where is CenteringPolicy.HORIZONTAL
centery |= where is CenteringPolicy.VERTICAL
pos = list(self.pos)
if centerx:
pos[0] = (terminal.width - self.width + 2) // 2
if centery:
pos[1] = (terminal.height - self.height + 2) // 2
self.pos = (pos[0], pos[1])
if store:
self._centered_axis = where
self._prev_screen = terminal.size
return self
def handle_mouse(self, event: MouseEvent) -> bool:
"""Applies a mouse event on all children.
Args:
event: The event to handle
Returns:
A boolean showing whether the event was handled.
"""
if event.action is MouseAction.RELEASE:
# Force RELEASE event to be sent
if self._drag_target is not None:
self._drag_target.handle_mouse(
MouseEvent(MouseAction.RELEASE, event.position)
)
self._drag_target = None
if self._drag_target is not None:
return self._drag_target.handle_mouse(event)
selectables_index = 0
for widget in self._widgets:
if widget.contains(event.position):
handled = widget.handle_mouse(event)
if widget.selected_index is not None:
selectables_index += widget.selected_index
if event.action is MouseAction.LEFT_CLICK:
self._drag_target = widget
if handled:
self.select(selectables_index)
return handled
if widget.is_selectable:
selectables_index += widget.selectables_length
return False
def handle_key(self, key: str) -> bool:
"""Handles a keypress, returns its success.
Args:
key: A key str.
Returns:
A boolean showing whether the key was handled.
"""
def _is_nav(key: str) -> bool:
"""Determine if a key is in the navigation sets"""
return key in self.keys["next"] | self.keys["previous"]
if self.selected is not None and self.selected.handle_key(key):
return True
# Only use navigation when there is more than one selectable
if self.selectables_length > 1 and _is_nav(key):
handled = False
if self.selected_index is None:
self.select(0)
assert isinstance(self.selected_index, int)
if key in self.keys["previous"]:
# No more selectables left, user wants to exit Container
# upwards.
if self.selected_index == 0:
return False
self.select(self.selected_index - 1)
handled = True
elif key in self.keys["next"]:
# Stop selection at last element, return as unhandled
new = self.selected_index + 1
if new == len(self.selectables):
return False
self.select(new)
handled = True
if handled:
return True
if key == keys.ENTER and self.selected is not None:
if self.selected.selected_index is not None:
self.selected.handle_key(key)
return True
return False
def wipe(self) -> None:
"""Wipes the characters occupied by the object"""
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(real_length(line) * " ")
def print(self) -> None:
"""Prints this Container.
If the screen size has changed since last `print` call, the object
will be centered based on its `_centered_axis`.
"""
if not terminal.size == self._prev_screen:
clear()
self.center(self._centered_axis)
self._prev_screen = terminal.size
if self.allow_fullscreen:
self.pos = terminal.origin
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(line)
self._has_printed = True
def debug(self) -> str:
"""Returns a string with identifiable information on this widget.
Returns:
A str in the form of a class construction. This string is in a form that
__could have been__ used to create this Container.
"""
out = "Container("
for widget in self._widgets:
out += widget.debug() + ", "
out = out.strip(", ")
out += ", **attrs)"
return out
class Splitter(Container):
"""A widget that displays other widgets, stacked horizontally."""
chars: dict[str, list[str] | str] = {"separator": " | "}
styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND}
keys = {
"previous": {keys.LEFT, "h", keys.CTRL_B},
"next": {keys.RIGHT, "l", keys.CTRL_F},
}
parent_align = HorizontalAlignment.RIGHT
def _align(
self, alignment: HorizontalAlignment, target_width: int, line: str
) -> tuple[int, str]:
"""Align a line
r/wordavalanches"""
available = target_width - real_length(line)
fill_style = self._get_style("fill")
char = fill_style(" ")
line = fill_style(line)
if alignment == HorizontalAlignment.CENTER:
padding, offset = divmod(available, 2)
return padding, padding * char + line + (padding + offset) * char
if alignment == HorizontalAlignment.RIGHT:
return available, available * char + line
return 0, line + available * char
def get_lines(self) -> list[str]:
"""Join all widgets horizontally."""
# An error will be raised if `separator` is not the correct type (str).
separator = self._get_style("separator")(self._get_char("separator")) # type: ignore
separator_length = real_length(separator)
target_width, error = divmod(
self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets)
)
vertical_lines = []
total_offset = 0
for widget in self._widgets:
inner = []
if widget.size_policy is SizePolicy.STATIC:
target_width += target_width - widget.width
width = target_width
else:
widget.width = target_width + error
width = widget.width
error = 0
aligned: str | None = None
for line in widget.get_lines():
# See `enums.py` for information about this ignore
padding, aligned = self._align(
cast(HorizontalAlignment, widget.parent_align), width, line
)
inner.append(aligned)
widget.pos = (
self.pos[0] + padding + total_offset,
self.pos[1] + (1 if type(widget).__name__ == "Container" else 0),
)
if aligned is not None:
total_offset += real_length(inner[-1]) + separator_length
vertical_lines.append(inner)
lines = []
for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width):
lines.append((reset() + separator).join(horizontal))
return lines
def debug(self) -> str:
"""Return identifiable information"""
return super().debug().replace("Container", "Splitter", 1)
| bczsalba__pytermgui |
54 | 54-67-36 | inproject | RESIZE | [
"fill",
"height",
"margins",
"origin",
"RESIZE",
"size",
"subscribe",
"width",
"_alt_sigwinch",
"_call_listener",
"_get_size",
"_listeners",
"_update_size",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """The module containing all of the layout-related widgets."""
# These widgets have more than the 7 allowed instance attributes.
# pylint: disable=too-many-instance-attributes
from __future__ import annotations
from itertools import zip_longest
from typing import Any, Callable, Iterator, cast
from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal
from ..context_managers import cursor_at
from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment
from ..exceptions import WidthExceededError
from ..helpers import real_length
from ..input import keys
from . import boxes
from . import styles as w_styles
from .base import Widget
class Container(Widget):
"""A widget that displays other widgets, stacked vertically."""
chars: dict[str, w_styles.CharType] = {
"border": ["| ", "-", " |", "-"],
"corner": [""] * 4,
}
styles = {
"border": w_styles.MARKUP,
"corner": w_styles.MARKUP,
"fill": w_styles.BACKGROUND,
}
keys = {
"next": {keys.DOWN, keys.CTRL_N, "j"},
"previous": {keys.UP, keys.CTRL_P, "k"},
}
serialized = Widget.serialized + ["_centered_axis"]
vertical_align = VerticalAlignment.CENTER
allow_fullscreen = True
# TODO: Add `WidgetConvertible`? type instead of Any
def __init__(self, *widgets: Any, **attrs: Any) -> None:
"""Initialize Container data"""
super().__init__(**attrs)
# TODO: This is just a band-aid.
if "width" not in attrs:
self.width = 40
self._widgets: list[Widget] = []
self._centered_axis: CenteringPolicy | None = None
self._prev_screen: tuple[int, int] = (0, 0)
self._has_printed = False
self.styles = type(self).styles.copy()
self.chars = type(self).chars.copy()
for widget in widgets:
self._add_widget(widget)
self._drag_target: Widget | None = None
terminal.subscribe(terminal. | , lambda *_: self.center(self._centered_axis))
@property
def sidelength(self) -> int:
"""Gets the length of left and right borders combined.
Returns:
An integer equal to the `pytermgui.helpers.real_length` of the concatenation of
the left and right borders of this widget, both with their respective styles
applied.
"""
chars = self._get_char("border")
style = self._get_style("border")
if not isinstance(chars, list):
return 0
left_border, _, right_border, _ = chars
return real_length(style(left_border) + style(right_border))
@property
def selectables(self) -> list[tuple[Widget, int]]:
"""Gets all selectable widgets and their inner indices.
This is used in order to have a constant reference to all selectable indices within this
widget.
Returns:
A list of tuples containing a widget and an integer each. For each widget that is
withing this one, it is added to this list as many times as it has selectables. Each
of the integers correspond to a selectable_index within the widget.
For example, a Container with a Button, InputField and an inner Container containing
3 selectables might return something like this:
```
[
(Button(...), 0),
(InputField(...), 0),
(Container(...), 0),
(Container(...), 1),
(Container(...), 2),
]
```
"""
_selectables: list[tuple[Widget, int]] = []
for widget in self._widgets:
if not widget.is_selectable:
continue
for i, (inner, _) in enumerate(widget.selectables):
_selectables.append((inner, i))
return _selectables
@property
def selectables_length(self) -> int:
"""Gets the length of the selectables list.
Returns:
An integer equal to the length of `self.selectables`.
"""
return len(self.selectables)
@property
def selected(self) -> Widget | None:
"""Returns the currently selected object
Returns:
The currently selected widget if selected_index is not None,
otherwise None.
"""
# TODO: Add deeper selection
if self.selected_index is None:
return None
if self.selected_index >= len(self.selectables):
return None
return self.selectables[self.selected_index][0]
@property
def box(self) -> boxes.Box:
"""Returns current box setting
Returns:
The currently set box instance.
"""
return self._box
@box.setter
def box(self, new: str | boxes.Box) -> None:
"""Applies a new box.
Args:
new: Either a `pytermgui.boxes.Box` instance or a string
analogous to one of the default box names.
"""
if isinstance(new, str):
from_module = vars(boxes).get(new)
if from_module is None:
raise ValueError(f"Unknown box type {new}.")
new = from_module
assert isinstance(new, boxes.Box)
self._box = new
new.set_chars_of(self)
def __iadd__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self._add_widget(other)
return self
def __add__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
This method is analogous to `Container.__iadd__`.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self.__iadd__(other)
return self
def __iter__(self) -> Iterator[Widget]:
"""Gets an iterator of self._widgets.
Yields:
The next widget.
"""
for widget in self._widgets:
yield widget
def __len__(self) -> int:
"""Gets the length of the widgets list.
Returns:
An integer describing len(self._widgets).
"""
return len(self._widgets)
def __getitem__(self, sli: int | slice) -> Widget | list[Widget]:
"""Gets an item from self._widgets.
Args:
sli: Slice of the list.
Returns:
The slice in the list.
"""
return self._widgets[sli]
def __setitem__(self, index: int, value: Any) -> None:
"""Sets an item in self._widgets.
Args:
index: The index to be set.
value: The new widget at this index.
"""
self._widgets[index] = value
def __contains__(self, other: object) -> bool:
"""Determines if self._widgets contains other widget.
Args:
other: Any widget-like.
Returns:
A boolean describing whether `other` is in `self.widgets`
"""
return other in self._widgets
def _add_widget(self, other: object, run_get_lines: bool = True) -> None:
"""Adds other to this widget.
Args:
other: Any widget-like object.
run_get_lines: Boolean controlling whether the self.get_lines is ran.
"""
if not isinstance(other, Widget):
to_widget = Widget.from_data(other)
if to_widget is None:
raise ValueError(
f"Could not convert {other} of type {type(other)} to a Widget!"
)
other = to_widget
# This is safe to do, as it would've raised an exception above already
assert isinstance(other, Widget)
self._widgets.append(other)
if isinstance(other, Container):
other.set_recursive_depth(self.depth + 2)
else:
other.depth = self.depth + 1
other.get_lines()
other.parent = self
if run_get_lines:
self.get_lines()
def _get_aligners(
self, widget: Widget, borders: tuple[str, str]
) -> tuple[Callable[[str], str], int]:
"""Gets an aligning method and position offset.
Args:
widget: The widget to align.
borders: The left and right borders to put the widget within.
Returns:
A tuple of a method that, when called with a line, will return that line
centered using the passed in widget's parent_align and width, as well as
the horizontal offset resulting from the widget being aligned.
"""
left, right = borders
char = self._get_style("fill")(" ")
def _align_left(text: str) -> str:
"""Align line to the left"""
padding = self.width - real_length(left + right) - real_length(text)
return left + text + padding * char + right
def _align_center(text: str) -> str:
"""Align line to the center"""
total = self.width - real_length(left + right) - real_length(text)
padding, offset = divmod(total, 2)
return left + (padding + offset) * char + text + padding * char + right
def _align_right(text: str) -> str:
"""Align line to the right"""
padding = self.width - real_length(left + right) - real_length(text)
return left + padding * char + text + right
if widget.parent_align == HorizontalAlignment.CENTER:
total = self.width - real_length(left + right) - widget.width
padding, offset = divmod(total, 2)
return _align_center, real_length(left) + padding + offset
if widget.parent_align == HorizontalAlignment.RIGHT:
return _align_right, self.width - real_length(left) - widget.width
# Default to left-aligned
return _align_left, real_length(left)
def _update_width(self, widget: Widget) -> None:
"""Updates the width of widget or self.
This method respects widget.size_policy.
Args:
widget: The widget to update/base updates on.
"""
available = (
self.width - self.sidelength - (0 if isinstance(widget, Container) else 1)
)
if widget.size_policy == SizePolicy.FILL:
widget.width = available
return
if widget.size_policy == SizePolicy.RELATIVE:
widget.width = widget.relative_width * available
return
if widget.width > available:
if widget.size_policy == SizePolicy.STATIC:
raise WidthExceededError(
f"Widget {widget}'s static width of {widget.width}"
+ f" exceeds its parent's available width {available}."
""
)
widget.width = available
def _apply_vertalign(
self, lines: list[str], diff: int, padder: str
) -> tuple[int, list[str]]:
"""Insert padder line into lines diff times, depending on self.vertical_align.
Args:
lines: The list of lines to align.
diff: The available height.
padder: The line to use to pad.
Returns:
A tuple containing the vertical offset as well as the padded list of lines.
Raises:
NotImplementedError: The given vertical alignment is not implemented.
"""
if self.vertical_align == VerticalAlignment.BOTTOM:
for _ in range(diff):
lines.insert(0, padder)
return diff, lines
if self.vertical_align == VerticalAlignment.TOP:
for _ in range(diff):
lines.append(padder)
return 0, lines
if self.vertical_align == VerticalAlignment.CENTER:
top, extra = divmod(diff, 2)
bottom = top + extra
for _ in range(top):
lines.insert(0, padder)
for _ in range(bottom):
lines.append(padder)
return top, lines
raise NotImplementedError(
f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}."
)
def get_lines(self) -> list[str]:
"""Gets all lines by spacing out inner widgets.
This method reflects & applies both width settings, as well as
the `parent_align` field.
Returns:
A list of all lines that represent this Container.
"""
def _get_border(left: str, char: str, right: str) -> str:
"""Gets a top or bottom border.
Args:
left: Left corner character.
char: Border character filling between left & right.
right: Right corner character.
Returns:
The border line.
"""
offset = real_length(left + right)
return left + char * (self.width - offset) + right
lines = []
style = self._get_style("border")
borders = [style(char) for char in self._get_char("border")]
style = self._get_style("corner")
corners = [style(char) for char in self._get_char("corner")]
has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0)
align = lambda item: item
for widget in self._widgets:
align, offset = self._get_aligners(widget, (borders[0], borders[2]))
self._update_width(widget)
widget.pos = (
self.pos[0] + offset,
self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0),
)
widget_lines = []
for line in widget.get_lines():
widget_lines.append(align(line))
lines.extend(widget_lines)
vertical_offset, lines = self._apply_vertalign(
lines, self.height - len(lines) - sum(has_top_bottom), align("")
)
for widget in self._widgets:
widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset)
# TODO: This is wasteful.
widget.get_lines()
if has_top_bottom[0]:
lines.insert(0, _get_border(corners[0], borders[1], corners[1]))
if has_top_bottom[1]:
lines.append(_get_border(corners[3], borders[3], corners[2]))
self.height = len(lines)
return lines
def set_widgets(self, new: list[Widget]) -> None:
"""Sets new list in place of self._widgets.
Args:
new: The new widget list.
"""
self._widgets = []
for widget in new:
self._add_widget(widget)
def serialize(self) -> dict[str, Any]:
"""Serializes this Container, adding in serializations of all widgets.
See `pytermgui.widgets.base.Widget.serialize` for more info.
Returns:
The dictionary containing all serialized data.
"""
out = super().serialize()
out["_widgets"] = []
for widget in self._widgets:
out["_widgets"].append(widget.serialize())
return out
def pop(self, index: int = -1) -> Widget:
"""Pops widget from self._widgets.
Analogous to self._widgets.pop(index).
Args:
index: The index to operate on.
Returns:
The widget that was popped off the list.
"""
return self._widgets.pop(index)
def remove(self, other: Widget) -> None:
"""Remove widget from self._widgets
Analogous to self._widgets.remove(other).
Args:
widget: The widget to remove.
"""
return self._widgets.remove(other)
def set_recursive_depth(self, value: int) -> None:
"""Set depth for this Container and all its children.
All inner widgets will receive value+1 as their new depth.
Args:
value: The new depth to use as the base depth.
"""
self.depth = value
for widget in self._widgets:
if isinstance(widget, Container):
widget.set_recursive_depth(value + 1)
else:
widget.depth = value
def select(self, index: int | None = None) -> None:
"""Selects inner subwidget.
Args:
index: The index to select.
Raises:
IndexError: The index provided was beyond len(self.selectables).
"""
# Unselect all sub-elements
for other in self._widgets:
if other.selectables_length > 0:
other.select(None)
if index is not None:
if index >= len(self.selectables) is None:
raise IndexError("Container selection index out of range")
widget, inner_index = self.selectables[index]
widget.select(inner_index)
self.selected_index = index
def center(
self, where: CenteringPolicy | None = None, store: bool = True
) -> Container:
"""Centers this object to the given axis.
Args:
where: A CenteringPolicy describing the place to center to
store: When set, this centering will be reapplied during every
print, as well as when calling this method with no arguments.
Returns:
This Container.
"""
# Refresh in case changes happened
self.get_lines()
if where is None:
# See `enums.py` for explanation about this ignore.
where = CenteringPolicy.get_default() # type: ignore
centerx = centery = where is CenteringPolicy.ALL
centerx |= where is CenteringPolicy.HORIZONTAL
centery |= where is CenteringPolicy.VERTICAL
pos = list(self.pos)
if centerx:
pos[0] = (terminal.width - self.width + 2) // 2
if centery:
pos[1] = (terminal.height - self.height + 2) // 2
self.pos = (pos[0], pos[1])
if store:
self._centered_axis = where
self._prev_screen = terminal.size
return self
def handle_mouse(self, event: MouseEvent) -> bool:
"""Applies a mouse event on all children.
Args:
event: The event to handle
Returns:
A boolean showing whether the event was handled.
"""
if event.action is MouseAction.RELEASE:
# Force RELEASE event to be sent
if self._drag_target is not None:
self._drag_target.handle_mouse(
MouseEvent(MouseAction.RELEASE, event.position)
)
self._drag_target = None
if self._drag_target is not None:
return self._drag_target.handle_mouse(event)
selectables_index = 0
for widget in self._widgets:
if widget.contains(event.position):
handled = widget.handle_mouse(event)
if widget.selected_index is not None:
selectables_index += widget.selected_index
if event.action is MouseAction.LEFT_CLICK:
self._drag_target = widget
if handled:
self.select(selectables_index)
return handled
if widget.is_selectable:
selectables_index += widget.selectables_length
return False
def handle_key(self, key: str) -> bool:
"""Handles a keypress, returns its success.
Args:
key: A key str.
Returns:
A boolean showing whether the key was handled.
"""
def _is_nav(key: str) -> bool:
"""Determine if a key is in the navigation sets"""
return key in self.keys["next"] | self.keys["previous"]
if self.selected is not None and self.selected.handle_key(key):
return True
# Only use navigation when there is more than one selectable
if self.selectables_length > 1 and _is_nav(key):
handled = False
if self.selected_index is None:
self.select(0)
assert isinstance(self.selected_index, int)
if key in self.keys["previous"]:
# No more selectables left, user wants to exit Container
# upwards.
if self.selected_index == 0:
return False
self.select(self.selected_index - 1)
handled = True
elif key in self.keys["next"]:
# Stop selection at last element, return as unhandled
new = self.selected_index + 1
if new == len(self.selectables):
return False
self.select(new)
handled = True
if handled:
return True
if key == keys.ENTER and self.selected is not None:
if self.selected.selected_index is not None:
self.selected.handle_key(key)
return True
return False
def wipe(self) -> None:
"""Wipes the characters occupied by the object"""
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(real_length(line) * " ")
def print(self) -> None:
"""Prints this Container.
If the screen size has changed since last `print` call, the object
will be centered based on its `_centered_axis`.
"""
if not terminal.size == self._prev_screen:
clear()
self.center(self._centered_axis)
self._prev_screen = terminal.size
if self.allow_fullscreen:
self.pos = terminal.origin
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(line)
self._has_printed = True
def debug(self) -> str:
"""Returns a string with identifiable information on this widget.
Returns:
A str in the form of a class construction. This string is in a form that
__could have been__ used to create this Container.
"""
out = "Container("
for widget in self._widgets:
out += widget.debug() + ", "
out = out.strip(", ")
out += ", **attrs)"
return out
class Splitter(Container):
"""A widget that displays other widgets, stacked horizontally."""
chars: dict[str, list[str] | str] = {"separator": " | "}
styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND}
keys = {
"previous": {keys.LEFT, "h", keys.CTRL_B},
"next": {keys.RIGHT, "l", keys.CTRL_F},
}
parent_align = HorizontalAlignment.RIGHT
def _align(
self, alignment: HorizontalAlignment, target_width: int, line: str
) -> tuple[int, str]:
"""Align a line
r/wordavalanches"""
available = target_width - real_length(line)
fill_style = self._get_style("fill")
char = fill_style(" ")
line = fill_style(line)
if alignment == HorizontalAlignment.CENTER:
padding, offset = divmod(available, 2)
return padding, padding * char + line + (padding + offset) * char
if alignment == HorizontalAlignment.RIGHT:
return available, available * char + line
return 0, line + available * char
def get_lines(self) -> list[str]:
"""Join all widgets horizontally."""
# An error will be raised if `separator` is not the correct type (str).
separator = self._get_style("separator")(self._get_char("separator")) # type: ignore
separator_length = real_length(separator)
target_width, error = divmod(
self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets)
)
vertical_lines = []
total_offset = 0
for widget in self._widgets:
inner = []
if widget.size_policy is SizePolicy.STATIC:
target_width += target_width - widget.width
width = target_width
else:
widget.width = target_width + error
width = widget.width
error = 0
aligned: str | None = None
for line in widget.get_lines():
# See `enums.py` for information about this ignore
padding, aligned = self._align(
cast(HorizontalAlignment, widget.parent_align), width, line
)
inner.append(aligned)
widget.pos = (
self.pos[0] + padding + total_offset,
self.pos[1] + (1 if type(widget).__name__ == "Container" else 0),
)
if aligned is not None:
total_offset += real_length(inner[-1]) + separator_length
vertical_lines.append(inner)
lines = []
for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width):
lines.append((reset() + separator).join(horizontal))
return lines
def debug(self) -> str:
"""Return identifiable information"""
return super().debug().replace("Container", "Splitter", 1)
| bczsalba__pytermgui |
54 | 54-67-60 | inproject | center | [
"allow_fullscreen",
"bind",
"bindings",
"box",
"center",
"chars",
"contains",
"copy",
"debug",
"depth",
"execute_binding",
"get_lines",
"handle_key",
"handle_mouse",
"height",
"id",
"is_bindable",
"is_selectable",
"keys",
"parent",
"parent_align",
"pop",
"pos",
"print",
"remove",
"select",
"selectables",
"selectables_length",
"selected",
"selected_index",
"serialize",
"serialized",
"set_char",
"set_recursive_depth",
"set_style",
"set_widgets",
"sidelength",
"size_policy",
"static_width",
"styles",
"vertical_align",
"width",
"wipe",
"_add_widget",
"_apply_vertalign",
"_bindings",
"_box",
"_centered_axis",
"_drag_target",
"_get_aligners",
"_get_char",
"_get_style",
"_has_printed",
"_id",
"_id_manager",
"_prev_screen",
"_selectables_length",
"_serialized_fields",
"_update_width",
"_widgets",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__getitem__",
"__hash__",
"__iadd__",
"__init__",
"__init_subclass__",
"__iter__",
"__len__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__setitem__",
"__sizeof__",
"__slots__",
"__str__"
] | """The module containing all of the layout-related widgets."""
# These widgets have more than the 7 allowed instance attributes.
# pylint: disable=too-many-instance-attributes
from __future__ import annotations
from itertools import zip_longest
from typing import Any, Callable, Iterator, cast
from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal
from ..context_managers import cursor_at
from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment
from ..exceptions import WidthExceededError
from ..helpers import real_length
from ..input import keys
from . import boxes
from . import styles as w_styles
from .base import Widget
class Container(Widget):
"""A widget that displays other widgets, stacked vertically."""
chars: dict[str, w_styles.CharType] = {
"border": ["| ", "-", " |", "-"],
"corner": [""] * 4,
}
styles = {
"border": w_styles.MARKUP,
"corner": w_styles.MARKUP,
"fill": w_styles.BACKGROUND,
}
keys = {
"next": {keys.DOWN, keys.CTRL_N, "j"},
"previous": {keys.UP, keys.CTRL_P, "k"},
}
serialized = Widget.serialized + ["_centered_axis"]
vertical_align = VerticalAlignment.CENTER
allow_fullscreen = True
# TODO: Add `WidgetConvertible`? type instead of Any
def __init__(self, *widgets: Any, **attrs: Any) -> None:
"""Initialize Container data"""
super().__init__(**attrs)
# TODO: This is just a band-aid.
if "width" not in attrs:
self.width = 40
self._widgets: list[Widget] = []
self._centered_axis: CenteringPolicy | None = None
self._prev_screen: tuple[int, int] = (0, 0)
self._has_printed = False
self.styles = type(self).styles.copy()
self.chars = type(self).chars.copy()
for widget in widgets:
self._add_widget(widget)
self._drag_target: Widget | None = None
terminal.subscribe(terminal.RESIZE, lambda *_: self. | (self._centered_axis))
@property
def sidelength(self) -> int:
"""Gets the length of left and right borders combined.
Returns:
An integer equal to the `pytermgui.helpers.real_length` of the concatenation of
the left and right borders of this widget, both with their respective styles
applied.
"""
chars = self._get_char("border")
style = self._get_style("border")
if not isinstance(chars, list):
return 0
left_border, _, right_border, _ = chars
return real_length(style(left_border) + style(right_border))
@property
def selectables(self) -> list[tuple[Widget, int]]:
"""Gets all selectable widgets and their inner indices.
This is used in order to have a constant reference to all selectable indices within this
widget.
Returns:
A list of tuples containing a widget and an integer each. For each widget that is
withing this one, it is added to this list as many times as it has selectables. Each
of the integers correspond to a selectable_index within the widget.
For example, a Container with a Button, InputField and an inner Container containing
3 selectables might return something like this:
```
[
(Button(...), 0),
(InputField(...), 0),
(Container(...), 0),
(Container(...), 1),
(Container(...), 2),
]
```
"""
_selectables: list[tuple[Widget, int]] = []
for widget in self._widgets:
if not widget.is_selectable:
continue
for i, (inner, _) in enumerate(widget.selectables):
_selectables.append((inner, i))
return _selectables
@property
def selectables_length(self) -> int:
"""Gets the length of the selectables list.
Returns:
An integer equal to the length of `self.selectables`.
"""
return len(self.selectables)
@property
def selected(self) -> Widget | None:
"""Returns the currently selected object
Returns:
The currently selected widget if selected_index is not None,
otherwise None.
"""
# TODO: Add deeper selection
if self.selected_index is None:
return None
if self.selected_index >= len(self.selectables):
return None
return self.selectables[self.selected_index][0]
@property
def box(self) -> boxes.Box:
"""Returns current box setting
Returns:
The currently set box instance.
"""
return self._box
@box.setter
def box(self, new: str | boxes.Box) -> None:
"""Applies a new box.
Args:
new: Either a `pytermgui.boxes.Box` instance or a string
analogous to one of the default box names.
"""
if isinstance(new, str):
from_module = vars(boxes).get(new)
if from_module is None:
raise ValueError(f"Unknown box type {new}.")
new = from_module
assert isinstance(new, boxes.Box)
self._box = new
new.set_chars_of(self)
def __iadd__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self._add_widget(other)
return self
def __add__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
This method is analogous to `Container.__iadd__`.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self.__iadd__(other)
return self
def __iter__(self) -> Iterator[Widget]:
"""Gets an iterator of self._widgets.
Yields:
The next widget.
"""
for widget in self._widgets:
yield widget
def __len__(self) -> int:
"""Gets the length of the widgets list.
Returns:
An integer describing len(self._widgets).
"""
return len(self._widgets)
def __getitem__(self, sli: int | slice) -> Widget | list[Widget]:
"""Gets an item from self._widgets.
Args:
sli: Slice of the list.
Returns:
The slice in the list.
"""
return self._widgets[sli]
def __setitem__(self, index: int, value: Any) -> None:
"""Sets an item in self._widgets.
Args:
index: The index to be set.
value: The new widget at this index.
"""
self._widgets[index] = value
def __contains__(self, other: object) -> bool:
"""Determines if self._widgets contains other widget.
Args:
other: Any widget-like.
Returns:
A boolean describing whether `other` is in `self.widgets`
"""
return other in self._widgets
def _add_widget(self, other: object, run_get_lines: bool = True) -> None:
"""Adds other to this widget.
Args:
other: Any widget-like object.
run_get_lines: Boolean controlling whether the self.get_lines is ran.
"""
if not isinstance(other, Widget):
to_widget = Widget.from_data(other)
if to_widget is None:
raise ValueError(
f"Could not convert {other} of type {type(other)} to a Widget!"
)
other = to_widget
# This is safe to do, as it would've raised an exception above already
assert isinstance(other, Widget)
self._widgets.append(other)
if isinstance(other, Container):
other.set_recursive_depth(self.depth + 2)
else:
other.depth = self.depth + 1
other.get_lines()
other.parent = self
if run_get_lines:
self.get_lines()
def _get_aligners(
self, widget: Widget, borders: tuple[str, str]
) -> tuple[Callable[[str], str], int]:
"""Gets an aligning method and position offset.
Args:
widget: The widget to align.
borders: The left and right borders to put the widget within.
Returns:
A tuple of a method that, when called with a line, will return that line
centered using the passed in widget's parent_align and width, as well as
the horizontal offset resulting from the widget being aligned.
"""
left, right = borders
char = self._get_style("fill")(" ")
def _align_left(text: str) -> str:
"""Align line to the left"""
padding = self.width - real_length(left + right) - real_length(text)
return left + text + padding * char + right
def _align_center(text: str) -> str:
"""Align line to the center"""
total = self.width - real_length(left + right) - real_length(text)
padding, offset = divmod(total, 2)
return left + (padding + offset) * char + text + padding * char + right
def _align_right(text: str) -> str:
"""Align line to the right"""
padding = self.width - real_length(left + right) - real_length(text)
return left + padding * char + text + right
if widget.parent_align == HorizontalAlignment.CENTER:
total = self.width - real_length(left + right) - widget.width
padding, offset = divmod(total, 2)
return _align_center, real_length(left) + padding + offset
if widget.parent_align == HorizontalAlignment.RIGHT:
return _align_right, self.width - real_length(left) - widget.width
# Default to left-aligned
return _align_left, real_length(left)
def _update_width(self, widget: Widget) -> None:
"""Updates the width of widget or self.
This method respects widget.size_policy.
Args:
widget: The widget to update/base updates on.
"""
available = (
self.width - self.sidelength - (0 if isinstance(widget, Container) else 1)
)
if widget.size_policy == SizePolicy.FILL:
widget.width = available
return
if widget.size_policy == SizePolicy.RELATIVE:
widget.width = widget.relative_width * available
return
if widget.width > available:
if widget.size_policy == SizePolicy.STATIC:
raise WidthExceededError(
f"Widget {widget}'s static width of {widget.width}"
+ f" exceeds its parent's available width {available}."
""
)
widget.width = available
def _apply_vertalign(
self, lines: list[str], diff: int, padder: str
) -> tuple[int, list[str]]:
"""Insert padder line into lines diff times, depending on self.vertical_align.
Args:
lines: The list of lines to align.
diff: The available height.
padder: The line to use to pad.
Returns:
A tuple containing the vertical offset as well as the padded list of lines.
Raises:
NotImplementedError: The given vertical alignment is not implemented.
"""
if self.vertical_align == VerticalAlignment.BOTTOM:
for _ in range(diff):
lines.insert(0, padder)
return diff, lines
if self.vertical_align == VerticalAlignment.TOP:
for _ in range(diff):
lines.append(padder)
return 0, lines
if self.vertical_align == VerticalAlignment.CENTER:
top, extra = divmod(diff, 2)
bottom = top + extra
for _ in range(top):
lines.insert(0, padder)
for _ in range(bottom):
lines.append(padder)
return top, lines
raise NotImplementedError(
f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}."
)
def get_lines(self) -> list[str]:
"""Gets all lines by spacing out inner widgets.
This method reflects & applies both width settings, as well as
the `parent_align` field.
Returns:
A list of all lines that represent this Container.
"""
def _get_border(left: str, char: str, right: str) -> str:
"""Gets a top or bottom border.
Args:
left: Left corner character.
char: Border character filling between left & right.
right: Right corner character.
Returns:
The border line.
"""
offset = real_length(left + right)
return left + char * (self.width - offset) + right
lines = []
style = self._get_style("border")
borders = [style(char) for char in self._get_char("border")]
style = self._get_style("corner")
corners = [style(char) for char in self._get_char("corner")]
has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0)
align = lambda item: item
for widget in self._widgets:
align, offset = self._get_aligners(widget, (borders[0], borders[2]))
self._update_width(widget)
widget.pos = (
self.pos[0] + offset,
self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0),
)
widget_lines = []
for line in widget.get_lines():
widget_lines.append(align(line))
lines.extend(widget_lines)
vertical_offset, lines = self._apply_vertalign(
lines, self.height - len(lines) - sum(has_top_bottom), align("")
)
for widget in self._widgets:
widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset)
# TODO: This is wasteful.
widget.get_lines()
if has_top_bottom[0]:
lines.insert(0, _get_border(corners[0], borders[1], corners[1]))
if has_top_bottom[1]:
lines.append(_get_border(corners[3], borders[3], corners[2]))
self.height = len(lines)
return lines
def set_widgets(self, new: list[Widget]) -> None:
"""Sets new list in place of self._widgets.
Args:
new: The new widget list.
"""
self._widgets = []
for widget in new:
self._add_widget(widget)
def serialize(self) -> dict[str, Any]:
"""Serializes this Container, adding in serializations of all widgets.
See `pytermgui.widgets.base.Widget.serialize` for more info.
Returns:
The dictionary containing all serialized data.
"""
out = super().serialize()
out["_widgets"] = []
for widget in self._widgets:
out["_widgets"].append(widget.serialize())
return out
def pop(self, index: int = -1) -> Widget:
"""Pops widget from self._widgets.
Analogous to self._widgets.pop(index).
Args:
index: The index to operate on.
Returns:
The widget that was popped off the list.
"""
return self._widgets.pop(index)
def remove(self, other: Widget) -> None:
"""Remove widget from self._widgets
Analogous to self._widgets.remove(other).
Args:
widget: The widget to remove.
"""
return self._widgets.remove(other)
def set_recursive_depth(self, value: int) -> None:
"""Set depth for this Container and all its children.
All inner widgets will receive value+1 as their new depth.
Args:
value: The new depth to use as the base depth.
"""
self.depth = value
for widget in self._widgets:
if isinstance(widget, Container):
widget.set_recursive_depth(value + 1)
else:
widget.depth = value
def select(self, index: int | None = None) -> None:
"""Selects inner subwidget.
Args:
index: The index to select.
Raises:
IndexError: The index provided was beyond len(self.selectables).
"""
# Unselect all sub-elements
for other in self._widgets:
if other.selectables_length > 0:
other.select(None)
if index is not None:
if index >= len(self.selectables) is None:
raise IndexError("Container selection index out of range")
widget, inner_index = self.selectables[index]
widget.select(inner_index)
self.selected_index = index
def center(
self, where: CenteringPolicy | None = None, store: bool = True
) -> Container:
"""Centers this object to the given axis.
Args:
where: A CenteringPolicy describing the place to center to
store: When set, this centering will be reapplied during every
print, as well as when calling this method with no arguments.
Returns:
This Container.
"""
# Refresh in case changes happened
self.get_lines()
if where is None:
# See `enums.py` for explanation about this ignore.
where = CenteringPolicy.get_default() # type: ignore
centerx = centery = where is CenteringPolicy.ALL
centerx |= where is CenteringPolicy.HORIZONTAL
centery |= where is CenteringPolicy.VERTICAL
pos = list(self.pos)
if centerx:
pos[0] = (terminal.width - self.width + 2) // 2
if centery:
pos[1] = (terminal.height - self.height + 2) // 2
self.pos = (pos[0], pos[1])
if store:
self._centered_axis = where
self._prev_screen = terminal.size
return self
def handle_mouse(self, event: MouseEvent) -> bool:
"""Applies a mouse event on all children.
Args:
event: The event to handle
Returns:
A boolean showing whether the event was handled.
"""
if event.action is MouseAction.RELEASE:
# Force RELEASE event to be sent
if self._drag_target is not None:
self._drag_target.handle_mouse(
MouseEvent(MouseAction.RELEASE, event.position)
)
self._drag_target = None
if self._drag_target is not None:
return self._drag_target.handle_mouse(event)
selectables_index = 0
for widget in self._widgets:
if widget.contains(event.position):
handled = widget.handle_mouse(event)
if widget.selected_index is not None:
selectables_index += widget.selected_index
if event.action is MouseAction.LEFT_CLICK:
self._drag_target = widget
if handled:
self.select(selectables_index)
return handled
if widget.is_selectable:
selectables_index += widget.selectables_length
return False
def handle_key(self, key: str) -> bool:
"""Handles a keypress, returns its success.
Args:
key: A key str.
Returns:
A boolean showing whether the key was handled.
"""
def _is_nav(key: str) -> bool:
"""Determine if a key is in the navigation sets"""
return key in self.keys["next"] | self.keys["previous"]
if self.selected is not None and self.selected.handle_key(key):
return True
# Only use navigation when there is more than one selectable
if self.selectables_length > 1 and _is_nav(key):
handled = False
if self.selected_index is None:
self.select(0)
assert isinstance(self.selected_index, int)
if key in self.keys["previous"]:
# No more selectables left, user wants to exit Container
# upwards.
if self.selected_index == 0:
return False
self.select(self.selected_index - 1)
handled = True
elif key in self.keys["next"]:
# Stop selection at last element, return as unhandled
new = self.selected_index + 1
if new == len(self.selectables):
return False
self.select(new)
handled = True
if handled:
return True
if key == keys.ENTER and self.selected is not None:
if self.selected.selected_index is not None:
self.selected.handle_key(key)
return True
return False
def wipe(self) -> None:
"""Wipes the characters occupied by the object"""
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(real_length(line) * " ")
def print(self) -> None:
"""Prints this Container.
If the screen size has changed since last `print` call, the object
will be centered based on its `_centered_axis`.
"""
if not terminal.size == self._prev_screen:
clear()
self.center(self._centered_axis)
self._prev_screen = terminal.size
if self.allow_fullscreen:
self.pos = terminal.origin
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(line)
self._has_printed = True
def debug(self) -> str:
"""Returns a string with identifiable information on this widget.
Returns:
A str in the form of a class construction. This string is in a form that
__could have been__ used to create this Container.
"""
out = "Container("
for widget in self._widgets:
out += widget.debug() + ", "
out = out.strip(", ")
out += ", **attrs)"
return out
class Splitter(Container):
"""A widget that displays other widgets, stacked horizontally."""
chars: dict[str, list[str] | str] = {"separator": " | "}
styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND}
keys = {
"previous": {keys.LEFT, "h", keys.CTRL_B},
"next": {keys.RIGHT, "l", keys.CTRL_F},
}
parent_align = HorizontalAlignment.RIGHT
def _align(
self, alignment: HorizontalAlignment, target_width: int, line: str
) -> tuple[int, str]:
"""Align a line
r/wordavalanches"""
available = target_width - real_length(line)
fill_style = self._get_style("fill")
char = fill_style(" ")
line = fill_style(line)
if alignment == HorizontalAlignment.CENTER:
padding, offset = divmod(available, 2)
return padding, padding * char + line + (padding + offset) * char
if alignment == HorizontalAlignment.RIGHT:
return available, available * char + line
return 0, line + available * char
def get_lines(self) -> list[str]:
"""Join all widgets horizontally."""
# An error will be raised if `separator` is not the correct type (str).
separator = self._get_style("separator")(self._get_char("separator")) # type: ignore
separator_length = real_length(separator)
target_width, error = divmod(
self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets)
)
vertical_lines = []
total_offset = 0
for widget in self._widgets:
inner = []
if widget.size_policy is SizePolicy.STATIC:
target_width += target_width - widget.width
width = target_width
else:
widget.width = target_width + error
width = widget.width
error = 0
aligned: str | None = None
for line in widget.get_lines():
# See `enums.py` for information about this ignore
padding, aligned = self._align(
cast(HorizontalAlignment, widget.parent_align), width, line
)
inner.append(aligned)
widget.pos = (
self.pos[0] + padding + total_offset,
self.pos[1] + (1 if type(widget).__name__ == "Container" else 0),
)
if aligned is not None:
total_offset += real_length(inner[-1]) + separator_length
vertical_lines.append(inner)
lines = []
for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width):
lines.append((reset() + separator).join(horizontal))
return lines
def debug(self) -> str:
"""Return identifiable information"""
return super().debug().replace("Container", "Splitter", 1)
| bczsalba__pytermgui |
54 | 54-67-72 | inproject | _centered_axis | [
"allow_fullscreen",
"bind",
"bindings",
"box",
"center",
"chars",
"contains",
"copy",
"debug",
"depth",
"execute_binding",
"get_lines",
"handle_key",
"handle_mouse",
"height",
"id",
"is_bindable",
"is_selectable",
"keys",
"parent",
"parent_align",
"pop",
"pos",
"print",
"remove",
"select",
"selectables",
"selectables_length",
"selected",
"selected_index",
"serialize",
"serialized",
"set_char",
"set_recursive_depth",
"set_style",
"set_widgets",
"sidelength",
"size_policy",
"static_width",
"styles",
"vertical_align",
"width",
"wipe",
"_add_widget",
"_apply_vertalign",
"_bindings",
"_box",
"_centered_axis",
"_drag_target",
"_get_aligners",
"_get_char",
"_get_style",
"_has_printed",
"_id",
"_id_manager",
"_prev_screen",
"_selectables_length",
"_serialized_fields",
"_update_width",
"_widgets",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__getitem__",
"__hash__",
"__iadd__",
"__init__",
"__init_subclass__",
"__iter__",
"__len__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__setitem__",
"__sizeof__",
"__slots__",
"__str__"
] | """The module containing all of the layout-related widgets."""
# These widgets have more than the 7 allowed instance attributes.
# pylint: disable=too-many-instance-attributes
from __future__ import annotations
from itertools import zip_longest
from typing import Any, Callable, Iterator, cast
from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal
from ..context_managers import cursor_at
from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment
from ..exceptions import WidthExceededError
from ..helpers import real_length
from ..input import keys
from . import boxes
from . import styles as w_styles
from .base import Widget
class Container(Widget):
"""A widget that displays other widgets, stacked vertically."""
chars: dict[str, w_styles.CharType] = {
"border": ["| ", "-", " |", "-"],
"corner": [""] * 4,
}
styles = {
"border": w_styles.MARKUP,
"corner": w_styles.MARKUP,
"fill": w_styles.BACKGROUND,
}
keys = {
"next": {keys.DOWN, keys.CTRL_N, "j"},
"previous": {keys.UP, keys.CTRL_P, "k"},
}
serialized = Widget.serialized + ["_centered_axis"]
vertical_align = VerticalAlignment.CENTER
allow_fullscreen = True
# TODO: Add `WidgetConvertible`? type instead of Any
def __init__(self, *widgets: Any, **attrs: Any) -> None:
"""Initialize Container data"""
super().__init__(**attrs)
# TODO: This is just a band-aid.
if "width" not in attrs:
self.width = 40
self._widgets: list[Widget] = []
self._centered_axis: CenteringPolicy | None = None
self._prev_screen: tuple[int, int] = (0, 0)
self._has_printed = False
self.styles = type(self).styles.copy()
self.chars = type(self).chars.copy()
for widget in widgets:
self._add_widget(widget)
self._drag_target: Widget | None = None
terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self. | ))
@property
def sidelength(self) -> int:
"""Gets the length of left and right borders combined.
Returns:
An integer equal to the `pytermgui.helpers.real_length` of the concatenation of
the left and right borders of this widget, both with their respective styles
applied.
"""
chars = self._get_char("border")
style = self._get_style("border")
if not isinstance(chars, list):
return 0
left_border, _, right_border, _ = chars
return real_length(style(left_border) + style(right_border))
@property
def selectables(self) -> list[tuple[Widget, int]]:
"""Gets all selectable widgets and their inner indices.
This is used in order to have a constant reference to all selectable indices within this
widget.
Returns:
A list of tuples containing a widget and an integer each. For each widget that is
withing this one, it is added to this list as many times as it has selectables. Each
of the integers correspond to a selectable_index within the widget.
For example, a Container with a Button, InputField and an inner Container containing
3 selectables might return something like this:
```
[
(Button(...), 0),
(InputField(...), 0),
(Container(...), 0),
(Container(...), 1),
(Container(...), 2),
]
```
"""
_selectables: list[tuple[Widget, int]] = []
for widget in self._widgets:
if not widget.is_selectable:
continue
for i, (inner, _) in enumerate(widget.selectables):
_selectables.append((inner, i))
return _selectables
@property
def selectables_length(self) -> int:
"""Gets the length of the selectables list.
Returns:
An integer equal to the length of `self.selectables`.
"""
return len(self.selectables)
@property
def selected(self) -> Widget | None:
"""Returns the currently selected object
Returns:
The currently selected widget if selected_index is not None,
otherwise None.
"""
# TODO: Add deeper selection
if self.selected_index is None:
return None
if self.selected_index >= len(self.selectables):
return None
return self.selectables[self.selected_index][0]
@property
def box(self) -> boxes.Box:
"""Returns current box setting
Returns:
The currently set box instance.
"""
return self._box
@box.setter
def box(self, new: str | boxes.Box) -> None:
"""Applies a new box.
Args:
new: Either a `pytermgui.boxes.Box` instance or a string
analogous to one of the default box names.
"""
if isinstance(new, str):
from_module = vars(boxes).get(new)
if from_module is None:
raise ValueError(f"Unknown box type {new}.")
new = from_module
assert isinstance(new, boxes.Box)
self._box = new
new.set_chars_of(self)
def __iadd__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self._add_widget(other)
return self
def __add__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
This method is analogous to `Container.__iadd__`.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self.__iadd__(other)
return self
def __iter__(self) -> Iterator[Widget]:
"""Gets an iterator of self._widgets.
Yields:
The next widget.
"""
for widget in self._widgets:
yield widget
def __len__(self) -> int:
"""Gets the length of the widgets list.
Returns:
An integer describing len(self._widgets).
"""
return len(self._widgets)
def __getitem__(self, sli: int | slice) -> Widget | list[Widget]:
"""Gets an item from self._widgets.
Args:
sli: Slice of the list.
Returns:
The slice in the list.
"""
return self._widgets[sli]
def __setitem__(self, index: int, value: Any) -> None:
"""Sets an item in self._widgets.
Args:
index: The index to be set.
value: The new widget at this index.
"""
self._widgets[index] = value
def __contains__(self, other: object) -> bool:
"""Determines if self._widgets contains other widget.
Args:
other: Any widget-like.
Returns:
A boolean describing whether `other` is in `self.widgets`
"""
return other in self._widgets
def _add_widget(self, other: object, run_get_lines: bool = True) -> None:
"""Adds other to this widget.
Args:
other: Any widget-like object.
run_get_lines: Boolean controlling whether the self.get_lines is ran.
"""
if not isinstance(other, Widget):
to_widget = Widget.from_data(other)
if to_widget is None:
raise ValueError(
f"Could not convert {other} of type {type(other)} to a Widget!"
)
other = to_widget
# This is safe to do, as it would've raised an exception above already
assert isinstance(other, Widget)
self._widgets.append(other)
if isinstance(other, Container):
other.set_recursive_depth(self.depth + 2)
else:
other.depth = self.depth + 1
other.get_lines()
other.parent = self
if run_get_lines:
self.get_lines()
def _get_aligners(
self, widget: Widget, borders: tuple[str, str]
) -> tuple[Callable[[str], str], int]:
"""Gets an aligning method and position offset.
Args:
widget: The widget to align.
borders: The left and right borders to put the widget within.
Returns:
A tuple of a method that, when called with a line, will return that line
centered using the passed in widget's parent_align and width, as well as
the horizontal offset resulting from the widget being aligned.
"""
left, right = borders
char = self._get_style("fill")(" ")
def _align_left(text: str) -> str:
"""Align line to the left"""
padding = self.width - real_length(left + right) - real_length(text)
return left + text + padding * char + right
def _align_center(text: str) -> str:
"""Align line to the center"""
total = self.width - real_length(left + right) - real_length(text)
padding, offset = divmod(total, 2)
return left + (padding + offset) * char + text + padding * char + right
def _align_right(text: str) -> str:
"""Align line to the right"""
padding = self.width - real_length(left + right) - real_length(text)
return left + padding * char + text + right
if widget.parent_align == HorizontalAlignment.CENTER:
total = self.width - real_length(left + right) - widget.width
padding, offset = divmod(total, 2)
return _align_center, real_length(left) + padding + offset
if widget.parent_align == HorizontalAlignment.RIGHT:
return _align_right, self.width - real_length(left) - widget.width
# Default to left-aligned
return _align_left, real_length(left)
def _update_width(self, widget: Widget) -> None:
"""Updates the width of widget or self.
This method respects widget.size_policy.
Args:
widget: The widget to update/base updates on.
"""
available = (
self.width - self.sidelength - (0 if isinstance(widget, Container) else 1)
)
if widget.size_policy == SizePolicy.FILL:
widget.width = available
return
if widget.size_policy == SizePolicy.RELATIVE:
widget.width = widget.relative_width * available
return
if widget.width > available:
if widget.size_policy == SizePolicy.STATIC:
raise WidthExceededError(
f"Widget {widget}'s static width of {widget.width}"
+ f" exceeds its parent's available width {available}."
""
)
widget.width = available
def _apply_vertalign(
self, lines: list[str], diff: int, padder: str
) -> tuple[int, list[str]]:
"""Insert padder line into lines diff times, depending on self.vertical_align.
Args:
lines: The list of lines to align.
diff: The available height.
padder: The line to use to pad.
Returns:
A tuple containing the vertical offset as well as the padded list of lines.
Raises:
NotImplementedError: The given vertical alignment is not implemented.
"""
if self.vertical_align == VerticalAlignment.BOTTOM:
for _ in range(diff):
lines.insert(0, padder)
return diff, lines
if self.vertical_align == VerticalAlignment.TOP:
for _ in range(diff):
lines.append(padder)
return 0, lines
if self.vertical_align == VerticalAlignment.CENTER:
top, extra = divmod(diff, 2)
bottom = top + extra
for _ in range(top):
lines.insert(0, padder)
for _ in range(bottom):
lines.append(padder)
return top, lines
raise NotImplementedError(
f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}."
)
def get_lines(self) -> list[str]:
"""Gets all lines by spacing out inner widgets.
This method reflects & applies both width settings, as well as
the `parent_align` field.
Returns:
A list of all lines that represent this Container.
"""
def _get_border(left: str, char: str, right: str) -> str:
"""Gets a top or bottom border.
Args:
left: Left corner character.
char: Border character filling between left & right.
right: Right corner character.
Returns:
The border line.
"""
offset = real_length(left + right)
return left + char * (self.width - offset) + right
lines = []
style = self._get_style("border")
borders = [style(char) for char in self._get_char("border")]
style = self._get_style("corner")
corners = [style(char) for char in self._get_char("corner")]
has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0)
align = lambda item: item
for widget in self._widgets:
align, offset = self._get_aligners(widget, (borders[0], borders[2]))
self._update_width(widget)
widget.pos = (
self.pos[0] + offset,
self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0),
)
widget_lines = []
for line in widget.get_lines():
widget_lines.append(align(line))
lines.extend(widget_lines)
vertical_offset, lines = self._apply_vertalign(
lines, self.height - len(lines) - sum(has_top_bottom), align("")
)
for widget in self._widgets:
widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset)
# TODO: This is wasteful.
widget.get_lines()
if has_top_bottom[0]:
lines.insert(0, _get_border(corners[0], borders[1], corners[1]))
if has_top_bottom[1]:
lines.append(_get_border(corners[3], borders[3], corners[2]))
self.height = len(lines)
return lines
def set_widgets(self, new: list[Widget]) -> None:
"""Sets new list in place of self._widgets.
Args:
new: The new widget list.
"""
self._widgets = []
for widget in new:
self._add_widget(widget)
def serialize(self) -> dict[str, Any]:
"""Serializes this Container, adding in serializations of all widgets.
See `pytermgui.widgets.base.Widget.serialize` for more info.
Returns:
The dictionary containing all serialized data.
"""
out = super().serialize()
out["_widgets"] = []
for widget in self._widgets:
out["_widgets"].append(widget.serialize())
return out
def pop(self, index: int = -1) -> Widget:
"""Pops widget from self._widgets.
Analogous to self._widgets.pop(index).
Args:
index: The index to operate on.
Returns:
The widget that was popped off the list.
"""
return self._widgets.pop(index)
def remove(self, other: Widget) -> None:
"""Remove widget from self._widgets
Analogous to self._widgets.remove(other).
Args:
widget: The widget to remove.
"""
return self._widgets.remove(other)
def set_recursive_depth(self, value: int) -> None:
"""Set depth for this Container and all its children.
All inner widgets will receive value+1 as their new depth.
Args:
value: The new depth to use as the base depth.
"""
self.depth = value
for widget in self._widgets:
if isinstance(widget, Container):
widget.set_recursive_depth(value + 1)
else:
widget.depth = value
def select(self, index: int | None = None) -> None:
"""Selects inner subwidget.
Args:
index: The index to select.
Raises:
IndexError: The index provided was beyond len(self.selectables).
"""
# Unselect all sub-elements
for other in self._widgets:
if other.selectables_length > 0:
other.select(None)
if index is not None:
if index >= len(self.selectables) is None:
raise IndexError("Container selection index out of range")
widget, inner_index = self.selectables[index]
widget.select(inner_index)
self.selected_index = index
def center(
self, where: CenteringPolicy | None = None, store: bool = True
) -> Container:
"""Centers this object to the given axis.
Args:
where: A CenteringPolicy describing the place to center to
store: When set, this centering will be reapplied during every
print, as well as when calling this method with no arguments.
Returns:
This Container.
"""
# Refresh in case changes happened
self.get_lines()
if where is None:
# See `enums.py` for explanation about this ignore.
where = CenteringPolicy.get_default() # type: ignore
centerx = centery = where is CenteringPolicy.ALL
centerx |= where is CenteringPolicy.HORIZONTAL
centery |= where is CenteringPolicy.VERTICAL
pos = list(self.pos)
if centerx:
pos[0] = (terminal.width - self.width + 2) // 2
if centery:
pos[1] = (terminal.height - self.height + 2) // 2
self.pos = (pos[0], pos[1])
if store:
self._centered_axis = where
self._prev_screen = terminal.size
return self
def handle_mouse(self, event: MouseEvent) -> bool:
"""Applies a mouse event on all children.
Args:
event: The event to handle
Returns:
A boolean showing whether the event was handled.
"""
if event.action is MouseAction.RELEASE:
# Force RELEASE event to be sent
if self._drag_target is not None:
self._drag_target.handle_mouse(
MouseEvent(MouseAction.RELEASE, event.position)
)
self._drag_target = None
if self._drag_target is not None:
return self._drag_target.handle_mouse(event)
selectables_index = 0
for widget in self._widgets:
if widget.contains(event.position):
handled = widget.handle_mouse(event)
if widget.selected_index is not None:
selectables_index += widget.selected_index
if event.action is MouseAction.LEFT_CLICK:
self._drag_target = widget
if handled:
self.select(selectables_index)
return handled
if widget.is_selectable:
selectables_index += widget.selectables_length
return False
def handle_key(self, key: str) -> bool:
"""Handles a keypress, returns its success.
Args:
key: A key str.
Returns:
A boolean showing whether the key was handled.
"""
def _is_nav(key: str) -> bool:
"""Determine if a key is in the navigation sets"""
return key in self.keys["next"] | self.keys["previous"]
if self.selected is not None and self.selected.handle_key(key):
return True
# Only use navigation when there is more than one selectable
if self.selectables_length > 1 and _is_nav(key):
handled = False
if self.selected_index is None:
self.select(0)
assert isinstance(self.selected_index, int)
if key in self.keys["previous"]:
# No more selectables left, user wants to exit Container
# upwards.
if self.selected_index == 0:
return False
self.select(self.selected_index - 1)
handled = True
elif key in self.keys["next"]:
# Stop selection at last element, return as unhandled
new = self.selected_index + 1
if new == len(self.selectables):
return False
self.select(new)
handled = True
if handled:
return True
if key == keys.ENTER and self.selected is not None:
if self.selected.selected_index is not None:
self.selected.handle_key(key)
return True
return False
def wipe(self) -> None:
"""Wipes the characters occupied by the object"""
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(real_length(line) * " ")
def print(self) -> None:
"""Prints this Container.
If the screen size has changed since last `print` call, the object
will be centered based on its `_centered_axis`.
"""
if not terminal.size == self._prev_screen:
clear()
self.center(self._centered_axis)
self._prev_screen = terminal.size
if self.allow_fullscreen:
self.pos = terminal.origin
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(line)
self._has_printed = True
def debug(self) -> str:
"""Returns a string with identifiable information on this widget.
Returns:
A str in the form of a class construction. This string is in a form that
__could have been__ used to create this Container.
"""
out = "Container("
for widget in self._widgets:
out += widget.debug() + ", "
out = out.strip(", ")
out += ", **attrs)"
return out
class Splitter(Container):
"""A widget that displays other widgets, stacked horizontally."""
chars: dict[str, list[str] | str] = {"separator": " | "}
styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND}
keys = {
"previous": {keys.LEFT, "h", keys.CTRL_B},
"next": {keys.RIGHT, "l", keys.CTRL_F},
}
parent_align = HorizontalAlignment.RIGHT
def _align(
self, alignment: HorizontalAlignment, target_width: int, line: str
) -> tuple[int, str]:
"""Align a line
r/wordavalanches"""
available = target_width - real_length(line)
fill_style = self._get_style("fill")
char = fill_style(" ")
line = fill_style(line)
if alignment == HorizontalAlignment.CENTER:
padding, offset = divmod(available, 2)
return padding, padding * char + line + (padding + offset) * char
if alignment == HorizontalAlignment.RIGHT:
return available, available * char + line
return 0, line + available * char
def get_lines(self) -> list[str]:
"""Join all widgets horizontally."""
# An error will be raised if `separator` is not the correct type (str).
separator = self._get_style("separator")(self._get_char("separator")) # type: ignore
separator_length = real_length(separator)
target_width, error = divmod(
self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets)
)
vertical_lines = []
total_offset = 0
for widget in self._widgets:
inner = []
if widget.size_policy is SizePolicy.STATIC:
target_width += target_width - widget.width
width = target_width
else:
widget.width = target_width + error
width = widget.width
error = 0
aligned: str | None = None
for line in widget.get_lines():
# See `enums.py` for information about this ignore
padding, aligned = self._align(
cast(HorizontalAlignment, widget.parent_align), width, line
)
inner.append(aligned)
widget.pos = (
self.pos[0] + padding + total_offset,
self.pos[1] + (1 if type(widget).__name__ == "Container" else 0),
)
if aligned is not None:
total_offset += real_length(inner[-1]) + separator_length
vertical_lines.append(inner)
lines = []
for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width):
lines.append((reset() + separator).join(horizontal))
return lines
def debug(self) -> str:
"""Return identifiable information"""
return super().debug().replace("Container", "Splitter", 1)
| bczsalba__pytermgui |
54 | 54-115-26 | inproject | is_selectable | [
"bind",
"bindings",
"chars",
"contains",
"copy",
"debug",
"depth",
"execute_binding",
"get_lines",
"handle_key",
"handle_mouse",
"height",
"id",
"is_bindable",
"is_selectable",
"keys",
"parent",
"parent_align",
"pos",
"print",
"select",
"selectables",
"selectables_length",
"selected_index",
"serialize",
"serialized",
"set_char",
"set_style",
"size_policy",
"static_width",
"styles",
"width",
"_bindings",
"_get_char",
"_get_style",
"_id",
"_id_manager",
"_selectables_length",
"_serialized_fields",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__iter__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """The module containing all of the layout-related widgets."""
# These widgets have more than the 7 allowed instance attributes.
# pylint: disable=too-many-instance-attributes
from __future__ import annotations
from itertools import zip_longest
from typing import Any, Callable, Iterator, cast
from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal
from ..context_managers import cursor_at
from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment
from ..exceptions import WidthExceededError
from ..helpers import real_length
from ..input import keys
from . import boxes
from . import styles as w_styles
from .base import Widget
class Container(Widget):
"""A widget that displays other widgets, stacked vertically."""
chars: dict[str, w_styles.CharType] = {
"border": ["| ", "-", " |", "-"],
"corner": [""] * 4,
}
styles = {
"border": w_styles.MARKUP,
"corner": w_styles.MARKUP,
"fill": w_styles.BACKGROUND,
}
keys = {
"next": {keys.DOWN, keys.CTRL_N, "j"},
"previous": {keys.UP, keys.CTRL_P, "k"},
}
serialized = Widget.serialized + ["_centered_axis"]
vertical_align = VerticalAlignment.CENTER
allow_fullscreen = True
# TODO: Add `WidgetConvertible`? type instead of Any
def __init__(self, *widgets: Any, **attrs: Any) -> None:
"""Initialize Container data"""
super().__init__(**attrs)
# TODO: This is just a band-aid.
if "width" not in attrs:
self.width = 40
self._widgets: list[Widget] = []
self._centered_axis: CenteringPolicy | None = None
self._prev_screen: tuple[int, int] = (0, 0)
self._has_printed = False
self.styles = type(self).styles.copy()
self.chars = type(self).chars.copy()
for widget in widgets:
self._add_widget(widget)
self._drag_target: Widget | None = None
terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis))
@property
def sidelength(self) -> int:
"""Gets the length of left and right borders combined.
Returns:
An integer equal to the `pytermgui.helpers.real_length` of the concatenation of
the left and right borders of this widget, both with their respective styles
applied.
"""
chars = self._get_char("border")
style = self._get_style("border")
if not isinstance(chars, list):
return 0
left_border, _, right_border, _ = chars
return real_length(style(left_border) + style(right_border))
@property
def selectables(self) -> list[tuple[Widget, int]]:
"""Gets all selectable widgets and their inner indices.
This is used in order to have a constant reference to all selectable indices within this
widget.
Returns:
A list of tuples containing a widget and an integer each. For each widget that is
withing this one, it is added to this list as many times as it has selectables. Each
of the integers correspond to a selectable_index within the widget.
For example, a Container with a Button, InputField and an inner Container containing
3 selectables might return something like this:
```
[
(Button(...), 0),
(InputField(...), 0),
(Container(...), 0),
(Container(...), 1),
(Container(...), 2),
]
```
"""
_selectables: list[tuple[Widget, int]] = []
for widget in self._widgets:
if not widget. | :
continue
for i, (inner, _) in enumerate(widget.selectables):
_selectables.append((inner, i))
return _selectables
@property
def selectables_length(self) -> int:
"""Gets the length of the selectables list.
Returns:
An integer equal to the length of `self.selectables`.
"""
return len(self.selectables)
@property
def selected(self) -> Widget | None:
"""Returns the currently selected object
Returns:
The currently selected widget if selected_index is not None,
otherwise None.
"""
# TODO: Add deeper selection
if self.selected_index is None:
return None
if self.selected_index >= len(self.selectables):
return None
return self.selectables[self.selected_index][0]
@property
def box(self) -> boxes.Box:
"""Returns current box setting
Returns:
The currently set box instance.
"""
return self._box
@box.setter
def box(self, new: str | boxes.Box) -> None:
"""Applies a new box.
Args:
new: Either a `pytermgui.boxes.Box` instance or a string
analogous to one of the default box names.
"""
if isinstance(new, str):
from_module = vars(boxes).get(new)
if from_module is None:
raise ValueError(f"Unknown box type {new}.")
new = from_module
assert isinstance(new, boxes.Box)
self._box = new
new.set_chars_of(self)
def __iadd__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self._add_widget(other)
return self
def __add__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
This method is analogous to `Container.__iadd__`.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self.__iadd__(other)
return self
def __iter__(self) -> Iterator[Widget]:
"""Gets an iterator of self._widgets.
Yields:
The next widget.
"""
for widget in self._widgets:
yield widget
def __len__(self) -> int:
"""Gets the length of the widgets list.
Returns:
An integer describing len(self._widgets).
"""
return len(self._widgets)
def __getitem__(self, sli: int | slice) -> Widget | list[Widget]:
"""Gets an item from self._widgets.
Args:
sli: Slice of the list.
Returns:
The slice in the list.
"""
return self._widgets[sli]
def __setitem__(self, index: int, value: Any) -> None:
"""Sets an item in self._widgets.
Args:
index: The index to be set.
value: The new widget at this index.
"""
self._widgets[index] = value
def __contains__(self, other: object) -> bool:
"""Determines if self._widgets contains other widget.
Args:
other: Any widget-like.
Returns:
A boolean describing whether `other` is in `self.widgets`
"""
return other in self._widgets
def _add_widget(self, other: object, run_get_lines: bool = True) -> None:
"""Adds other to this widget.
Args:
other: Any widget-like object.
run_get_lines: Boolean controlling whether the self.get_lines is ran.
"""
if not isinstance(other, Widget):
to_widget = Widget.from_data(other)
if to_widget is None:
raise ValueError(
f"Could not convert {other} of type {type(other)} to a Widget!"
)
other = to_widget
# This is safe to do, as it would've raised an exception above already
assert isinstance(other, Widget)
self._widgets.append(other)
if isinstance(other, Container):
other.set_recursive_depth(self.depth + 2)
else:
other.depth = self.depth + 1
other.get_lines()
other.parent = self
if run_get_lines:
self.get_lines()
def _get_aligners(
self, widget: Widget, borders: tuple[str, str]
) -> tuple[Callable[[str], str], int]:
"""Gets an aligning method and position offset.
Args:
widget: The widget to align.
borders: The left and right borders to put the widget within.
Returns:
A tuple of a method that, when called with a line, will return that line
centered using the passed in widget's parent_align and width, as well as
the horizontal offset resulting from the widget being aligned.
"""
left, right = borders
char = self._get_style("fill")(" ")
def _align_left(text: str) -> str:
"""Align line to the left"""
padding = self.width - real_length(left + right) - real_length(text)
return left + text + padding * char + right
def _align_center(text: str) -> str:
"""Align line to the center"""
total = self.width - real_length(left + right) - real_length(text)
padding, offset = divmod(total, 2)
return left + (padding + offset) * char + text + padding * char + right
def _align_right(text: str) -> str:
"""Align line to the right"""
padding = self.width - real_length(left + right) - real_length(text)
return left + padding * char + text + right
if widget.parent_align == HorizontalAlignment.CENTER:
total = self.width - real_length(left + right) - widget.width
padding, offset = divmod(total, 2)
return _align_center, real_length(left) + padding + offset
if widget.parent_align == HorizontalAlignment.RIGHT:
return _align_right, self.width - real_length(left) - widget.width
# Default to left-aligned
return _align_left, real_length(left)
def _update_width(self, widget: Widget) -> None:
"""Updates the width of widget or self.
This method respects widget.size_policy.
Args:
widget: The widget to update/base updates on.
"""
available = (
self.width - self.sidelength - (0 if isinstance(widget, Container) else 1)
)
if widget.size_policy == SizePolicy.FILL:
widget.width = available
return
if widget.size_policy == SizePolicy.RELATIVE:
widget.width = widget.relative_width * available
return
if widget.width > available:
if widget.size_policy == SizePolicy.STATIC:
raise WidthExceededError(
f"Widget {widget}'s static width of {widget.width}"
+ f" exceeds its parent's available width {available}."
""
)
widget.width = available
def _apply_vertalign(
self, lines: list[str], diff: int, padder: str
) -> tuple[int, list[str]]:
"""Insert padder line into lines diff times, depending on self.vertical_align.
Args:
lines: The list of lines to align.
diff: The available height.
padder: The line to use to pad.
Returns:
A tuple containing the vertical offset as well as the padded list of lines.
Raises:
NotImplementedError: The given vertical alignment is not implemented.
"""
if self.vertical_align == VerticalAlignment.BOTTOM:
for _ in range(diff):
lines.insert(0, padder)
return diff, lines
if self.vertical_align == VerticalAlignment.TOP:
for _ in range(diff):
lines.append(padder)
return 0, lines
if self.vertical_align == VerticalAlignment.CENTER:
top, extra = divmod(diff, 2)
bottom = top + extra
for _ in range(top):
lines.insert(0, padder)
for _ in range(bottom):
lines.append(padder)
return top, lines
raise NotImplementedError(
f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}."
)
def get_lines(self) -> list[str]:
"""Gets all lines by spacing out inner widgets.
This method reflects & applies both width settings, as well as
the `parent_align` field.
Returns:
A list of all lines that represent this Container.
"""
def _get_border(left: str, char: str, right: str) -> str:
"""Gets a top or bottom border.
Args:
left: Left corner character.
char: Border character filling between left & right.
right: Right corner character.
Returns:
The border line.
"""
offset = real_length(left + right)
return left + char * (self.width - offset) + right
lines = []
style = self._get_style("border")
borders = [style(char) for char in self._get_char("border")]
style = self._get_style("corner")
corners = [style(char) for char in self._get_char("corner")]
has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0)
align = lambda item: item
for widget in self._widgets:
align, offset = self._get_aligners(widget, (borders[0], borders[2]))
self._update_width(widget)
widget.pos = (
self.pos[0] + offset,
self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0),
)
widget_lines = []
for line in widget.get_lines():
widget_lines.append(align(line))
lines.extend(widget_lines)
vertical_offset, lines = self._apply_vertalign(
lines, self.height - len(lines) - sum(has_top_bottom), align("")
)
for widget in self._widgets:
widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset)
# TODO: This is wasteful.
widget.get_lines()
if has_top_bottom[0]:
lines.insert(0, _get_border(corners[0], borders[1], corners[1]))
if has_top_bottom[1]:
lines.append(_get_border(corners[3], borders[3], corners[2]))
self.height = len(lines)
return lines
def set_widgets(self, new: list[Widget]) -> None:
"""Sets new list in place of self._widgets.
Args:
new: The new widget list.
"""
self._widgets = []
for widget in new:
self._add_widget(widget)
def serialize(self) -> dict[str, Any]:
"""Serializes this Container, adding in serializations of all widgets.
See `pytermgui.widgets.base.Widget.serialize` for more info.
Returns:
The dictionary containing all serialized data.
"""
out = super().serialize()
out["_widgets"] = []
for widget in self._widgets:
out["_widgets"].append(widget.serialize())
return out
def pop(self, index: int = -1) -> Widget:
"""Pops widget from self._widgets.
Analogous to self._widgets.pop(index).
Args:
index: The index to operate on.
Returns:
The widget that was popped off the list.
"""
return self._widgets.pop(index)
def remove(self, other: Widget) -> None:
"""Remove widget from self._widgets
Analogous to self._widgets.remove(other).
Args:
widget: The widget to remove.
"""
return self._widgets.remove(other)
def set_recursive_depth(self, value: int) -> None:
"""Set depth for this Container and all its children.
All inner widgets will receive value+1 as their new depth.
Args:
value: The new depth to use as the base depth.
"""
self.depth = value
for widget in self._widgets:
if isinstance(widget, Container):
widget.set_recursive_depth(value + 1)
else:
widget.depth = value
def select(self, index: int | None = None) -> None:
"""Selects inner subwidget.
Args:
index: The index to select.
Raises:
IndexError: The index provided was beyond len(self.selectables).
"""
# Unselect all sub-elements
for other in self._widgets:
if other.selectables_length > 0:
other.select(None)
if index is not None:
if index >= len(self.selectables) is None:
raise IndexError("Container selection index out of range")
widget, inner_index = self.selectables[index]
widget.select(inner_index)
self.selected_index = index
def center(
self, where: CenteringPolicy | None = None, store: bool = True
) -> Container:
"""Centers this object to the given axis.
Args:
where: A CenteringPolicy describing the place to center to
store: When set, this centering will be reapplied during every
print, as well as when calling this method with no arguments.
Returns:
This Container.
"""
# Refresh in case changes happened
self.get_lines()
if where is None:
# See `enums.py` for explanation about this ignore.
where = CenteringPolicy.get_default() # type: ignore
centerx = centery = where is CenteringPolicy.ALL
centerx |= where is CenteringPolicy.HORIZONTAL
centery |= where is CenteringPolicy.VERTICAL
pos = list(self.pos)
if centerx:
pos[0] = (terminal.width - self.width + 2) // 2
if centery:
pos[1] = (terminal.height - self.height + 2) // 2
self.pos = (pos[0], pos[1])
if store:
self._centered_axis = where
self._prev_screen = terminal.size
return self
def handle_mouse(self, event: MouseEvent) -> bool:
"""Applies a mouse event on all children.
Args:
event: The event to handle
Returns:
A boolean showing whether the event was handled.
"""
if event.action is MouseAction.RELEASE:
# Force RELEASE event to be sent
if self._drag_target is not None:
self._drag_target.handle_mouse(
MouseEvent(MouseAction.RELEASE, event.position)
)
self._drag_target = None
if self._drag_target is not None:
return self._drag_target.handle_mouse(event)
selectables_index = 0
for widget in self._widgets:
if widget.contains(event.position):
handled = widget.handle_mouse(event)
if widget.selected_index is not None:
selectables_index += widget.selected_index
if event.action is MouseAction.LEFT_CLICK:
self._drag_target = widget
if handled:
self.select(selectables_index)
return handled
if widget.is_selectable:
selectables_index += widget.selectables_length
return False
def handle_key(self, key: str) -> bool:
"""Handles a keypress, returns its success.
Args:
key: A key str.
Returns:
A boolean showing whether the key was handled.
"""
def _is_nav(key: str) -> bool:
"""Determine if a key is in the navigation sets"""
return key in self.keys["next"] | self.keys["previous"]
if self.selected is not None and self.selected.handle_key(key):
return True
# Only use navigation when there is more than one selectable
if self.selectables_length > 1 and _is_nav(key):
handled = False
if self.selected_index is None:
self.select(0)
assert isinstance(self.selected_index, int)
if key in self.keys["previous"]:
# No more selectables left, user wants to exit Container
# upwards.
if self.selected_index == 0:
return False
self.select(self.selected_index - 1)
handled = True
elif key in self.keys["next"]:
# Stop selection at last element, return as unhandled
new = self.selected_index + 1
if new == len(self.selectables):
return False
self.select(new)
handled = True
if handled:
return True
if key == keys.ENTER and self.selected is not None:
if self.selected.selected_index is not None:
self.selected.handle_key(key)
return True
return False
def wipe(self) -> None:
"""Wipes the characters occupied by the object"""
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(real_length(line) * " ")
def print(self) -> None:
"""Prints this Container.
If the screen size has changed since last `print` call, the object
will be centered based on its `_centered_axis`.
"""
if not terminal.size == self._prev_screen:
clear()
self.center(self._centered_axis)
self._prev_screen = terminal.size
if self.allow_fullscreen:
self.pos = terminal.origin
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(line)
self._has_printed = True
def debug(self) -> str:
"""Returns a string with identifiable information on this widget.
Returns:
A str in the form of a class construction. This string is in a form that
__could have been__ used to create this Container.
"""
out = "Container("
for widget in self._widgets:
out += widget.debug() + ", "
out = out.strip(", ")
out += ", **attrs)"
return out
class Splitter(Container):
"""A widget that displays other widgets, stacked horizontally."""
chars: dict[str, list[str] | str] = {"separator": " | "}
styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND}
keys = {
"previous": {keys.LEFT, "h", keys.CTRL_B},
"next": {keys.RIGHT, "l", keys.CTRL_F},
}
parent_align = HorizontalAlignment.RIGHT
def _align(
self, alignment: HorizontalAlignment, target_width: int, line: str
) -> tuple[int, str]:
"""Align a line
r/wordavalanches"""
available = target_width - real_length(line)
fill_style = self._get_style("fill")
char = fill_style(" ")
line = fill_style(line)
if alignment == HorizontalAlignment.CENTER:
padding, offset = divmod(available, 2)
return padding, padding * char + line + (padding + offset) * char
if alignment == HorizontalAlignment.RIGHT:
return available, available * char + line
return 0, line + available * char
def get_lines(self) -> list[str]:
"""Join all widgets horizontally."""
# An error will be raised if `separator` is not the correct type (str).
separator = self._get_style("separator")(self._get_char("separator")) # type: ignore
separator_length = real_length(separator)
target_width, error = divmod(
self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets)
)
vertical_lines = []
total_offset = 0
for widget in self._widgets:
inner = []
if widget.size_policy is SizePolicy.STATIC:
target_width += target_width - widget.width
width = target_width
else:
widget.width = target_width + error
width = widget.width
error = 0
aligned: str | None = None
for line in widget.get_lines():
# See `enums.py` for information about this ignore
padding, aligned = self._align(
cast(HorizontalAlignment, widget.parent_align), width, line
)
inner.append(aligned)
widget.pos = (
self.pos[0] + padding + total_offset,
self.pos[1] + (1 if type(widget).__name__ == "Container" else 0),
)
if aligned is not None:
total_offset += real_length(inner[-1]) + separator_length
vertical_lines.append(inner)
lines = []
for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width):
lines.append((reset() + separator).join(horizontal))
return lines
def debug(self) -> str:
"""Return identifiable information"""
return super().debug().replace("Container", "Splitter", 1)
| bczsalba__pytermgui |
54 | 54-118-50 | infile | selectables | [
"bind",
"bindings",
"chars",
"contains",
"copy",
"debug",
"depth",
"execute_binding",
"get_lines",
"handle_key",
"handle_mouse",
"height",
"id",
"is_bindable",
"is_selectable",
"keys",
"parent",
"parent_align",
"pos",
"print",
"select",
"selectables",
"selectables_length",
"selected_index",
"serialize",
"serialized",
"set_char",
"set_style",
"size_policy",
"static_width",
"styles",
"width",
"_bindings",
"_get_char",
"_get_style",
"_id",
"_id_manager",
"_selectables_length",
"_serialized_fields",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__iter__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """The module containing all of the layout-related widgets."""
# These widgets have more than the 7 allowed instance attributes.
# pylint: disable=too-many-instance-attributes
from __future__ import annotations
from itertools import zip_longest
from typing import Any, Callable, Iterator, cast
from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal
from ..context_managers import cursor_at
from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment
from ..exceptions import WidthExceededError
from ..helpers import real_length
from ..input import keys
from . import boxes
from . import styles as w_styles
from .base import Widget
class Container(Widget):
"""A widget that displays other widgets, stacked vertically."""
chars: dict[str, w_styles.CharType] = {
"border": ["| ", "-", " |", "-"],
"corner": [""] * 4,
}
styles = {
"border": w_styles.MARKUP,
"corner": w_styles.MARKUP,
"fill": w_styles.BACKGROUND,
}
keys = {
"next": {keys.DOWN, keys.CTRL_N, "j"},
"previous": {keys.UP, keys.CTRL_P, "k"},
}
serialized = Widget.serialized + ["_centered_axis"]
vertical_align = VerticalAlignment.CENTER
allow_fullscreen = True
# TODO: Add `WidgetConvertible`? type instead of Any
def __init__(self, *widgets: Any, **attrs: Any) -> None:
"""Initialize Container data"""
super().__init__(**attrs)
# TODO: This is just a band-aid.
if "width" not in attrs:
self.width = 40
self._widgets: list[Widget] = []
self._centered_axis: CenteringPolicy | None = None
self._prev_screen: tuple[int, int] = (0, 0)
self._has_printed = False
self.styles = type(self).styles.copy()
self.chars = type(self).chars.copy()
for widget in widgets:
self._add_widget(widget)
self._drag_target: Widget | None = None
terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis))
@property
def sidelength(self) -> int:
"""Gets the length of left and right borders combined.
Returns:
An integer equal to the `pytermgui.helpers.real_length` of the concatenation of
the left and right borders of this widget, both with their respective styles
applied.
"""
chars = self._get_char("border")
style = self._get_style("border")
if not isinstance(chars, list):
return 0
left_border, _, right_border, _ = chars
return real_length(style(left_border) + style(right_border))
@property
def selectables(self) -> list[tuple[Widget, int]]:
"""Gets all selectable widgets and their inner indices.
This is used in order to have a constant reference to all selectable indices within this
widget.
Returns:
A list of tuples containing a widget and an integer each. For each widget that is
withing this one, it is added to this list as many times as it has selectables. Each
of the integers correspond to a selectable_index within the widget.
For example, a Container with a Button, InputField and an inner Container containing
3 selectables might return something like this:
```
[
(Button(...), 0),
(InputField(...), 0),
(Container(...), 0),
(Container(...), 1),
(Container(...), 2),
]
```
"""
_selectables: list[tuple[Widget, int]] = []
for widget in self._widgets:
if not widget.is_selectable:
continue
for i, (inner, _) in enumerate(widget. | ):
_selectables.append((inner, i))
return _selectables
@property
def selectables_length(self) -> int:
"""Gets the length of the selectables list.
Returns:
An integer equal to the length of `self.selectables`.
"""
return len(self.selectables)
@property
def selected(self) -> Widget | None:
"""Returns the currently selected object
Returns:
The currently selected widget if selected_index is not None,
otherwise None.
"""
# TODO: Add deeper selection
if self.selected_index is None:
return None
if self.selected_index >= len(self.selectables):
return None
return self.selectables[self.selected_index][0]
@property
def box(self) -> boxes.Box:
"""Returns current box setting
Returns:
The currently set box instance.
"""
return self._box
@box.setter
def box(self, new: str | boxes.Box) -> None:
"""Applies a new box.
Args:
new: Either a `pytermgui.boxes.Box` instance or a string
analogous to one of the default box names.
"""
if isinstance(new, str):
from_module = vars(boxes).get(new)
if from_module is None:
raise ValueError(f"Unknown box type {new}.")
new = from_module
assert isinstance(new, boxes.Box)
self._box = new
new.set_chars_of(self)
def __iadd__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self._add_widget(other)
return self
def __add__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
This method is analogous to `Container.__iadd__`.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self.__iadd__(other)
return self
def __iter__(self) -> Iterator[Widget]:
"""Gets an iterator of self._widgets.
Yields:
The next widget.
"""
for widget in self._widgets:
yield widget
def __len__(self) -> int:
"""Gets the length of the widgets list.
Returns:
An integer describing len(self._widgets).
"""
return len(self._widgets)
def __getitem__(self, sli: int | slice) -> Widget | list[Widget]:
"""Gets an item from self._widgets.
Args:
sli: Slice of the list.
Returns:
The slice in the list.
"""
return self._widgets[sli]
def __setitem__(self, index: int, value: Any) -> None:
"""Sets an item in self._widgets.
Args:
index: The index to be set.
value: The new widget at this index.
"""
self._widgets[index] = value
def __contains__(self, other: object) -> bool:
"""Determines if self._widgets contains other widget.
Args:
other: Any widget-like.
Returns:
A boolean describing whether `other` is in `self.widgets`
"""
return other in self._widgets
def _add_widget(self, other: object, run_get_lines: bool = True) -> None:
"""Adds other to this widget.
Args:
other: Any widget-like object.
run_get_lines: Boolean controlling whether the self.get_lines is ran.
"""
if not isinstance(other, Widget):
to_widget = Widget.from_data(other)
if to_widget is None:
raise ValueError(
f"Could not convert {other} of type {type(other)} to a Widget!"
)
other = to_widget
# This is safe to do, as it would've raised an exception above already
assert isinstance(other, Widget)
self._widgets.append(other)
if isinstance(other, Container):
other.set_recursive_depth(self.depth + 2)
else:
other.depth = self.depth + 1
other.get_lines()
other.parent = self
if run_get_lines:
self.get_lines()
def _get_aligners(
self, widget: Widget, borders: tuple[str, str]
) -> tuple[Callable[[str], str], int]:
"""Gets an aligning method and position offset.
Args:
widget: The widget to align.
borders: The left and right borders to put the widget within.
Returns:
A tuple of a method that, when called with a line, will return that line
centered using the passed in widget's parent_align and width, as well as
the horizontal offset resulting from the widget being aligned.
"""
left, right = borders
char = self._get_style("fill")(" ")
def _align_left(text: str) -> str:
"""Align line to the left"""
padding = self.width - real_length(left + right) - real_length(text)
return left + text + padding * char + right
def _align_center(text: str) -> str:
"""Align line to the center"""
total = self.width - real_length(left + right) - real_length(text)
padding, offset = divmod(total, 2)
return left + (padding + offset) * char + text + padding * char + right
def _align_right(text: str) -> str:
"""Align line to the right"""
padding = self.width - real_length(left + right) - real_length(text)
return left + padding * char + text + right
if widget.parent_align == HorizontalAlignment.CENTER:
total = self.width - real_length(left + right) - widget.width
padding, offset = divmod(total, 2)
return _align_center, real_length(left) + padding + offset
if widget.parent_align == HorizontalAlignment.RIGHT:
return _align_right, self.width - real_length(left) - widget.width
# Default to left-aligned
return _align_left, real_length(left)
def _update_width(self, widget: Widget) -> None:
"""Updates the width of widget or self.
This method respects widget.size_policy.
Args:
widget: The widget to update/base updates on.
"""
available = (
self.width - self.sidelength - (0 if isinstance(widget, Container) else 1)
)
if widget.size_policy == SizePolicy.FILL:
widget.width = available
return
if widget.size_policy == SizePolicy.RELATIVE:
widget.width = widget.relative_width * available
return
if widget.width > available:
if widget.size_policy == SizePolicy.STATIC:
raise WidthExceededError(
f"Widget {widget}'s static width of {widget.width}"
+ f" exceeds its parent's available width {available}."
""
)
widget.width = available
def _apply_vertalign(
self, lines: list[str], diff: int, padder: str
) -> tuple[int, list[str]]:
"""Insert padder line into lines diff times, depending on self.vertical_align.
Args:
lines: The list of lines to align.
diff: The available height.
padder: The line to use to pad.
Returns:
A tuple containing the vertical offset as well as the padded list of lines.
Raises:
NotImplementedError: The given vertical alignment is not implemented.
"""
if self.vertical_align == VerticalAlignment.BOTTOM:
for _ in range(diff):
lines.insert(0, padder)
return diff, lines
if self.vertical_align == VerticalAlignment.TOP:
for _ in range(diff):
lines.append(padder)
return 0, lines
if self.vertical_align == VerticalAlignment.CENTER:
top, extra = divmod(diff, 2)
bottom = top + extra
for _ in range(top):
lines.insert(0, padder)
for _ in range(bottom):
lines.append(padder)
return top, lines
raise NotImplementedError(
f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}."
)
def get_lines(self) -> list[str]:
"""Gets all lines by spacing out inner widgets.
This method reflects & applies both width settings, as well as
the `parent_align` field.
Returns:
A list of all lines that represent this Container.
"""
def _get_border(left: str, char: str, right: str) -> str:
"""Gets a top or bottom border.
Args:
left: Left corner character.
char: Border character filling between left & right.
right: Right corner character.
Returns:
The border line.
"""
offset = real_length(left + right)
return left + char * (self.width - offset) + right
lines = []
style = self._get_style("border")
borders = [style(char) for char in self._get_char("border")]
style = self._get_style("corner")
corners = [style(char) for char in self._get_char("corner")]
has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0)
align = lambda item: item
for widget in self._widgets:
align, offset = self._get_aligners(widget, (borders[0], borders[2]))
self._update_width(widget)
widget.pos = (
self.pos[0] + offset,
self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0),
)
widget_lines = []
for line in widget.get_lines():
widget_lines.append(align(line))
lines.extend(widget_lines)
vertical_offset, lines = self._apply_vertalign(
lines, self.height - len(lines) - sum(has_top_bottom), align("")
)
for widget in self._widgets:
widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset)
# TODO: This is wasteful.
widget.get_lines()
if has_top_bottom[0]:
lines.insert(0, _get_border(corners[0], borders[1], corners[1]))
if has_top_bottom[1]:
lines.append(_get_border(corners[3], borders[3], corners[2]))
self.height = len(lines)
return lines
def set_widgets(self, new: list[Widget]) -> None:
"""Sets new list in place of self._widgets.
Args:
new: The new widget list.
"""
self._widgets = []
for widget in new:
self._add_widget(widget)
def serialize(self) -> dict[str, Any]:
"""Serializes this Container, adding in serializations of all widgets.
See `pytermgui.widgets.base.Widget.serialize` for more info.
Returns:
The dictionary containing all serialized data.
"""
out = super().serialize()
out["_widgets"] = []
for widget in self._widgets:
out["_widgets"].append(widget.serialize())
return out
def pop(self, index: int = -1) -> Widget:
"""Pops widget from self._widgets.
Analogous to self._widgets.pop(index).
Args:
index: The index to operate on.
Returns:
The widget that was popped off the list.
"""
return self._widgets.pop(index)
def remove(self, other: Widget) -> None:
"""Remove widget from self._widgets
Analogous to self._widgets.remove(other).
Args:
widget: The widget to remove.
"""
return self._widgets.remove(other)
def set_recursive_depth(self, value: int) -> None:
"""Set depth for this Container and all its children.
All inner widgets will receive value+1 as their new depth.
Args:
value: The new depth to use as the base depth.
"""
self.depth = value
for widget in self._widgets:
if isinstance(widget, Container):
widget.set_recursive_depth(value + 1)
else:
widget.depth = value
def select(self, index: int | None = None) -> None:
"""Selects inner subwidget.
Args:
index: The index to select.
Raises:
IndexError: The index provided was beyond len(self.selectables).
"""
# Unselect all sub-elements
for other in self._widgets:
if other.selectables_length > 0:
other.select(None)
if index is not None:
if index >= len(self.selectables) is None:
raise IndexError("Container selection index out of range")
widget, inner_index = self.selectables[index]
widget.select(inner_index)
self.selected_index = index
def center(
self, where: CenteringPolicy | None = None, store: bool = True
) -> Container:
"""Centers this object to the given axis.
Args:
where: A CenteringPolicy describing the place to center to
store: When set, this centering will be reapplied during every
print, as well as when calling this method with no arguments.
Returns:
This Container.
"""
# Refresh in case changes happened
self.get_lines()
if where is None:
# See `enums.py` for explanation about this ignore.
where = CenteringPolicy.get_default() # type: ignore
centerx = centery = where is CenteringPolicy.ALL
centerx |= where is CenteringPolicy.HORIZONTAL
centery |= where is CenteringPolicy.VERTICAL
pos = list(self.pos)
if centerx:
pos[0] = (terminal.width - self.width + 2) // 2
if centery:
pos[1] = (terminal.height - self.height + 2) // 2
self.pos = (pos[0], pos[1])
if store:
self._centered_axis = where
self._prev_screen = terminal.size
return self
def handle_mouse(self, event: MouseEvent) -> bool:
"""Applies a mouse event on all children.
Args:
event: The event to handle
Returns:
A boolean showing whether the event was handled.
"""
if event.action is MouseAction.RELEASE:
# Force RELEASE event to be sent
if self._drag_target is not None:
self._drag_target.handle_mouse(
MouseEvent(MouseAction.RELEASE, event.position)
)
self._drag_target = None
if self._drag_target is not None:
return self._drag_target.handle_mouse(event)
selectables_index = 0
for widget in self._widgets:
if widget.contains(event.position):
handled = widget.handle_mouse(event)
if widget.selected_index is not None:
selectables_index += widget.selected_index
if event.action is MouseAction.LEFT_CLICK:
self._drag_target = widget
if handled:
self.select(selectables_index)
return handled
if widget.is_selectable:
selectables_index += widget.selectables_length
return False
def handle_key(self, key: str) -> bool:
"""Handles a keypress, returns its success.
Args:
key: A key str.
Returns:
A boolean showing whether the key was handled.
"""
def _is_nav(key: str) -> bool:
"""Determine if a key is in the navigation sets"""
return key in self.keys["next"] | self.keys["previous"]
if self.selected is not None and self.selected.handle_key(key):
return True
# Only use navigation when there is more than one selectable
if self.selectables_length > 1 and _is_nav(key):
handled = False
if self.selected_index is None:
self.select(0)
assert isinstance(self.selected_index, int)
if key in self.keys["previous"]:
# No more selectables left, user wants to exit Container
# upwards.
if self.selected_index == 0:
return False
self.select(self.selected_index - 1)
handled = True
elif key in self.keys["next"]:
# Stop selection at last element, return as unhandled
new = self.selected_index + 1
if new == len(self.selectables):
return False
self.select(new)
handled = True
if handled:
return True
if key == keys.ENTER and self.selected is not None:
if self.selected.selected_index is not None:
self.selected.handle_key(key)
return True
return False
def wipe(self) -> None:
"""Wipes the characters occupied by the object"""
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(real_length(line) * " ")
def print(self) -> None:
"""Prints this Container.
If the screen size has changed since last `print` call, the object
will be centered based on its `_centered_axis`.
"""
if not terminal.size == self._prev_screen:
clear()
self.center(self._centered_axis)
self._prev_screen = terminal.size
if self.allow_fullscreen:
self.pos = terminal.origin
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(line)
self._has_printed = True
def debug(self) -> str:
"""Returns a string with identifiable information on this widget.
Returns:
A str in the form of a class construction. This string is in a form that
__could have been__ used to create this Container.
"""
out = "Container("
for widget in self._widgets:
out += widget.debug() + ", "
out = out.strip(", ")
out += ", **attrs)"
return out
class Splitter(Container):
"""A widget that displays other widgets, stacked horizontally."""
chars: dict[str, list[str] | str] = {"separator": " | "}
styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND}
keys = {
"previous": {keys.LEFT, "h", keys.CTRL_B},
"next": {keys.RIGHT, "l", keys.CTRL_F},
}
parent_align = HorizontalAlignment.RIGHT
def _align(
self, alignment: HorizontalAlignment, target_width: int, line: str
) -> tuple[int, str]:
"""Align a line
r/wordavalanches"""
available = target_width - real_length(line)
fill_style = self._get_style("fill")
char = fill_style(" ")
line = fill_style(line)
if alignment == HorizontalAlignment.CENTER:
padding, offset = divmod(available, 2)
return padding, padding * char + line + (padding + offset) * char
if alignment == HorizontalAlignment.RIGHT:
return available, available * char + line
return 0, line + available * char
def get_lines(self) -> list[str]:
"""Join all widgets horizontally."""
# An error will be raised if `separator` is not the correct type (str).
separator = self._get_style("separator")(self._get_char("separator")) # type: ignore
separator_length = real_length(separator)
target_width, error = divmod(
self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets)
)
vertical_lines = []
total_offset = 0
for widget in self._widgets:
inner = []
if widget.size_policy is SizePolicy.STATIC:
target_width += target_width - widget.width
width = target_width
else:
widget.width = target_width + error
width = widget.width
error = 0
aligned: str | None = None
for line in widget.get_lines():
# See `enums.py` for information about this ignore
padding, aligned = self._align(
cast(HorizontalAlignment, widget.parent_align), width, line
)
inner.append(aligned)
widget.pos = (
self.pos[0] + padding + total_offset,
self.pos[1] + (1 if type(widget).__name__ == "Container" else 0),
)
if aligned is not None:
total_offset += real_length(inner[-1]) + separator_length
vertical_lines.append(inner)
lines = []
for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width):
lines.append((reset() + separator).join(horizontal))
return lines
def debug(self) -> str:
"""Return identifiable information"""
return super().debug().replace("Container", "Splitter", 1)
| bczsalba__pytermgui |
54 | 54-147-16 | infile | selected_index | [
"allow_fullscreen",
"bind",
"bindings",
"box",
"center",
"chars",
"contains",
"copy",
"debug",
"depth",
"execute_binding",
"get_lines",
"handle_key",
"handle_mouse",
"height",
"id",
"is_bindable",
"is_selectable",
"keys",
"parent",
"parent_align",
"pop",
"pos",
"print",
"remove",
"select",
"selectables",
"selectables_length",
"selected",
"selected_index",
"serialize",
"serialized",
"set_char",
"set_recursive_depth",
"set_style",
"set_widgets",
"sidelength",
"size_policy",
"static_width",
"styles",
"vertical_align",
"width",
"wipe",
"_add_widget",
"_apply_vertalign",
"_bindings",
"_box",
"_centered_axis",
"_drag_target",
"_get_aligners",
"_get_char",
"_get_style",
"_has_printed",
"_id",
"_id_manager",
"_prev_screen",
"_selectables_length",
"_serialized_fields",
"_update_width",
"_widgets",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__getitem__",
"__hash__",
"__iadd__",
"__init__",
"__init_subclass__",
"__iter__",
"__len__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__setitem__",
"__sizeof__",
"__slots__",
"__str__"
] | """The module containing all of the layout-related widgets."""
# These widgets have more than the 7 allowed instance attributes.
# pylint: disable=too-many-instance-attributes
from __future__ import annotations
from itertools import zip_longest
from typing import Any, Callable, Iterator, cast
from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal
from ..context_managers import cursor_at
from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment
from ..exceptions import WidthExceededError
from ..helpers import real_length
from ..input import keys
from . import boxes
from . import styles as w_styles
from .base import Widget
class Container(Widget):
"""A widget that displays other widgets, stacked vertically."""
chars: dict[str, w_styles.CharType] = {
"border": ["| ", "-", " |", "-"],
"corner": [""] * 4,
}
styles = {
"border": w_styles.MARKUP,
"corner": w_styles.MARKUP,
"fill": w_styles.BACKGROUND,
}
keys = {
"next": {keys.DOWN, keys.CTRL_N, "j"},
"previous": {keys.UP, keys.CTRL_P, "k"},
}
serialized = Widget.serialized + ["_centered_axis"]
vertical_align = VerticalAlignment.CENTER
allow_fullscreen = True
# TODO: Add `WidgetConvertible`? type instead of Any
def __init__(self, *widgets: Any, **attrs: Any) -> None:
"""Initialize Container data"""
super().__init__(**attrs)
# TODO: This is just a band-aid.
if "width" not in attrs:
self.width = 40
self._widgets: list[Widget] = []
self._centered_axis: CenteringPolicy | None = None
self._prev_screen: tuple[int, int] = (0, 0)
self._has_printed = False
self.styles = type(self).styles.copy()
self.chars = type(self).chars.copy()
for widget in widgets:
self._add_widget(widget)
self._drag_target: Widget | None = None
terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis))
@property
def sidelength(self) -> int:
"""Gets the length of left and right borders combined.
Returns:
An integer equal to the `pytermgui.helpers.real_length` of the concatenation of
the left and right borders of this widget, both with their respective styles
applied.
"""
chars = self._get_char("border")
style = self._get_style("border")
if not isinstance(chars, list):
return 0
left_border, _, right_border, _ = chars
return real_length(style(left_border) + style(right_border))
@property
def selectables(self) -> list[tuple[Widget, int]]:
"""Gets all selectable widgets and their inner indices.
This is used in order to have a constant reference to all selectable indices within this
widget.
Returns:
A list of tuples containing a widget and an integer each. For each widget that is
withing this one, it is added to this list as many times as it has selectables. Each
of the integers correspond to a selectable_index within the widget.
For example, a Container with a Button, InputField and an inner Container containing
3 selectables might return something like this:
```
[
(Button(...), 0),
(InputField(...), 0),
(Container(...), 0),
(Container(...), 1),
(Container(...), 2),
]
```
"""
_selectables: list[tuple[Widget, int]] = []
for widget in self._widgets:
if not widget.is_selectable:
continue
for i, (inner, _) in enumerate(widget.selectables):
_selectables.append((inner, i))
return _selectables
@property
def selectables_length(self) -> int:
"""Gets the length of the selectables list.
Returns:
An integer equal to the length of `self.selectables`.
"""
return len(self.selectables)
@property
def selected(self) -> Widget | None:
"""Returns the currently selected object
Returns:
The currently selected widget if selected_index is not None,
otherwise None.
"""
# TODO: Add deeper selection
if self.selected_index is None:
return None
if self. | >= len(self.selectables):
return None
return self.selectables[self.selected_index][0]
@property
def box(self) -> boxes.Box:
"""Returns current box setting
Returns:
The currently set box instance.
"""
return self._box
@box.setter
def box(self, new: str | boxes.Box) -> None:
"""Applies a new box.
Args:
new: Either a `pytermgui.boxes.Box` instance or a string
analogous to one of the default box names.
"""
if isinstance(new, str):
from_module = vars(boxes).get(new)
if from_module is None:
raise ValueError(f"Unknown box type {new}.")
new = from_module
assert isinstance(new, boxes.Box)
self._box = new
new.set_chars_of(self)
def __iadd__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self._add_widget(other)
return self
def __add__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
This method is analogous to `Container.__iadd__`.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self.__iadd__(other)
return self
def __iter__(self) -> Iterator[Widget]:
"""Gets an iterator of self._widgets.
Yields:
The next widget.
"""
for widget in self._widgets:
yield widget
def __len__(self) -> int:
"""Gets the length of the widgets list.
Returns:
An integer describing len(self._widgets).
"""
return len(self._widgets)
def __getitem__(self, sli: int | slice) -> Widget | list[Widget]:
"""Gets an item from self._widgets.
Args:
sli: Slice of the list.
Returns:
The slice in the list.
"""
return self._widgets[sli]
def __setitem__(self, index: int, value: Any) -> None:
"""Sets an item in self._widgets.
Args:
index: The index to be set.
value: The new widget at this index.
"""
self._widgets[index] = value
def __contains__(self, other: object) -> bool:
"""Determines if self._widgets contains other widget.
Args:
other: Any widget-like.
Returns:
A boolean describing whether `other` is in `self.widgets`
"""
return other in self._widgets
def _add_widget(self, other: object, run_get_lines: bool = True) -> None:
"""Adds other to this widget.
Args:
other: Any widget-like object.
run_get_lines: Boolean controlling whether the self.get_lines is ran.
"""
if not isinstance(other, Widget):
to_widget = Widget.from_data(other)
if to_widget is None:
raise ValueError(
f"Could not convert {other} of type {type(other)} to a Widget!"
)
other = to_widget
# This is safe to do, as it would've raised an exception above already
assert isinstance(other, Widget)
self._widgets.append(other)
if isinstance(other, Container):
other.set_recursive_depth(self.depth + 2)
else:
other.depth = self.depth + 1
other.get_lines()
other.parent = self
if run_get_lines:
self.get_lines()
def _get_aligners(
self, widget: Widget, borders: tuple[str, str]
) -> tuple[Callable[[str], str], int]:
"""Gets an aligning method and position offset.
Args:
widget: The widget to align.
borders: The left and right borders to put the widget within.
Returns:
A tuple of a method that, when called with a line, will return that line
centered using the passed in widget's parent_align and width, as well as
the horizontal offset resulting from the widget being aligned.
"""
left, right = borders
char = self._get_style("fill")(" ")
def _align_left(text: str) -> str:
"""Align line to the left"""
padding = self.width - real_length(left + right) - real_length(text)
return left + text + padding * char + right
def _align_center(text: str) -> str:
"""Align line to the center"""
total = self.width - real_length(left + right) - real_length(text)
padding, offset = divmod(total, 2)
return left + (padding + offset) * char + text + padding * char + right
def _align_right(text: str) -> str:
"""Align line to the right"""
padding = self.width - real_length(left + right) - real_length(text)
return left + padding * char + text + right
if widget.parent_align == HorizontalAlignment.CENTER:
total = self.width - real_length(left + right) - widget.width
padding, offset = divmod(total, 2)
return _align_center, real_length(left) + padding + offset
if widget.parent_align == HorizontalAlignment.RIGHT:
return _align_right, self.width - real_length(left) - widget.width
# Default to left-aligned
return _align_left, real_length(left)
def _update_width(self, widget: Widget) -> None:
"""Updates the width of widget or self.
This method respects widget.size_policy.
Args:
widget: The widget to update/base updates on.
"""
available = (
self.width - self.sidelength - (0 if isinstance(widget, Container) else 1)
)
if widget.size_policy == SizePolicy.FILL:
widget.width = available
return
if widget.size_policy == SizePolicy.RELATIVE:
widget.width = widget.relative_width * available
return
if widget.width > available:
if widget.size_policy == SizePolicy.STATIC:
raise WidthExceededError(
f"Widget {widget}'s static width of {widget.width}"
+ f" exceeds its parent's available width {available}."
""
)
widget.width = available
def _apply_vertalign(
self, lines: list[str], diff: int, padder: str
) -> tuple[int, list[str]]:
"""Insert padder line into lines diff times, depending on self.vertical_align.
Args:
lines: The list of lines to align.
diff: The available height.
padder: The line to use to pad.
Returns:
A tuple containing the vertical offset as well as the padded list of lines.
Raises:
NotImplementedError: The given vertical alignment is not implemented.
"""
if self.vertical_align == VerticalAlignment.BOTTOM:
for _ in range(diff):
lines.insert(0, padder)
return diff, lines
if self.vertical_align == VerticalAlignment.TOP:
for _ in range(diff):
lines.append(padder)
return 0, lines
if self.vertical_align == VerticalAlignment.CENTER:
top, extra = divmod(diff, 2)
bottom = top + extra
for _ in range(top):
lines.insert(0, padder)
for _ in range(bottom):
lines.append(padder)
return top, lines
raise NotImplementedError(
f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}."
)
def get_lines(self) -> list[str]:
"""Gets all lines by spacing out inner widgets.
This method reflects & applies both width settings, as well as
the `parent_align` field.
Returns:
A list of all lines that represent this Container.
"""
def _get_border(left: str, char: str, right: str) -> str:
"""Gets a top or bottom border.
Args:
left: Left corner character.
char: Border character filling between left & right.
right: Right corner character.
Returns:
The border line.
"""
offset = real_length(left + right)
return left + char * (self.width - offset) + right
lines = []
style = self._get_style("border")
borders = [style(char) for char in self._get_char("border")]
style = self._get_style("corner")
corners = [style(char) for char in self._get_char("corner")]
has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0)
align = lambda item: item
for widget in self._widgets:
align, offset = self._get_aligners(widget, (borders[0], borders[2]))
self._update_width(widget)
widget.pos = (
self.pos[0] + offset,
self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0),
)
widget_lines = []
for line in widget.get_lines():
widget_lines.append(align(line))
lines.extend(widget_lines)
vertical_offset, lines = self._apply_vertalign(
lines, self.height - len(lines) - sum(has_top_bottom), align("")
)
for widget in self._widgets:
widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset)
# TODO: This is wasteful.
widget.get_lines()
if has_top_bottom[0]:
lines.insert(0, _get_border(corners[0], borders[1], corners[1]))
if has_top_bottom[1]:
lines.append(_get_border(corners[3], borders[3], corners[2]))
self.height = len(lines)
return lines
def set_widgets(self, new: list[Widget]) -> None:
"""Sets new list in place of self._widgets.
Args:
new: The new widget list.
"""
self._widgets = []
for widget in new:
self._add_widget(widget)
def serialize(self) -> dict[str, Any]:
"""Serializes this Container, adding in serializations of all widgets.
See `pytermgui.widgets.base.Widget.serialize` for more info.
Returns:
The dictionary containing all serialized data.
"""
out = super().serialize()
out["_widgets"] = []
for widget in self._widgets:
out["_widgets"].append(widget.serialize())
return out
def pop(self, index: int = -1) -> Widget:
"""Pops widget from self._widgets.
Analogous to self._widgets.pop(index).
Args:
index: The index to operate on.
Returns:
The widget that was popped off the list.
"""
return self._widgets.pop(index)
def remove(self, other: Widget) -> None:
"""Remove widget from self._widgets
Analogous to self._widgets.remove(other).
Args:
widget: The widget to remove.
"""
return self._widgets.remove(other)
def set_recursive_depth(self, value: int) -> None:
"""Set depth for this Container and all its children.
All inner widgets will receive value+1 as their new depth.
Args:
value: The new depth to use as the base depth.
"""
self.depth = value
for widget in self._widgets:
if isinstance(widget, Container):
widget.set_recursive_depth(value + 1)
else:
widget.depth = value
def select(self, index: int | None = None) -> None:
"""Selects inner subwidget.
Args:
index: The index to select.
Raises:
IndexError: The index provided was beyond len(self.selectables).
"""
# Unselect all sub-elements
for other in self._widgets:
if other.selectables_length > 0:
other.select(None)
if index is not None:
if index >= len(self.selectables) is None:
raise IndexError("Container selection index out of range")
widget, inner_index = self.selectables[index]
widget.select(inner_index)
self.selected_index = index
def center(
self, where: CenteringPolicy | None = None, store: bool = True
) -> Container:
"""Centers this object to the given axis.
Args:
where: A CenteringPolicy describing the place to center to
store: When set, this centering will be reapplied during every
print, as well as when calling this method with no arguments.
Returns:
This Container.
"""
# Refresh in case changes happened
self.get_lines()
if where is None:
# See `enums.py` for explanation about this ignore.
where = CenteringPolicy.get_default() # type: ignore
centerx = centery = where is CenteringPolicy.ALL
centerx |= where is CenteringPolicy.HORIZONTAL
centery |= where is CenteringPolicy.VERTICAL
pos = list(self.pos)
if centerx:
pos[0] = (terminal.width - self.width + 2) // 2
if centery:
pos[1] = (terminal.height - self.height + 2) // 2
self.pos = (pos[0], pos[1])
if store:
self._centered_axis = where
self._prev_screen = terminal.size
return self
def handle_mouse(self, event: MouseEvent) -> bool:
"""Applies a mouse event on all children.
Args:
event: The event to handle
Returns:
A boolean showing whether the event was handled.
"""
if event.action is MouseAction.RELEASE:
# Force RELEASE event to be sent
if self._drag_target is not None:
self._drag_target.handle_mouse(
MouseEvent(MouseAction.RELEASE, event.position)
)
self._drag_target = None
if self._drag_target is not None:
return self._drag_target.handle_mouse(event)
selectables_index = 0
for widget in self._widgets:
if widget.contains(event.position):
handled = widget.handle_mouse(event)
if widget.selected_index is not None:
selectables_index += widget.selected_index
if event.action is MouseAction.LEFT_CLICK:
self._drag_target = widget
if handled:
self.select(selectables_index)
return handled
if widget.is_selectable:
selectables_index += widget.selectables_length
return False
def handle_key(self, key: str) -> bool:
"""Handles a keypress, returns its success.
Args:
key: A key str.
Returns:
A boolean showing whether the key was handled.
"""
def _is_nav(key: str) -> bool:
"""Determine if a key is in the navigation sets"""
return key in self.keys["next"] | self.keys["previous"]
if self.selected is not None and self.selected.handle_key(key):
return True
# Only use navigation when there is more than one selectable
if self.selectables_length > 1 and _is_nav(key):
handled = False
if self.selected_index is None:
self.select(0)
assert isinstance(self.selected_index, int)
if key in self.keys["previous"]:
# No more selectables left, user wants to exit Container
# upwards.
if self.selected_index == 0:
return False
self.select(self.selected_index - 1)
handled = True
elif key in self.keys["next"]:
# Stop selection at last element, return as unhandled
new = self.selected_index + 1
if new == len(self.selectables):
return False
self.select(new)
handled = True
if handled:
return True
if key == keys.ENTER and self.selected is not None:
if self.selected.selected_index is not None:
self.selected.handle_key(key)
return True
return False
def wipe(self) -> None:
"""Wipes the characters occupied by the object"""
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(real_length(line) * " ")
def print(self) -> None:
"""Prints this Container.
If the screen size has changed since last `print` call, the object
will be centered based on its `_centered_axis`.
"""
if not terminal.size == self._prev_screen:
clear()
self.center(self._centered_axis)
self._prev_screen = terminal.size
if self.allow_fullscreen:
self.pos = terminal.origin
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(line)
self._has_printed = True
def debug(self) -> str:
"""Returns a string with identifiable information on this widget.
Returns:
A str in the form of a class construction. This string is in a form that
__could have been__ used to create this Container.
"""
out = "Container("
for widget in self._widgets:
out += widget.debug() + ", "
out = out.strip(", ")
out += ", **attrs)"
return out
class Splitter(Container):
"""A widget that displays other widgets, stacked horizontally."""
chars: dict[str, list[str] | str] = {"separator": " | "}
styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND}
keys = {
"previous": {keys.LEFT, "h", keys.CTRL_B},
"next": {keys.RIGHT, "l", keys.CTRL_F},
}
parent_align = HorizontalAlignment.RIGHT
def _align(
self, alignment: HorizontalAlignment, target_width: int, line: str
) -> tuple[int, str]:
"""Align a line
r/wordavalanches"""
available = target_width - real_length(line)
fill_style = self._get_style("fill")
char = fill_style(" ")
line = fill_style(line)
if alignment == HorizontalAlignment.CENTER:
padding, offset = divmod(available, 2)
return padding, padding * char + line + (padding + offset) * char
if alignment == HorizontalAlignment.RIGHT:
return available, available * char + line
return 0, line + available * char
def get_lines(self) -> list[str]:
"""Join all widgets horizontally."""
# An error will be raised if `separator` is not the correct type (str).
separator = self._get_style("separator")(self._get_char("separator")) # type: ignore
separator_length = real_length(separator)
target_width, error = divmod(
self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets)
)
vertical_lines = []
total_offset = 0
for widget in self._widgets:
inner = []
if widget.size_policy is SizePolicy.STATIC:
target_width += target_width - widget.width
width = target_width
else:
widget.width = target_width + error
width = widget.width
error = 0
aligned: str | None = None
for line in widget.get_lines():
# See `enums.py` for information about this ignore
padding, aligned = self._align(
cast(HorizontalAlignment, widget.parent_align), width, line
)
inner.append(aligned)
widget.pos = (
self.pos[0] + padding + total_offset,
self.pos[1] + (1 if type(widget).__name__ == "Container" else 0),
)
if aligned is not None:
total_offset += real_length(inner[-1]) + separator_length
vertical_lines.append(inner)
lines = []
for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width):
lines.append((reset() + separator).join(horizontal))
return lines
def debug(self) -> str:
"""Return identifiable information"""
return super().debug().replace("Container", "Splitter", 1)
| bczsalba__pytermgui |
54 | 54-147-43 | infile | selectables | [
"allow_fullscreen",
"bind",
"bindings",
"box",
"center",
"chars",
"contains",
"copy",
"debug",
"depth",
"execute_binding",
"get_lines",
"handle_key",
"handle_mouse",
"height",
"id",
"is_bindable",
"is_selectable",
"keys",
"parent",
"parent_align",
"pop",
"pos",
"print",
"remove",
"select",
"selectables",
"selectables_length",
"selected",
"selected_index",
"serialize",
"serialized",
"set_char",
"set_recursive_depth",
"set_style",
"set_widgets",
"sidelength",
"size_policy",
"static_width",
"styles",
"vertical_align",
"width",
"wipe",
"_add_widget",
"_apply_vertalign",
"_bindings",
"_box",
"_centered_axis",
"_drag_target",
"_get_aligners",
"_get_char",
"_get_style",
"_has_printed",
"_id",
"_id_manager",
"_prev_screen",
"_selectables_length",
"_serialized_fields",
"_update_width",
"_widgets",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__getitem__",
"__hash__",
"__iadd__",
"__init__",
"__init_subclass__",
"__iter__",
"__len__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__setitem__",
"__sizeof__",
"__slots__",
"__str__"
] | """The module containing all of the layout-related widgets."""
# These widgets have more than the 7 allowed instance attributes.
# pylint: disable=too-many-instance-attributes
from __future__ import annotations
from itertools import zip_longest
from typing import Any, Callable, Iterator, cast
from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal
from ..context_managers import cursor_at
from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment
from ..exceptions import WidthExceededError
from ..helpers import real_length
from ..input import keys
from . import boxes
from . import styles as w_styles
from .base import Widget
class Container(Widget):
"""A widget that displays other widgets, stacked vertically."""
chars: dict[str, w_styles.CharType] = {
"border": ["| ", "-", " |", "-"],
"corner": [""] * 4,
}
styles = {
"border": w_styles.MARKUP,
"corner": w_styles.MARKUP,
"fill": w_styles.BACKGROUND,
}
keys = {
"next": {keys.DOWN, keys.CTRL_N, "j"},
"previous": {keys.UP, keys.CTRL_P, "k"},
}
serialized = Widget.serialized + ["_centered_axis"]
vertical_align = VerticalAlignment.CENTER
allow_fullscreen = True
# TODO: Add `WidgetConvertible`? type instead of Any
def __init__(self, *widgets: Any, **attrs: Any) -> None:
"""Initialize Container data"""
super().__init__(**attrs)
# TODO: This is just a band-aid.
if "width" not in attrs:
self.width = 40
self._widgets: list[Widget] = []
self._centered_axis: CenteringPolicy | None = None
self._prev_screen: tuple[int, int] = (0, 0)
self._has_printed = False
self.styles = type(self).styles.copy()
self.chars = type(self).chars.copy()
for widget in widgets:
self._add_widget(widget)
self._drag_target: Widget | None = None
terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis))
@property
def sidelength(self) -> int:
"""Gets the length of left and right borders combined.
Returns:
An integer equal to the `pytermgui.helpers.real_length` of the concatenation of
the left and right borders of this widget, both with their respective styles
applied.
"""
chars = self._get_char("border")
style = self._get_style("border")
if not isinstance(chars, list):
return 0
left_border, _, right_border, _ = chars
return real_length(style(left_border) + style(right_border))
@property
def selectables(self) -> list[tuple[Widget, int]]:
"""Gets all selectable widgets and their inner indices.
This is used in order to have a constant reference to all selectable indices within this
widget.
Returns:
A list of tuples containing a widget and an integer each. For each widget that is
withing this one, it is added to this list as many times as it has selectables. Each
of the integers correspond to a selectable_index within the widget.
For example, a Container with a Button, InputField and an inner Container containing
3 selectables might return something like this:
```
[
(Button(...), 0),
(InputField(...), 0),
(Container(...), 0),
(Container(...), 1),
(Container(...), 2),
]
```
"""
_selectables: list[tuple[Widget, int]] = []
for widget in self._widgets:
if not widget.is_selectable:
continue
for i, (inner, _) in enumerate(widget.selectables):
_selectables.append((inner, i))
return _selectables
@property
def selectables_length(self) -> int:
"""Gets the length of the selectables list.
Returns:
An integer equal to the length of `self.selectables`.
"""
return len(self.selectables)
@property
def selected(self) -> Widget | None:
"""Returns the currently selected object
Returns:
The currently selected widget if selected_index is not None,
otherwise None.
"""
# TODO: Add deeper selection
if self.selected_index is None:
return None
if self.selected_index >= len(self. | ):
return None
return self.selectables[self.selected_index][0]
@property
def box(self) -> boxes.Box:
"""Returns current box setting
Returns:
The currently set box instance.
"""
return self._box
@box.setter
def box(self, new: str | boxes.Box) -> None:
"""Applies a new box.
Args:
new: Either a `pytermgui.boxes.Box` instance or a string
analogous to one of the default box names.
"""
if isinstance(new, str):
from_module = vars(boxes).get(new)
if from_module is None:
raise ValueError(f"Unknown box type {new}.")
new = from_module
assert isinstance(new, boxes.Box)
self._box = new
new.set_chars_of(self)
def __iadd__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self._add_widget(other)
return self
def __add__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
This method is analogous to `Container.__iadd__`.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self.__iadd__(other)
return self
def __iter__(self) -> Iterator[Widget]:
"""Gets an iterator of self._widgets.
Yields:
The next widget.
"""
for widget in self._widgets:
yield widget
def __len__(self) -> int:
"""Gets the length of the widgets list.
Returns:
An integer describing len(self._widgets).
"""
return len(self._widgets)
def __getitem__(self, sli: int | slice) -> Widget | list[Widget]:
"""Gets an item from self._widgets.
Args:
sli: Slice of the list.
Returns:
The slice in the list.
"""
return self._widgets[sli]
def __setitem__(self, index: int, value: Any) -> None:
"""Sets an item in self._widgets.
Args:
index: The index to be set.
value: The new widget at this index.
"""
self._widgets[index] = value
def __contains__(self, other: object) -> bool:
"""Determines if self._widgets contains other widget.
Args:
other: Any widget-like.
Returns:
A boolean describing whether `other` is in `self.widgets`
"""
return other in self._widgets
def _add_widget(self, other: object, run_get_lines: bool = True) -> None:
"""Adds other to this widget.
Args:
other: Any widget-like object.
run_get_lines: Boolean controlling whether the self.get_lines is ran.
"""
if not isinstance(other, Widget):
to_widget = Widget.from_data(other)
if to_widget is None:
raise ValueError(
f"Could not convert {other} of type {type(other)} to a Widget!"
)
other = to_widget
# This is safe to do, as it would've raised an exception above already
assert isinstance(other, Widget)
self._widgets.append(other)
if isinstance(other, Container):
other.set_recursive_depth(self.depth + 2)
else:
other.depth = self.depth + 1
other.get_lines()
other.parent = self
if run_get_lines:
self.get_lines()
def _get_aligners(
self, widget: Widget, borders: tuple[str, str]
) -> tuple[Callable[[str], str], int]:
"""Gets an aligning method and position offset.
Args:
widget: The widget to align.
borders: The left and right borders to put the widget within.
Returns:
A tuple of a method that, when called with a line, will return that line
centered using the passed in widget's parent_align and width, as well as
the horizontal offset resulting from the widget being aligned.
"""
left, right = borders
char = self._get_style("fill")(" ")
def _align_left(text: str) -> str:
"""Align line to the left"""
padding = self.width - real_length(left + right) - real_length(text)
return left + text + padding * char + right
def _align_center(text: str) -> str:
"""Align line to the center"""
total = self.width - real_length(left + right) - real_length(text)
padding, offset = divmod(total, 2)
return left + (padding + offset) * char + text + padding * char + right
def _align_right(text: str) -> str:
"""Align line to the right"""
padding = self.width - real_length(left + right) - real_length(text)
return left + padding * char + text + right
if widget.parent_align == HorizontalAlignment.CENTER:
total = self.width - real_length(left + right) - widget.width
padding, offset = divmod(total, 2)
return _align_center, real_length(left) + padding + offset
if widget.parent_align == HorizontalAlignment.RIGHT:
return _align_right, self.width - real_length(left) - widget.width
# Default to left-aligned
return _align_left, real_length(left)
def _update_width(self, widget: Widget) -> None:
"""Updates the width of widget or self.
This method respects widget.size_policy.
Args:
widget: The widget to update/base updates on.
"""
available = (
self.width - self.sidelength - (0 if isinstance(widget, Container) else 1)
)
if widget.size_policy == SizePolicy.FILL:
widget.width = available
return
if widget.size_policy == SizePolicy.RELATIVE:
widget.width = widget.relative_width * available
return
if widget.width > available:
if widget.size_policy == SizePolicy.STATIC:
raise WidthExceededError(
f"Widget {widget}'s static width of {widget.width}"
+ f" exceeds its parent's available width {available}."
""
)
widget.width = available
def _apply_vertalign(
self, lines: list[str], diff: int, padder: str
) -> tuple[int, list[str]]:
"""Insert padder line into lines diff times, depending on self.vertical_align.
Args:
lines: The list of lines to align.
diff: The available height.
padder: The line to use to pad.
Returns:
A tuple containing the vertical offset as well as the padded list of lines.
Raises:
NotImplementedError: The given vertical alignment is not implemented.
"""
if self.vertical_align == VerticalAlignment.BOTTOM:
for _ in range(diff):
lines.insert(0, padder)
return diff, lines
if self.vertical_align == VerticalAlignment.TOP:
for _ in range(diff):
lines.append(padder)
return 0, lines
if self.vertical_align == VerticalAlignment.CENTER:
top, extra = divmod(diff, 2)
bottom = top + extra
for _ in range(top):
lines.insert(0, padder)
for _ in range(bottom):
lines.append(padder)
return top, lines
raise NotImplementedError(
f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}."
)
def get_lines(self) -> list[str]:
"""Gets all lines by spacing out inner widgets.
This method reflects & applies both width settings, as well as
the `parent_align` field.
Returns:
A list of all lines that represent this Container.
"""
def _get_border(left: str, char: str, right: str) -> str:
"""Gets a top or bottom border.
Args:
left: Left corner character.
char: Border character filling between left & right.
right: Right corner character.
Returns:
The border line.
"""
offset = real_length(left + right)
return left + char * (self.width - offset) + right
lines = []
style = self._get_style("border")
borders = [style(char) for char in self._get_char("border")]
style = self._get_style("corner")
corners = [style(char) for char in self._get_char("corner")]
has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0)
align = lambda item: item
for widget in self._widgets:
align, offset = self._get_aligners(widget, (borders[0], borders[2]))
self._update_width(widget)
widget.pos = (
self.pos[0] + offset,
self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0),
)
widget_lines = []
for line in widget.get_lines():
widget_lines.append(align(line))
lines.extend(widget_lines)
vertical_offset, lines = self._apply_vertalign(
lines, self.height - len(lines) - sum(has_top_bottom), align("")
)
for widget in self._widgets:
widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset)
# TODO: This is wasteful.
widget.get_lines()
if has_top_bottom[0]:
lines.insert(0, _get_border(corners[0], borders[1], corners[1]))
if has_top_bottom[1]:
lines.append(_get_border(corners[3], borders[3], corners[2]))
self.height = len(lines)
return lines
def set_widgets(self, new: list[Widget]) -> None:
"""Sets new list in place of self._widgets.
Args:
new: The new widget list.
"""
self._widgets = []
for widget in new:
self._add_widget(widget)
def serialize(self) -> dict[str, Any]:
"""Serializes this Container, adding in serializations of all widgets.
See `pytermgui.widgets.base.Widget.serialize` for more info.
Returns:
The dictionary containing all serialized data.
"""
out = super().serialize()
out["_widgets"] = []
for widget in self._widgets:
out["_widgets"].append(widget.serialize())
return out
def pop(self, index: int = -1) -> Widget:
"""Pops widget from self._widgets.
Analogous to self._widgets.pop(index).
Args:
index: The index to operate on.
Returns:
The widget that was popped off the list.
"""
return self._widgets.pop(index)
def remove(self, other: Widget) -> None:
"""Remove widget from self._widgets
Analogous to self._widgets.remove(other).
Args:
widget: The widget to remove.
"""
return self._widgets.remove(other)
def set_recursive_depth(self, value: int) -> None:
"""Set depth for this Container and all its children.
All inner widgets will receive value+1 as their new depth.
Args:
value: The new depth to use as the base depth.
"""
self.depth = value
for widget in self._widgets:
if isinstance(widget, Container):
widget.set_recursive_depth(value + 1)
else:
widget.depth = value
def select(self, index: int | None = None) -> None:
"""Selects inner subwidget.
Args:
index: The index to select.
Raises:
IndexError: The index provided was beyond len(self.selectables).
"""
# Unselect all sub-elements
for other in self._widgets:
if other.selectables_length > 0:
other.select(None)
if index is not None:
if index >= len(self.selectables) is None:
raise IndexError("Container selection index out of range")
widget, inner_index = self.selectables[index]
widget.select(inner_index)
self.selected_index = index
def center(
self, where: CenteringPolicy | None = None, store: bool = True
) -> Container:
"""Centers this object to the given axis.
Args:
where: A CenteringPolicy describing the place to center to
store: When set, this centering will be reapplied during every
print, as well as when calling this method with no arguments.
Returns:
This Container.
"""
# Refresh in case changes happened
self.get_lines()
if where is None:
# See `enums.py` for explanation about this ignore.
where = CenteringPolicy.get_default() # type: ignore
centerx = centery = where is CenteringPolicy.ALL
centerx |= where is CenteringPolicy.HORIZONTAL
centery |= where is CenteringPolicy.VERTICAL
pos = list(self.pos)
if centerx:
pos[0] = (terminal.width - self.width + 2) // 2
if centery:
pos[1] = (terminal.height - self.height + 2) // 2
self.pos = (pos[0], pos[1])
if store:
self._centered_axis = where
self._prev_screen = terminal.size
return self
def handle_mouse(self, event: MouseEvent) -> bool:
"""Applies a mouse event on all children.
Args:
event: The event to handle
Returns:
A boolean showing whether the event was handled.
"""
if event.action is MouseAction.RELEASE:
# Force RELEASE event to be sent
if self._drag_target is not None:
self._drag_target.handle_mouse(
MouseEvent(MouseAction.RELEASE, event.position)
)
self._drag_target = None
if self._drag_target is not None:
return self._drag_target.handle_mouse(event)
selectables_index = 0
for widget in self._widgets:
if widget.contains(event.position):
handled = widget.handle_mouse(event)
if widget.selected_index is not None:
selectables_index += widget.selected_index
if event.action is MouseAction.LEFT_CLICK:
self._drag_target = widget
if handled:
self.select(selectables_index)
return handled
if widget.is_selectable:
selectables_index += widget.selectables_length
return False
def handle_key(self, key: str) -> bool:
"""Handles a keypress, returns its success.
Args:
key: A key str.
Returns:
A boolean showing whether the key was handled.
"""
def _is_nav(key: str) -> bool:
"""Determine if a key is in the navigation sets"""
return key in self.keys["next"] | self.keys["previous"]
if self.selected is not None and self.selected.handle_key(key):
return True
# Only use navigation when there is more than one selectable
if self.selectables_length > 1 and _is_nav(key):
handled = False
if self.selected_index is None:
self.select(0)
assert isinstance(self.selected_index, int)
if key in self.keys["previous"]:
# No more selectables left, user wants to exit Container
# upwards.
if self.selected_index == 0:
return False
self.select(self.selected_index - 1)
handled = True
elif key in self.keys["next"]:
# Stop selection at last element, return as unhandled
new = self.selected_index + 1
if new == len(self.selectables):
return False
self.select(new)
handled = True
if handled:
return True
if key == keys.ENTER and self.selected is not None:
if self.selected.selected_index is not None:
self.selected.handle_key(key)
return True
return False
def wipe(self) -> None:
"""Wipes the characters occupied by the object"""
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(real_length(line) * " ")
def print(self) -> None:
"""Prints this Container.
If the screen size has changed since last `print` call, the object
will be centered based on its `_centered_axis`.
"""
if not terminal.size == self._prev_screen:
clear()
self.center(self._centered_axis)
self._prev_screen = terminal.size
if self.allow_fullscreen:
self.pos = terminal.origin
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(line)
self._has_printed = True
def debug(self) -> str:
"""Returns a string with identifiable information on this widget.
Returns:
A str in the form of a class construction. This string is in a form that
__could have been__ used to create this Container.
"""
out = "Container("
for widget in self._widgets:
out += widget.debug() + ", "
out = out.strip(", ")
out += ", **attrs)"
return out
class Splitter(Container):
"""A widget that displays other widgets, stacked horizontally."""
chars: dict[str, list[str] | str] = {"separator": " | "}
styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND}
keys = {
"previous": {keys.LEFT, "h", keys.CTRL_B},
"next": {keys.RIGHT, "l", keys.CTRL_F},
}
parent_align = HorizontalAlignment.RIGHT
def _align(
self, alignment: HorizontalAlignment, target_width: int, line: str
) -> tuple[int, str]:
"""Align a line
r/wordavalanches"""
available = target_width - real_length(line)
fill_style = self._get_style("fill")
char = fill_style(" ")
line = fill_style(line)
if alignment == HorizontalAlignment.CENTER:
padding, offset = divmod(available, 2)
return padding, padding * char + line + (padding + offset) * char
if alignment == HorizontalAlignment.RIGHT:
return available, available * char + line
return 0, line + available * char
def get_lines(self) -> list[str]:
"""Join all widgets horizontally."""
# An error will be raised if `separator` is not the correct type (str).
separator = self._get_style("separator")(self._get_char("separator")) # type: ignore
separator_length = real_length(separator)
target_width, error = divmod(
self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets)
)
vertical_lines = []
total_offset = 0
for widget in self._widgets:
inner = []
if widget.size_policy is SizePolicy.STATIC:
target_width += target_width - widget.width
width = target_width
else:
widget.width = target_width + error
width = widget.width
error = 0
aligned: str | None = None
for line in widget.get_lines():
# See `enums.py` for information about this ignore
padding, aligned = self._align(
cast(HorizontalAlignment, widget.parent_align), width, line
)
inner.append(aligned)
widget.pos = (
self.pos[0] + padding + total_offset,
self.pos[1] + (1 if type(widget).__name__ == "Container" else 0),
)
if aligned is not None:
total_offset += real_length(inner[-1]) + separator_length
vertical_lines.append(inner)
lines = []
for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width):
lines.append((reset() + separator).join(horizontal))
return lines
def debug(self) -> str:
"""Return identifiable information"""
return super().debug().replace("Container", "Splitter", 1)
| bczsalba__pytermgui |
54 | 54-150-20 | infile | selectables | [
"allow_fullscreen",
"bind",
"bindings",
"box",
"center",
"chars",
"contains",
"copy",
"debug",
"depth",
"execute_binding",
"get_lines",
"handle_key",
"handle_mouse",
"height",
"id",
"is_bindable",
"is_selectable",
"keys",
"parent",
"parent_align",
"pop",
"pos",
"print",
"remove",
"select",
"selectables",
"selectables_length",
"selected",
"selected_index",
"serialize",
"serialized",
"set_char",
"set_recursive_depth",
"set_style",
"set_widgets",
"sidelength",
"size_policy",
"static_width",
"styles",
"vertical_align",
"width",
"wipe",
"_add_widget",
"_apply_vertalign",
"_bindings",
"_box",
"_centered_axis",
"_drag_target",
"_get_aligners",
"_get_char",
"_get_style",
"_has_printed",
"_id",
"_id_manager",
"_prev_screen",
"_selectables_length",
"_serialized_fields",
"_update_width",
"_widgets",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__getitem__",
"__hash__",
"__iadd__",
"__init__",
"__init_subclass__",
"__iter__",
"__len__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__setitem__",
"__sizeof__",
"__slots__",
"__str__"
] | """The module containing all of the layout-related widgets."""
# These widgets have more than the 7 allowed instance attributes.
# pylint: disable=too-many-instance-attributes
from __future__ import annotations
from itertools import zip_longest
from typing import Any, Callable, Iterator, cast
from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal
from ..context_managers import cursor_at
from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment
from ..exceptions import WidthExceededError
from ..helpers import real_length
from ..input import keys
from . import boxes
from . import styles as w_styles
from .base import Widget
class Container(Widget):
"""A widget that displays other widgets, stacked vertically."""
chars: dict[str, w_styles.CharType] = {
"border": ["| ", "-", " |", "-"],
"corner": [""] * 4,
}
styles = {
"border": w_styles.MARKUP,
"corner": w_styles.MARKUP,
"fill": w_styles.BACKGROUND,
}
keys = {
"next": {keys.DOWN, keys.CTRL_N, "j"},
"previous": {keys.UP, keys.CTRL_P, "k"},
}
serialized = Widget.serialized + ["_centered_axis"]
vertical_align = VerticalAlignment.CENTER
allow_fullscreen = True
# TODO: Add `WidgetConvertible`? type instead of Any
def __init__(self, *widgets: Any, **attrs: Any) -> None:
"""Initialize Container data"""
super().__init__(**attrs)
# TODO: This is just a band-aid.
if "width" not in attrs:
self.width = 40
self._widgets: list[Widget] = []
self._centered_axis: CenteringPolicy | None = None
self._prev_screen: tuple[int, int] = (0, 0)
self._has_printed = False
self.styles = type(self).styles.copy()
self.chars = type(self).chars.copy()
for widget in widgets:
self._add_widget(widget)
self._drag_target: Widget | None = None
terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis))
@property
def sidelength(self) -> int:
"""Gets the length of left and right borders combined.
Returns:
An integer equal to the `pytermgui.helpers.real_length` of the concatenation of
the left and right borders of this widget, both with their respective styles
applied.
"""
chars = self._get_char("border")
style = self._get_style("border")
if not isinstance(chars, list):
return 0
left_border, _, right_border, _ = chars
return real_length(style(left_border) + style(right_border))
@property
def selectables(self) -> list[tuple[Widget, int]]:
"""Gets all selectable widgets and their inner indices.
This is used in order to have a constant reference to all selectable indices within this
widget.
Returns:
A list of tuples containing a widget and an integer each. For each widget that is
withing this one, it is added to this list as many times as it has selectables. Each
of the integers correspond to a selectable_index within the widget.
For example, a Container with a Button, InputField and an inner Container containing
3 selectables might return something like this:
```
[
(Button(...), 0),
(InputField(...), 0),
(Container(...), 0),
(Container(...), 1),
(Container(...), 2),
]
```
"""
_selectables: list[tuple[Widget, int]] = []
for widget in self._widgets:
if not widget.is_selectable:
continue
for i, (inner, _) in enumerate(widget.selectables):
_selectables.append((inner, i))
return _selectables
@property
def selectables_length(self) -> int:
"""Gets the length of the selectables list.
Returns:
An integer equal to the length of `self.selectables`.
"""
return len(self.selectables)
@property
def selected(self) -> Widget | None:
"""Returns the currently selected object
Returns:
The currently selected widget if selected_index is not None,
otherwise None.
"""
# TODO: Add deeper selection
if self.selected_index is None:
return None
if self.selected_index >= len(self.selectables):
return None
return self. | [self.selected_index][0]
@property
def box(self) -> boxes.Box:
"""Returns current box setting
Returns:
The currently set box instance.
"""
return self._box
@box.setter
def box(self, new: str | boxes.Box) -> None:
"""Applies a new box.
Args:
new: Either a `pytermgui.boxes.Box` instance or a string
analogous to one of the default box names.
"""
if isinstance(new, str):
from_module = vars(boxes).get(new)
if from_module is None:
raise ValueError(f"Unknown box type {new}.")
new = from_module
assert isinstance(new, boxes.Box)
self._box = new
new.set_chars_of(self)
def __iadd__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self._add_widget(other)
return self
def __add__(self, other: object) -> Container:
"""Adds a new widget, then returns self.
This method is analogous to `Container.__iadd__`.
Args:
other: Any widget instance, or data structure that can be turned
into a widget by `Widget.from_data`.
Returns:
A reference to self.
"""
self.__iadd__(other)
return self
def __iter__(self) -> Iterator[Widget]:
"""Gets an iterator of self._widgets.
Yields:
The next widget.
"""
for widget in self._widgets:
yield widget
def __len__(self) -> int:
"""Gets the length of the widgets list.
Returns:
An integer describing len(self._widgets).
"""
return len(self._widgets)
def __getitem__(self, sli: int | slice) -> Widget | list[Widget]:
"""Gets an item from self._widgets.
Args:
sli: Slice of the list.
Returns:
The slice in the list.
"""
return self._widgets[sli]
def __setitem__(self, index: int, value: Any) -> None:
"""Sets an item in self._widgets.
Args:
index: The index to be set.
value: The new widget at this index.
"""
self._widgets[index] = value
def __contains__(self, other: object) -> bool:
"""Determines if self._widgets contains other widget.
Args:
other: Any widget-like.
Returns:
A boolean describing whether `other` is in `self.widgets`
"""
return other in self._widgets
def _add_widget(self, other: object, run_get_lines: bool = True) -> None:
"""Adds other to this widget.
Args:
other: Any widget-like object.
run_get_lines: Boolean controlling whether the self.get_lines is ran.
"""
if not isinstance(other, Widget):
to_widget = Widget.from_data(other)
if to_widget is None:
raise ValueError(
f"Could not convert {other} of type {type(other)} to a Widget!"
)
other = to_widget
# This is safe to do, as it would've raised an exception above already
assert isinstance(other, Widget)
self._widgets.append(other)
if isinstance(other, Container):
other.set_recursive_depth(self.depth + 2)
else:
other.depth = self.depth + 1
other.get_lines()
other.parent = self
if run_get_lines:
self.get_lines()
def _get_aligners(
self, widget: Widget, borders: tuple[str, str]
) -> tuple[Callable[[str], str], int]:
"""Gets an aligning method and position offset.
Args:
widget: The widget to align.
borders: The left and right borders to put the widget within.
Returns:
A tuple of a method that, when called with a line, will return that line
centered using the passed in widget's parent_align and width, as well as
the horizontal offset resulting from the widget being aligned.
"""
left, right = borders
char = self._get_style("fill")(" ")
def _align_left(text: str) -> str:
"""Align line to the left"""
padding = self.width - real_length(left + right) - real_length(text)
return left + text + padding * char + right
def _align_center(text: str) -> str:
"""Align line to the center"""
total = self.width - real_length(left + right) - real_length(text)
padding, offset = divmod(total, 2)
return left + (padding + offset) * char + text + padding * char + right
def _align_right(text: str) -> str:
"""Align line to the right"""
padding = self.width - real_length(left + right) - real_length(text)
return left + padding * char + text + right
if widget.parent_align == HorizontalAlignment.CENTER:
total = self.width - real_length(left + right) - widget.width
padding, offset = divmod(total, 2)
return _align_center, real_length(left) + padding + offset
if widget.parent_align == HorizontalAlignment.RIGHT:
return _align_right, self.width - real_length(left) - widget.width
# Default to left-aligned
return _align_left, real_length(left)
def _update_width(self, widget: Widget) -> None:
"""Updates the width of widget or self.
This method respects widget.size_policy.
Args:
widget: The widget to update/base updates on.
"""
available = (
self.width - self.sidelength - (0 if isinstance(widget, Container) else 1)
)
if widget.size_policy == SizePolicy.FILL:
widget.width = available
return
if widget.size_policy == SizePolicy.RELATIVE:
widget.width = widget.relative_width * available
return
if widget.width > available:
if widget.size_policy == SizePolicy.STATIC:
raise WidthExceededError(
f"Widget {widget}'s static width of {widget.width}"
+ f" exceeds its parent's available width {available}."
""
)
widget.width = available
def _apply_vertalign(
self, lines: list[str], diff: int, padder: str
) -> tuple[int, list[str]]:
"""Insert padder line into lines diff times, depending on self.vertical_align.
Args:
lines: The list of lines to align.
diff: The available height.
padder: The line to use to pad.
Returns:
A tuple containing the vertical offset as well as the padded list of lines.
Raises:
NotImplementedError: The given vertical alignment is not implemented.
"""
if self.vertical_align == VerticalAlignment.BOTTOM:
for _ in range(diff):
lines.insert(0, padder)
return diff, lines
if self.vertical_align == VerticalAlignment.TOP:
for _ in range(diff):
lines.append(padder)
return 0, lines
if self.vertical_align == VerticalAlignment.CENTER:
top, extra = divmod(diff, 2)
bottom = top + extra
for _ in range(top):
lines.insert(0, padder)
for _ in range(bottom):
lines.append(padder)
return top, lines
raise NotImplementedError(
f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}."
)
def get_lines(self) -> list[str]:
"""Gets all lines by spacing out inner widgets.
This method reflects & applies both width settings, as well as
the `parent_align` field.
Returns:
A list of all lines that represent this Container.
"""
def _get_border(left: str, char: str, right: str) -> str:
"""Gets a top or bottom border.
Args:
left: Left corner character.
char: Border character filling between left & right.
right: Right corner character.
Returns:
The border line.
"""
offset = real_length(left + right)
return left + char * (self.width - offset) + right
lines = []
style = self._get_style("border")
borders = [style(char) for char in self._get_char("border")]
style = self._get_style("corner")
corners = [style(char) for char in self._get_char("corner")]
has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0)
align = lambda item: item
for widget in self._widgets:
align, offset = self._get_aligners(widget, (borders[0], borders[2]))
self._update_width(widget)
widget.pos = (
self.pos[0] + offset,
self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0),
)
widget_lines = []
for line in widget.get_lines():
widget_lines.append(align(line))
lines.extend(widget_lines)
vertical_offset, lines = self._apply_vertalign(
lines, self.height - len(lines) - sum(has_top_bottom), align("")
)
for widget in self._widgets:
widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset)
# TODO: This is wasteful.
widget.get_lines()
if has_top_bottom[0]:
lines.insert(0, _get_border(corners[0], borders[1], corners[1]))
if has_top_bottom[1]:
lines.append(_get_border(corners[3], borders[3], corners[2]))
self.height = len(lines)
return lines
def set_widgets(self, new: list[Widget]) -> None:
"""Sets new list in place of self._widgets.
Args:
new: The new widget list.
"""
self._widgets = []
for widget in new:
self._add_widget(widget)
def serialize(self) -> dict[str, Any]:
"""Serializes this Container, adding in serializations of all widgets.
See `pytermgui.widgets.base.Widget.serialize` for more info.
Returns:
The dictionary containing all serialized data.
"""
out = super().serialize()
out["_widgets"] = []
for widget in self._widgets:
out["_widgets"].append(widget.serialize())
return out
def pop(self, index: int = -1) -> Widget:
"""Pops widget from self._widgets.
Analogous to self._widgets.pop(index).
Args:
index: The index to operate on.
Returns:
The widget that was popped off the list.
"""
return self._widgets.pop(index)
def remove(self, other: Widget) -> None:
"""Remove widget from self._widgets
Analogous to self._widgets.remove(other).
Args:
widget: The widget to remove.
"""
return self._widgets.remove(other)
def set_recursive_depth(self, value: int) -> None:
"""Set depth for this Container and all its children.
All inner widgets will receive value+1 as their new depth.
Args:
value: The new depth to use as the base depth.
"""
self.depth = value
for widget in self._widgets:
if isinstance(widget, Container):
widget.set_recursive_depth(value + 1)
else:
widget.depth = value
def select(self, index: int | None = None) -> None:
"""Selects inner subwidget.
Args:
index: The index to select.
Raises:
IndexError: The index provided was beyond len(self.selectables).
"""
# Unselect all sub-elements
for other in self._widgets:
if other.selectables_length > 0:
other.select(None)
if index is not None:
if index >= len(self.selectables) is None:
raise IndexError("Container selection index out of range")
widget, inner_index = self.selectables[index]
widget.select(inner_index)
self.selected_index = index
def center(
self, where: CenteringPolicy | None = None, store: bool = True
) -> Container:
"""Centers this object to the given axis.
Args:
where: A CenteringPolicy describing the place to center to
store: When set, this centering will be reapplied during every
print, as well as when calling this method with no arguments.
Returns:
This Container.
"""
# Refresh in case changes happened
self.get_lines()
if where is None:
# See `enums.py` for explanation about this ignore.
where = CenteringPolicy.get_default() # type: ignore
centerx = centery = where is CenteringPolicy.ALL
centerx |= where is CenteringPolicy.HORIZONTAL
centery |= where is CenteringPolicy.VERTICAL
pos = list(self.pos)
if centerx:
pos[0] = (terminal.width - self.width + 2) // 2
if centery:
pos[1] = (terminal.height - self.height + 2) // 2
self.pos = (pos[0], pos[1])
if store:
self._centered_axis = where
self._prev_screen = terminal.size
return self
def handle_mouse(self, event: MouseEvent) -> bool:
"""Applies a mouse event on all children.
Args:
event: The event to handle
Returns:
A boolean showing whether the event was handled.
"""
if event.action is MouseAction.RELEASE:
# Force RELEASE event to be sent
if self._drag_target is not None:
self._drag_target.handle_mouse(
MouseEvent(MouseAction.RELEASE, event.position)
)
self._drag_target = None
if self._drag_target is not None:
return self._drag_target.handle_mouse(event)
selectables_index = 0
for widget in self._widgets:
if widget.contains(event.position):
handled = widget.handle_mouse(event)
if widget.selected_index is not None:
selectables_index += widget.selected_index
if event.action is MouseAction.LEFT_CLICK:
self._drag_target = widget
if handled:
self.select(selectables_index)
return handled
if widget.is_selectable:
selectables_index += widget.selectables_length
return False
def handle_key(self, key: str) -> bool:
"""Handles a keypress, returns its success.
Args:
key: A key str.
Returns:
A boolean showing whether the key was handled.
"""
def _is_nav(key: str) -> bool:
"""Determine if a key is in the navigation sets"""
return key in self.keys["next"] | self.keys["previous"]
if self.selected is not None and self.selected.handle_key(key):
return True
# Only use navigation when there is more than one selectable
if self.selectables_length > 1 and _is_nav(key):
handled = False
if self.selected_index is None:
self.select(0)
assert isinstance(self.selected_index, int)
if key in self.keys["previous"]:
# No more selectables left, user wants to exit Container
# upwards.
if self.selected_index == 0:
return False
self.select(self.selected_index - 1)
handled = True
elif key in self.keys["next"]:
# Stop selection at last element, return as unhandled
new = self.selected_index + 1
if new == len(self.selectables):
return False
self.select(new)
handled = True
if handled:
return True
if key == keys.ENTER and self.selected is not None:
if self.selected.selected_index is not None:
self.selected.handle_key(key)
return True
return False
def wipe(self) -> None:
"""Wipes the characters occupied by the object"""
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(real_length(line) * " ")
def print(self) -> None:
"""Prints this Container.
If the screen size has changed since last `print` call, the object
will be centered based on its `_centered_axis`.
"""
if not terminal.size == self._prev_screen:
clear()
self.center(self._centered_axis)
self._prev_screen = terminal.size
if self.allow_fullscreen:
self.pos = terminal.origin
with cursor_at(self.pos) as print_here:
for line in self.get_lines():
print_here(line)
self._has_printed = True
def debug(self) -> str:
"""Returns a string with identifiable information on this widget.
Returns:
A str in the form of a class construction. This string is in a form that
__could have been__ used to create this Container.
"""
out = "Container("
for widget in self._widgets:
out += widget.debug() + ", "
out = out.strip(", ")
out += ", **attrs)"
return out
class Splitter(Container):
"""A widget that displays other widgets, stacked horizontally."""
chars: dict[str, list[str] | str] = {"separator": " | "}
styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND}
keys = {
"previous": {keys.LEFT, "h", keys.CTRL_B},
"next": {keys.RIGHT, "l", keys.CTRL_F},
}
parent_align = HorizontalAlignment.RIGHT
def _align(
self, alignment: HorizontalAlignment, target_width: int, line: str
) -> tuple[int, str]:
"""Align a line
r/wordavalanches"""
available = target_width - real_length(line)
fill_style = self._get_style("fill")
char = fill_style(" ")
line = fill_style(line)
if alignment == HorizontalAlignment.CENTER:
padding, offset = divmod(available, 2)
return padding, padding * char + line + (padding + offset) * char
if alignment == HorizontalAlignment.RIGHT:
return available, available * char + line
return 0, line + available * char
def get_lines(self) -> list[str]:
"""Join all widgets horizontally."""
# An error will be raised if `separator` is not the correct type (str).
separator = self._get_style("separator")(self._get_char("separator")) # type: ignore
separator_length = real_length(separator)
target_width, error = divmod(
self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets)
)
vertical_lines = []
total_offset = 0
for widget in self._widgets:
inner = []
if widget.size_policy is SizePolicy.STATIC:
target_width += target_width - widget.width
width = target_width
else:
widget.width = target_width + error
width = widget.width
error = 0
aligned: str | None = None
for line in widget.get_lines():
# See `enums.py` for information about this ignore
padding, aligned = self._align(
cast(HorizontalAlignment, widget.parent_align), width, line
)
inner.append(aligned)
widget.pos = (
self.pos[0] + padding + total_offset,
self.pos[1] + (1 if type(widget).__name__ == "Container" else 0),
)
if aligned is not None:
total_offset += real_length(inner[-1]) + separator_length
vertical_lines.append(inner)
lines = []
for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width):
lines.append((reset() + separator).join(horizontal))
return lines
def debug(self) -> str:
"""Return identifiable information"""
return super().debug().replace("Container", "Splitter", 1)
| bczsalba__pytermgui |