main.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. #!/usr/bin/env python3
  2. import asyncio
  3. import inspect
  4. import re
  5. from contextlib import contextmanager
  6. from typing import Callable, Union
  7. import docutils.core
  8. from nicegui import ui
  9. # add docutils css to webpage
  10. ui.add_head_html(docutils.core.publish_parts('', writer_name='html')['stylesheet'])
  11. # avoid display:block for PyPI/Docker/GitHub badges
  12. ui.add_head_html('<style>p a img {display: inline; vertical-align: baseline}</style>')
  13. @contextmanager
  14. def example(content: Union[Callable, type, str]):
  15. callFrame = inspect.currentframe().f_back.f_back
  16. begin = callFrame.f_lineno
  17. def add_html_anchor(element: ui.html):
  18. html = element.content
  19. match = re.search(r'<h3.*?>(.*?)</h3>', html)
  20. if not match:
  21. return
  22. headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
  23. if not headline_id:
  24. return
  25. icon = '<span class="material-icons">link</span>'
  26. anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
  27. html = html.replace('<h3', f'<h3 id="{headline_id}"', 1)
  28. html = html.replace('</h3>', f' {anchor}</h3>', 1)
  29. element.view.inner_html = html
  30. with ui.row().classes('flex w-full'):
  31. if isinstance(content, str):
  32. add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
  33. else:
  34. doc = content.__doc__ or content.__init__.__doc__
  35. html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
  36. html = html.replace('<p>', '<h3>', 1)
  37. html = html.replace('</p>', '</h3>', 1)
  38. html = ui.markdown.apply_tailwind(html)
  39. add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
  40. try:
  41. with ui.card().classes('mt-12 w-2/12'):
  42. with ui.column().classes('flex w-full'):
  43. yield
  44. finally:
  45. code = inspect.getsource(callFrame)
  46. end = begin + 1
  47. lines = code.splitlines()
  48. while True:
  49. end += 1
  50. if end >= len(lines):
  51. break
  52. if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
  53. break
  54. code = lines[begin:end]
  55. code = [l[4:] for l in code]
  56. code.insert(0, '```python')
  57. code.insert(1, 'from nicegui import ui')
  58. if code[2].split()[0] not in ['from', 'import']:
  59. code.insert(2, '')
  60. code.append('ui.run()')
  61. code.append('```')
  62. code = '\n'.join(code)
  63. ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
  64. ui.html(
  65. '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-fork-ribbon-css/0.2.3/gh-fork-ribbon.min.css" />'
  66. '<style>.github-fork-ribbon:before { background-color: #999; }</style>'
  67. '<a class="github-fork-ribbon" href="https://github.com/zauberzeug/nicegui" data-ribbon="Fork me on GitHub" title="Fork me on GitHub">Fork me on GitHub</a>'
  68. )
  69. with ui.row().classes('flex w-full'):
  70. with open('README.md', 'r') as file:
  71. content = file.read()
  72. content = re.sub(r'(?m)^\<img.*\n?', '', content)
  73. ui.markdown(content).classes('w-6/12')
  74. with ui.card().classes('mx-auto mt-24'):
  75. with ui.row():
  76. with ui.column():
  77. ui.button('Click me!', on_click=lambda: output.set_text('Click'))
  78. ui.checkbox('Check me!', on_change=lambda e: output.set_text('Checked' if e.value else 'Unchecked'))
  79. ui.switch('Switch me!', on_change=lambda e: output.set_text('Switched' if e.value else 'Unswitched'))
  80. ui.input('Text', value='abc', on_change=lambda e: output.set_text(e.value))
  81. ui.number('Number', value=3.1415927, format='%.2f', on_change=lambda e: output.set_text(e.value))
  82. with ui.column():
  83. ui.slider(min=0, max=100, value=50, step=0.1, on_change=lambda e: output.set_text(e.value))
  84. ui.radio(['A', 'B', 'C'], value='A', on_change=lambda e: output.set_text(e.value)).props('inline')
  85. ui.toggle(['1', '2', '3'], value='1', on_change=lambda e: output.set_text(e.value)).classes('mx-auto')
  86. ui.select({1: 'One', 2: 'Two', 3: 'Three'}, value=1,
  87. on_change=lambda e: output.set_text(e.value)).classes('mx-auto')
  88. with ui.column().classes('w-24'):
  89. ui.label('Output:')
  90. output = ui.label('').classes('text-bold')
  91. ui.markdown('## API Documentation and Examples')
  92. with example(ui.label):
  93. ui.label('some label')
  94. with example(ui.image):
  95. ui.image('http://placeimg.com/640/360/tech')
  96. base64 = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QCMRXhpZgAATU0AKgAAAAgABQESAAMAAAABAAEAAAEaAAUAAAABAAAASgEbAAUAAAABAAAAUgEoAAMAAAABAAIAAIdpAAQAAAABAAAAWgAAAAAAAABIAAAAAQAAAEgAAAABAAOgAQADAAAAAQABAACgAgAEAAAAAQAAACKgAwAEAAAAAQAAACMAAAAA/8IAEQgAIwAiAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAMCBAEFAAYHCAkKC//EAMMQAAEDAwIEAwQGBAcGBAgGcwECAAMRBBIhBTETIhAGQVEyFGFxIweBIJFCFaFSM7EkYjAWwXLRQ5I0ggjhU0AlYxc18JNzolBEsoPxJlQ2ZJR0wmDShKMYcOInRTdls1V1pJXDhfLTRnaA40dWZrQJChkaKCkqODk6SElKV1hZWmdoaWp3eHl6hoeIiYqQlpeYmZqgpaanqKmqsLW2t7i5usDExcbHyMnK0NTV1tfY2drg5OXm5+jp6vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAQIAAwQFBgcICQoL/8QAwxEAAgIBAwMDAgMFAgUCBASHAQACEQMQEiEEIDFBEwUwIjJRFEAGMyNhQhVxUjSBUCSRoUOxFgdiNVPw0SVgwUThcvEXgmM2cCZFVJInotIICQoYGRooKSo3ODk6RkdISUpVVldYWVpkZWZnaGlqc3R1dnd4eXqAg4SFhoeIiYqQk5SVlpeYmZqgo6SlpqeoqaqwsrO0tba3uLm6wMLDxMXGx8jJytDT1NXW19jZ2uDi4+Tl5ufo6ery8/T19vf4+fr/2wBDAAwMDAwMDBUMDBUeFRUVHikeHh4eKTQpKSkpKTQ+NDQ0NDQ0Pj4+Pj4+Pj5LS0tLS0tXV1dXV2JiYmJiYmJiYmL/2wBDAQ8QEBkXGSsXFytnRjlGZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2f/2gAMAwEAAhEDEQAAAeqBgCIareozvbaK3avBqa52teT6He3z0TqCUZa22r//2gAIAQEAAQUCaVVKTjGnLFqSqqlGuciX+87YgM8ScWhAx5KWUJUdJClKadMye6O//9oACAEDEQE/AUxI86A0ynfb/9oACAECEQE/ASaYZBLxpKNinFh2dv8A/9oACAEBAAY/AmUniHVXxfVx7ZIP9x0GlOJdfa+BeVentkSWR66jsI1HUfF+f4l1UykiqR/CypAorg6n/hvuH5nv/8QAMxABAAMAAgICAgIDAQEAAAILAREAITFBUWFxgZGhscHw0RDh8SAwQFBgcICQoLDA0OD/2gAIAQEAAT8hrchP08Nlp8V+7MHK/wCcEXw8q94vkT4K5DD0fpsJBFkwYvy/8cJBuuX7l82UhL9HmlzVKCOfi+3/ADe6Z2jgePxcMYN/xxYQtAu8UCj/ALXDvn/sBxRB/g3/AL//2gAMAwEAAhEDEQAAEE5gPHEUEAP/xAAzEQEBAQADAAECBQUBAQABAQkBABEhMRBBUWEgcfCRgaGx0cHh8TBAUGBwgJCgsMDQ4P/aAAgBAxEBPxAN4PZaNJuOW/g//9oACAECEQE/EAGt2fwmfzBp3X8P/9oACAEBAAE/ELGubg74j5M+RuAgxMrE4g5c4qAjQh1Oh9GL3/xggJDuHs5H2fY1rQIGDISTZ3KuGYzkk8dSkh4Ah8TJ8c0SsIco+yPRD76/486QSwOdnIpjvmvjAQ8pEx4ixlVcDldAdtawTzP5CSqs1wAPeJDMz0nwvHVlRSYTI1ic6b58RUC4kuSTXmFOJuxknJgsgDQMkjQgj/gCBHee6QjzflUA4/5//9k='
  97. ui.image(base64).style('width:30px')
  98. with example(ui.svg):
  99. svg_content = '''
  100. <svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  101. <circle cx="100" cy="100" r="78" fill="yellow" stroke="black" stroke-width="3" />
  102. <circle cx="61" cy="82" r="12" />
  103. <circle cx="127" cy="82" r="12" />
  104. <path d="m136.81 116.53c.69 36.17-74.11 42-81.52-.73" style="fill:none; stroke: black; stroke-width: 5;" />
  105. </svg>'''
  106. ui.svg(svg_content)
  107. overlay = '''### Captions and Overlays
  108. By nesting elements inside a `ui.image` you can create augmentations.
  109. Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
  110. To overlay an svg, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
  111. '''
  112. with example(overlay):
  113. with ui.image('http://placeimg.com/640/360/nature'):
  114. ui.label('nice').classes('absolute-bottom text-subtitle2 text-center')
  115. with ui.image('https://cdn.pixabay.com/photo/2020/07/13/12/56/mute-swan-5400675__340.jpg'):
  116. svg_content = '''
  117. <svg viewBox="0 0 510 340" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
  118. <circle cx="200" cy="200" r="100" fill="none" stroke="red" stroke-width="10" />
  119. </svg>'''
  120. ui.svg(svg_content).style('background:transparent')
  121. with example(ui.interactive_image):
  122. from nicegui.events import MouseEventArguments
  123. def mouse_handler(e: MouseEventArguments):
  124. color = 'green' if e.type == 'mousedown' else 'orange'
  125. ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="10" fill="{color}"/>'
  126. ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
  127. ii = ui.interactive_image('http://placeimg.com/640/360/arch',
  128. on_mouse=mouse_handler,
  129. events=['mousedown', 'mouseup'], cross=True)
  130. with example(ui.markdown):
  131. ui.markdown('### Headline\nWith hyperlink to [GitHub](https://github.com/zauberzeug/nicegui).')
  132. with example(ui.html):
  133. ui.html('<p>demo paragraph in <strong>html</strong></p>')
  134. with example(ui.button):
  135. def button_increment():
  136. global button_count
  137. button_count += 1
  138. button_result.set_text(f'pressed: {button_count}')
  139. button_count = 0
  140. ui.button('Button', on_click=button_increment)
  141. button_result = ui.label('pressed: 0')
  142. async_button = '''### Button with asynchronous action
  143. The button element does also support asynchronous action.
  144. Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
  145. '''
  146. with example(async_button):
  147. async def async_task():
  148. ui.notify('Asynchronous task started')
  149. await asyncio.sleep(5)
  150. ui.notify('Asynchronous task finished')
  151. ui.button('start async task', on_click=async_task)
  152. with example(ui.checkbox):
  153. ui.checkbox('check me', on_change=lambda e: checkbox_state.set_text(e.value))
  154. with ui.row():
  155. ui.label('the checkbox is:')
  156. checkbox_state = ui.label('False')
  157. with example(ui.switch):
  158. ui.switch('switch me', on_change=lambda e: switch_state.set_text('ON' if e.value else'OFF'))
  159. with ui.row():
  160. ui.label('the switch is:')
  161. switch_state = ui.label('OFF')
  162. with example(ui.slider):
  163. slider = ui.slider(min=0, max=100, value=50).props('label')
  164. ui.label().bind_text_from(slider, 'value')
  165. with example(ui.input):
  166. ui.input(
  167. label='Text',
  168. placeholder='press ENTER to apply',
  169. on_change=lambda e: result.set_text('you typed: ' + e.value),
  170. ).classes('w-full')
  171. result = ui.label('')
  172. with example(ui.number):
  173. number_input = ui.number(label='Number', value=3.1415927, format='%.2f')
  174. with ui.row():
  175. ui.label('underlying value: ')
  176. ui.label().bind_text_from(number_input, 'value')
  177. with example(ui.color_input):
  178. color_label = ui.label('Change my color!')
  179. ui.color_input(label='Color', value='#000000',
  180. on_change=lambda e: color_label.style(f'color:{e.value}'))
  181. with example(ui.color_picker):
  182. picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
  183. button = ui.button(on_click=picker.open).props('icon=colorize')
  184. with example(ui.radio):
  185. radio = ui.radio([1, 2, 3], value=1).props('inline')
  186. ui.radio({1: 'A', 2: 'B', 3: 'C'}, value=1).props('inline').bind_value(radio, 'value')
  187. with example(ui.toggle):
  188. toggle = ui.toggle([1, 2, 3], value=1)
  189. ui.toggle({1: 'A', 2: 'B', 3: 'C'}, value=1).bind_value(toggle, 'value')
  190. with example(ui.select):
  191. with ui.row():
  192. select = ui.select([1, 2, 3], value=1).props('inline')
  193. ui.select({1: 'One', 2: 'Two', 3: 'Three'}, value=1).props('inline').bind_value(select, 'value')
  194. with example(ui.upload):
  195. ui.upload(on_upload=lambda e: content.set_text(e.files))
  196. content = ui.label()
  197. with example(ui.plot):
  198. import numpy as np
  199. from matplotlib import pyplot as plt
  200. with ui.plot(figsize=(2.5, 1.8)):
  201. x = np.linspace(0.0, 5.0)
  202. y = np.cos(2 * np.pi * x) * np.exp(-x)
  203. plt.plot(x, y, '-')
  204. plt.xlabel('time (s)')
  205. plt.ylabel('Damped oscillation')
  206. with example(ui.line_plot):
  207. lines = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)).with_legend(['sin', 'cos'], loc='upper center', ncol=2)
  208. line_updates = ui.timer(0.1, lambda: lines.push([datetime.now()], [
  209. [np.sin(datetime.now().timestamp()) + 0.02 * np.random.randn()],
  210. [np.cos(datetime.now().timestamp()) + 0.02 * np.random.randn()],
  211. ]), active=False)
  212. ui.checkbox('active').bind_value(line_updates, 'active')
  213. with example(ui.log):
  214. from datetime import datetime
  215. log = ui.log(max_lines=10).classes('h-16')
  216. ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
  217. with example(ui.tree):
  218. ui.tree([
  219. {'id': 'number', 'children': [{'id': '1'}, {'id': '2'}]},
  220. {'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
  221. ], label_key='id', on_select=lambda e: ui.notify(e.value))
  222. with example(ui.scene):
  223. with ui.scene(width=200, height=200) as scene:
  224. scene.sphere().material('#4488ff')
  225. scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
  226. scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
  227. with scene.group().move(z=2):
  228. box1 = scene.box().move(x=2)
  229. scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
  230. scene.box(wireframe=True).material('#888888').move(x=2, y=2)
  231. scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
  232. scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
  233. logo = "https://avatars.githubusercontent.com/u/2843826"
  234. scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
  235. [[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
  236. teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
  237. scene.stl(teapot).scale(0.2).move(-3, 4)
  238. scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
  239. scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
  240. with example(ui.chart):
  241. from numpy.random import random
  242. def update():
  243. chart.options.series[0].data[:] = random(2)
  244. chart.update()
  245. chart = ui.chart({
  246. 'title': False,
  247. 'chart': {'type': 'bar'},
  248. 'xAxis': {'categories': ['A', 'B']},
  249. 'series': [
  250. {'name': 'Alpha', 'data': [0.1, 0.2]},
  251. {'name': 'Beta', 'data': [0.3, 0.4]},
  252. ],
  253. }).classes('max-w-full h-64')
  254. ui.button('Update', on_click=update)
  255. with example(ui.table):
  256. def update():
  257. table.options.rowData[0].age += 1
  258. table.update()
  259. table = ui.table({
  260. 'columnDefs': [
  261. {'headerName': 'Name', 'field': 'name'},
  262. {'headerName': 'Age', 'field': 'age'},
  263. ],
  264. 'rowData': [
  265. {'name': 'Alice', 'age': 18},
  266. {'name': 'Bob', 'age': 21},
  267. {'name': 'Carol', 'age': 42},
  268. ],
  269. }).classes('max-h-40')
  270. ui.button('Update', on_click=update)
  271. with example(ui.joystick):
  272. ui.joystick(
  273. color='blue',
  274. size=50,
  275. on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
  276. on_end=lambda _: coordinates.set_text('0, 0'))
  277. coordinates = ui.label('0, 0')
  278. with example(ui.dialog):
  279. with ui.dialog() as dialog, ui.card():
  280. ui.label('Hello world!')
  281. ui.button('Close', on_click=dialog.close)
  282. ui.button('Open a dialog', on_click=dialog.open)
  283. async_dialog = '''### Awaitable dialog
  284. Dialogs can be awaited.
  285. Use the `submit` method to close the dialog and return a result.
  286. Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
  287. '''
  288. with example(async_dialog):
  289. with ui.dialog() as dialog, ui.card():
  290. ui.label('Are you sure?')
  291. with ui.row():
  292. ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
  293. ui.button('No', on_click=lambda: dialog.submit('No'))
  294. async def show():
  295. result = await dialog
  296. ui.notify(f'You chose {result}')
  297. ui.button('Await a dialog', on_click=show)
  298. tooltip = '''### Tooltips
  299. Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
  300. '''
  301. with example(tooltip):
  302. with ui.row():
  303. ui.button().props('icon=thumb_up').tooltip('I like this')
  304. ui.label('tooltips').classes('q-mt-sm').tooltip('tooltips are shown on mouse over')
  305. with example(ui.menu):
  306. choice = ui.label('Try the menu.')
  307. with ui.menu() as menu:
  308. ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
  309. ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
  310. ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
  311. ui.menu_separator()
  312. ui.menu_item('Close', on_click=menu.close)
  313. ui.button('Open menu', on_click=menu.open).props('color=secondary')
  314. with example(ui.expansion):
  315. with ui.expansion('Expand!', icon='work').classes('w-full'):
  316. ui.label('inside the expansion')
  317. with example(ui.notify):
  318. ui.button('Show notification', on_click=lambda: ui.notify('Some message', close_button='OK'))
  319. design = '''### Styling
  320. NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
  321. 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):
  322. Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
  323. You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
  324. If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
  325. All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
  326. '''
  327. with example(design):
  328. ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
  329. ui.button().props('icon=touch_app outline round').classes('shadow-lg ml-14')
  330. with example(ui.colors):
  331. ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
  332. ui.button('Default', on_click=lambda: ui.colors())
  333. ui.colors()
  334. with example(ui.card):
  335. with ui.card().tight():
  336. ui.image('http://placeimg.com/640/360/nature')
  337. with ui.card_section():
  338. ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
  339. with example(ui.column):
  340. with ui.column():
  341. ui.label('label 1')
  342. ui.label('label 2')
  343. ui.label('label 3')
  344. with example(ui.row):
  345. with ui.row():
  346. ui.label('label 1')
  347. ui.label('label 2')
  348. ui.label('label 3')
  349. clear = '''### Clear Containers
  350. To remove all elements from a row, column or card container, use the `clear()` method.
  351. '''
  352. with example(clear):
  353. container = ui.row()
  354. def add_face():
  355. with container:
  356. ui.icon('face')
  357. add_face()
  358. ui.button('Add', on_click=add_face)
  359. ui.button('Clear', on_click=container.clear)
  360. binding = '''### Bindings
  361. NiceGUI is able to directly bind UI elements to models.
  362. Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
  363. Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
  364. To define a one-way binding use the `_from` and `_to` variants of these methods.
  365. Just pass a property of the model as parameter to these methods to create the binding.
  366. '''
  367. with example(binding):
  368. class Demo:
  369. def __init__(self):
  370. self.number = 1
  371. demo = Demo()
  372. v = ui.checkbox('visible', value=True)
  373. with ui.column().bind_visibility_from(v, 'value'):
  374. ui.slider(min=1, max=3).bind_value(demo, 'number')
  375. ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
  376. ui.number().bind_value(demo, 'number')
  377. with example(ui.timer):
  378. from datetime import datetime
  379. with ui.row().classes('items-center'):
  380. clock = ui.label()
  381. t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
  382. ui.checkbox('active').bind_value(t, 'active')
  383. with ui.row():
  384. def lazy_update() -> None:
  385. new_text = datetime.now().strftime('%X.%f')[:-5]
  386. if lazy_clock.text[:8] == new_text[:8]:
  387. return
  388. lazy_clock.text = new_text
  389. lazy_clock = ui.label()
  390. ui.timer(interval=0.1, callback=lazy_update)
  391. lifecycle = '''### Lifecycle
  392. You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
  393. - `ui.on_startup`: Called when NiceGUI is started or restarted.
  394. - `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
  395. - `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
  396. - `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
  397. - `ui.on_disconnect`: Called when a client disconnects from NiceGUI.
  398. When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
  399. '''
  400. with example(lifecycle):
  401. import asyncio
  402. import time
  403. l = ui.label()
  404. async def run_clock():
  405. while True:
  406. l.text = f'unix time: {time.time():.1f}'
  407. await asyncio.sleep(1)
  408. ui.on_startup(run_clock)
  409. ui.on_connect(lambda: l.set_text('new connection'))
  410. updates = '''### UI Updates
  411. 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.
  412. In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
  413. The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
  414. '''
  415. with example(updates):
  416. from random import randint
  417. def add():
  418. numbers.options.rowData.append({'numbers': randint(0, 100)})
  419. numbers.update()
  420. def clear():
  421. numbers.options.rowData.clear()
  422. ui.update(numbers)
  423. numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
  424. ui.button('Add', on_click=add)
  425. ui.button('Clear', on_click=clear)
  426. with example(ui.link):
  427. ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
  428. with example(ui.page):
  429. with ui.page('/other_page'):
  430. ui.label('Welcome to the other side')
  431. ui.link('Back to main page', '#page')
  432. with ui.page('/dark_page', dark=True):
  433. ui.label('Welcome to the dark side')
  434. ui.link('Back to main page', '#page')
  435. ui.link('Visit other page', 'other_page')
  436. ui.link('Visit dark page', 'dark_page')
  437. with example(ui.open):
  438. with ui.page('/yet_another_page') as other:
  439. ui.label('Welcome to yet another page')
  440. ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
  441. ui.button('REDIRECT', on_click=lambda e: ui.open(other, e.socket))
  442. sessions = """### Sessions
  443. `ui.page` provides an optional `on_connect` argument to register a callback.
  444. It is invoked for each new connection to the page.
  445. 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).
  446. It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
  447. """
  448. with example(sessions):
  449. from collections import Counter
  450. from datetime import datetime
  451. from starlette.requests import Request
  452. id_counter = Counter()
  453. creation = datetime.now().strftime('%H:%M, %d %B %Y')
  454. def handle_connection(request: Request):
  455. id_counter[request.session_id] += 1
  456. visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
  457. with ui.page('/session_demo', on_connect=handle_connection) as page:
  458. visits = ui.label()
  459. ui.link('Visit session demo', page)
  460. add_route = """### Route
  461. Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
  462. Routed paths must start with a `'/'`.
  463. """
  464. with example(add_route):
  465. import starlette
  466. ui.add_route(starlette.routing.Route(
  467. '/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
  468. ))
  469. ui.link('Try the new route!', 'new/route')
  470. get_decorator = """### Get decorator
  471. Syntactic sugar to add routes.
  472. Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
  473. Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
  474. If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
  475. An optional `request` argument gives access to the complete request object.
  476. """
  477. with example(get_decorator):
  478. from starlette import requests, responses
  479. @ui.get('/another/route/{id}')
  480. def produce_plain_response(id: str, request: requests.Request):
  481. return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
  482. ui.link('Try yet another route!', 'another/route/42')
  483. with example(ui.keyboard):
  484. from nicegui.events import KeyEventArguments
  485. def handle_key(e: KeyEventArguments):
  486. if e.key == 'f' and not e.action.repeat:
  487. if e.action.keyup:
  488. ui.notify('f was just released')
  489. elif e.action.keydown:
  490. ui.notify('f was just pressed')
  491. if e.modifiers.shift and e.action.keydown:
  492. if e.key.arrow_left:
  493. ui.notify('going left')
  494. elif e.key.arrow_right:
  495. ui.notify('going right')
  496. elif e.key.arrow_up:
  497. ui.notify('going up')
  498. elif e.key.arrow_down:
  499. ui.notify('going down')
  500. keyboard = ui.keyboard(on_key=handle_key)
  501. ui.label('Key events can be caught globally by using the keyboard element.')
  502. ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
  503. ui.run()