main.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  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'<h4.*?>(.*?)</h4>', 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('<h4', f'<h4 id="{headline_id}"', 1)
  28. html = html.replace('</h4>', f' {anchor}</h4>', 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>', '<h4>', 1)
  37. html = html.replace('</p>', '</h4>', 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. def h3(text: str) -> None:
  93. ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
  94. h3('Basic Elements')
  95. with example(ui.label):
  96. ui.label('some label')
  97. with example(ui.icon):
  98. ui.icon('thumb_up')
  99. with example(ui.link):
  100. ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
  101. with example(ui.button):
  102. ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
  103. with example(ui.toggle):
  104. toggle1 = ui.toggle([1, 2, 3], value=1)
  105. toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
  106. with example(ui.radio):
  107. radio1 = ui.radio([1, 2, 3], value=1).props('inline')
  108. radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
  109. with example(ui.select):
  110. select1 = ui.select([1, 2, 3], value=1)
  111. select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
  112. with example(ui.checkbox):
  113. checkbox = ui.checkbox('check me')
  114. ui.label('Check!').bind_visibility_from(checkbox, 'value')
  115. with example(ui.switch):
  116. switch = ui.switch('switch me')
  117. ui.label('Switch!').bind_visibility_from(switch, 'value')
  118. with example(ui.slider):
  119. slider = ui.slider(min=0, max=100, value=50).props('label')
  120. ui.label().bind_text_from(slider, 'value')
  121. with example(ui.joystick):
  122. ui.joystick(color='blue', size=50,
  123. on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
  124. on_end=lambda msg: coordinates.set_text('0, 0'))
  125. coordinates = ui.label('0, 0')
  126. with example(ui.input):
  127. ui.input(label='Text', placeholder='press ENTER to apply',
  128. on_change=lambda e: input_result.set_text('you typed: ' + e.value))
  129. input_result = ui.label()
  130. with example(ui.number):
  131. ui.number(label='Number', value=3.1415927, format='%.2f',
  132. on_change=lambda e: number_result.set_text('you entered: ' + e.value))
  133. number_result = ui.label()
  134. with example(ui.color_input):
  135. color_label = ui.label('Change my color!')
  136. ui.color_input(label='Color', value='#000000',
  137. on_change=lambda e: color_label.style(f'color:{e.value}'))
  138. with example(ui.color_picker):
  139. picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
  140. button = ui.button(on_click=picker.open).props('icon=colorize')
  141. with example(ui.upload):
  142. ui.upload(on_upload=lambda e: upload_result.set_text(e.files))
  143. upload_result = ui.label()
  144. h3('Markdown and HTML')
  145. with example(ui.markdown):
  146. ui.markdown('''This is **Markdown**.''')
  147. with example(ui.html):
  148. ui.html('This is <strong>HTML</strong>.')
  149. svg = '''#### SVG
  150. You can add Scalable Vector Graphics using the `ui.html` element.
  151. '''
  152. with example(svg):
  153. content = '''
  154. <svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  155. <circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
  156. <circle cx="80" cy="85" r="8" />
  157. <circle cx="120" cy="85" r="8" />
  158. <path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
  159. </svg>'''
  160. ui.html(content)
  161. h3('Images')
  162. with example(ui.image):
  163. ui.image('http://placeimg.com/640/360/tech')
  164. captions_and_overlays = '''#### Captions and Overlays
  165. By nesting elements inside a `ui.image` you can create augmentations.
  166. Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
  167. To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
  168. '''
  169. with example(captions_and_overlays):
  170. with ui.image('http://placeimg.com/640/360/nature'):
  171. ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
  172. with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
  173. content = '''
  174. <svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
  175. <circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
  176. </svg>'''
  177. ui.html(content).style('background:transparent')
  178. with example(ui.interactive_image):
  179. from nicegui.events import MouseEventArguments
  180. def mouse_handler(e: MouseEventArguments):
  181. color = 'green' if e.type == 'mousedown' else 'orange'
  182. ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="10" fill="{color}"/>'
  183. ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
  184. src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
  185. ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
  186. h3('Data Elements')
  187. with example(ui.table):
  188. table = ui.table({
  189. 'columnDefs': [
  190. {'headerName': 'Name', 'field': 'name'},
  191. {'headerName': 'Age', 'field': 'age'},
  192. ],
  193. 'rowData': [
  194. {'name': 'Alice', 'age': 18},
  195. {'name': 'Bob', 'age': 21},
  196. {'name': 'Carol', 'age': 42},
  197. ],
  198. }).classes('max-h-40')
  199. def update():
  200. table.options.rowData[0].age += 1
  201. table.update()
  202. ui.button('Update', on_click=update)
  203. with example(ui.chart):
  204. from numpy.random import random
  205. chart = ui.chart({
  206. 'title': False,
  207. 'chart': {'type': 'bar'},
  208. 'xAxis': {'categories': ['A', 'B']},
  209. 'series': [
  210. {'name': 'Alpha', 'data': [0.1, 0.2]},
  211. {'name': 'Beta', 'data': [0.3, 0.4]},
  212. ],
  213. }).classes('max-w-full h-64')
  214. def update():
  215. chart.options.series[0].data[:] = random(2)
  216. chart.update()
  217. ui.button('Update', on_click=update)
  218. with example(ui.plot):
  219. import numpy as np
  220. from matplotlib import pyplot as plt
  221. with ui.plot(figsize=(2.5, 1.8)):
  222. x = np.linspace(0.0, 5.0)
  223. y = np.cos(2 * np.pi * x) * np.exp(-x)
  224. plt.plot(x, y, '-')
  225. plt.xlabel('time (s)')
  226. plt.ylabel('Damped oscillation')
  227. with example(ui.line_plot):
  228. from datetime import datetime
  229. import numpy as np
  230. line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
  231. .with_legend(['sin', 'cos'], loc='upper center', ncol=2)
  232. def update_line_plot() -> None:
  233. now = datetime.now()
  234. x = now.timestamp()
  235. y1 = np.sin(x)
  236. y2 = np.cos(x)
  237. line_plot.push([now], [[y1], [y2]])
  238. line_updates = ui.timer(0.1, update_line_plot, active=False)
  239. ui.checkbox('active').bind_value(line_updates, 'active')
  240. with example(ui.scene):
  241. with ui.scene(width=200, height=200) as scene:
  242. scene.sphere().material('#4488ff')
  243. scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
  244. scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
  245. with scene.group().move(z=2):
  246. box1 = scene.box().move(x=2)
  247. scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
  248. scene.box(wireframe=True).material('#888888').move(x=2, y=2)
  249. scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
  250. scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
  251. logo = "https://avatars.githubusercontent.com/u/2843826"
  252. scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
  253. [[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
  254. teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
  255. scene.stl(teapot).scale(0.2).move(-3, 4)
  256. scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
  257. scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
  258. with example(ui.tree):
  259. ui.tree([
  260. {'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
  261. {'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
  262. ], label_key='id', on_select=lambda e: ui.notify(e.value))
  263. with example(ui.log):
  264. from datetime import datetime
  265. log = ui.log(max_lines=10).classes('h-16')
  266. ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
  267. h3('Layout')
  268. with example(ui.card):
  269. with ui.card().tight():
  270. ui.image('http://placeimg.com/640/360/nature')
  271. with ui.card_section():
  272. ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
  273. with example(ui.column):
  274. with ui.column():
  275. ui.label('label 1')
  276. ui.label('label 2')
  277. ui.label('label 3')
  278. with example(ui.row):
  279. with ui.row():
  280. ui.label('label 1')
  281. ui.label('label 2')
  282. ui.label('label 3')
  283. clear_containers = '''#### Clear Containers
  284. To remove all elements from a row, column or card container, use the `clear()` method.
  285. '''
  286. with example(clear_containers):
  287. container = ui.row()
  288. def add_face():
  289. with container:
  290. ui.icon('face')
  291. add_face()
  292. ui.button('Add', on_click=add_face)
  293. ui.button('Clear', on_click=container.clear)
  294. with example(ui.expansion):
  295. with ui.expansion('Expand!', icon='work').classes('w-full'):
  296. ui.label('inside the expansion')
  297. with example(ui.menu):
  298. choice = ui.label('Try the menu.')
  299. with ui.menu() as menu:
  300. ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
  301. ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
  302. ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
  303. ui.menu_separator()
  304. ui.menu_item('Close', on_click=menu.close)
  305. ui.button('Open menu', on_click=menu.open)
  306. tooltips = '''#### Tooltips
  307. Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
  308. '''
  309. with example(tooltips):
  310. ui.label('Tooltips...').tooltip('...are shown on mouse over')
  311. ui.button().props('icon=thumb_up').tooltip('I like this')
  312. with example(ui.notify):
  313. ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
  314. with example(ui.dialog):
  315. with ui.dialog() as dialog, ui.card():
  316. ui.label('Hello world!')
  317. ui.button('Close', on_click=dialog.close)
  318. ui.button('Open a dialog', on_click=dialog.open)
  319. async_dialog = '''#### Awaitable dialog
  320. Dialogs can be awaited.
  321. Use the `submit` method to close the dialog and return a result.
  322. Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
  323. '''
  324. with example(async_dialog):
  325. with ui.dialog() as dialog, ui.card():
  326. ui.label('Are you sure?')
  327. with ui.row():
  328. ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
  329. ui.button('No', on_click=lambda: dialog.submit('No'))
  330. async def show():
  331. result = await dialog
  332. ui.notify(f'You chose {result}')
  333. ui.button('Await a dialog', on_click=show)
  334. h3('Appearance')
  335. design = '''#### Styling
  336. NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
  337. 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):
  338. Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
  339. You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
  340. If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
  341. All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
  342. '''
  343. with example(design):
  344. ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
  345. ui.button().props('icon=touch_app outline round').classes('shadow-lg')
  346. ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
  347. with example(ui.colors):
  348. ui.colors()
  349. ui.button('Default', on_click=lambda: ui.colors())
  350. ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
  351. h3('Action')
  352. lifecycle = '''#### Lifecycle
  353. You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
  354. - `ui.on_startup`: Called when NiceGUI is started or restarted.
  355. - `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
  356. - `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
  357. - `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
  358. - `ui.on_disconnect`: Called when a client disconnects from NiceGUI.
  359. When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
  360. '''
  361. with example(lifecycle):
  362. import asyncio
  363. import time
  364. l = ui.label()
  365. async def run_clock():
  366. while True:
  367. l.text = f'unix time: {time.time():.1f}'
  368. await asyncio.sleep(1)
  369. ui.on_startup(run_clock)
  370. ui.on_connect(lambda: l.set_text('new connection'))
  371. with example(ui.timer):
  372. from datetime import datetime
  373. with ui.row().classes('items-center'):
  374. clock = ui.label()
  375. t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
  376. ui.checkbox('active').bind_value(t, 'active')
  377. with ui.row():
  378. def lazy_update() -> None:
  379. new_text = datetime.now().strftime('%X.%f')[:-5]
  380. if lazy_clock.text[:8] == new_text[:8]:
  381. return
  382. lazy_clock.text = new_text
  383. lazy_clock = ui.label()
  384. ui.timer(interval=0.1, callback=lazy_update)
  385. with example(ui.keyboard):
  386. from nicegui.events import KeyEventArguments
  387. def handle_key(e: KeyEventArguments):
  388. if e.key == 'f' and not e.action.repeat:
  389. if e.action.keyup:
  390. ui.notify('f was just released')
  391. elif e.action.keydown:
  392. ui.notify('f was just pressed')
  393. if e.modifiers.shift and e.action.keydown:
  394. if e.key.arrow_left:
  395. ui.notify('going left')
  396. elif e.key.arrow_right:
  397. ui.notify('going right')
  398. elif e.key.arrow_up:
  399. ui.notify('going up')
  400. elif e.key.arrow_down:
  401. ui.notify('going down')
  402. keyboard = ui.keyboard(on_key=handle_key)
  403. ui.label('Key events can be caught globally by using the keyboard element.')
  404. ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
  405. bindings = '''#### Bindings
  406. NiceGUI is able to directly bind UI elements to models.
  407. Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
  408. Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
  409. To define a one-way binding use the `_from` and `_to` variants of these methods.
  410. Just pass a property of the model as parameter to these methods to create the binding.
  411. '''
  412. with example(bindings):
  413. class Demo:
  414. def __init__(self):
  415. self.number = 1
  416. demo = Demo()
  417. v = ui.checkbox('visible', value=True)
  418. with ui.column().bind_visibility_from(v, 'value'):
  419. ui.slider(min=1, max=3).bind_value(demo, 'number')
  420. ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
  421. ui.number().bind_value(demo, 'number')
  422. ui_updates = '''#### UI Updates
  423. 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.
  424. In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
  425. The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
  426. '''
  427. with example(ui_updates):
  428. from random import randint
  429. def add():
  430. numbers.options.rowData.append({'numbers': randint(0, 100)})
  431. numbers.update()
  432. def clear():
  433. numbers.options.rowData.clear()
  434. ui.update(numbers)
  435. numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
  436. ui.button('Add', on_click=add)
  437. ui.button('Clear', on_click=clear)
  438. async_handlers = '''#### Async event handlers
  439. Most elements also support asynchronous event handlers.
  440. Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
  441. '''
  442. with example(async_handlers):
  443. async def async_task():
  444. ui.notify('Asynchronous task started')
  445. await asyncio.sleep(5)
  446. ui.notify('Asynchronous task finished')
  447. ui.button('start async task', on_click=async_task)
  448. h3('Pages and Routes')
  449. with example(ui.page):
  450. with ui.page('/other_page'):
  451. ui.label('Welcome to the other side')
  452. ui.link('Back to main page', '#page')
  453. with ui.page('/dark_page', dark=True):
  454. ui.label('Welcome to the dark side')
  455. ui.link('Back to main page', '#page')
  456. ui.link('Visit other page', 'other_page')
  457. ui.link('Visit dark page', 'dark_page')
  458. with example(ui.open):
  459. with ui.page('/yet_another_page') as other:
  460. ui.label('Welcome to yet another page')
  461. ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
  462. ui.button('REDIRECT', on_click=lambda e: ui.open(other, e.socket))
  463. add_route = '''#### Route
  464. Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
  465. Routed paths must start with a `'/'`.
  466. '''
  467. with example(add_route):
  468. import starlette
  469. ui.add_route(starlette.routing.Route(
  470. '/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
  471. ))
  472. ui.link('Try the new route!', 'new/route')
  473. get_decorator = '''#### Get decorator
  474. Syntactic sugar to add routes.
  475. Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
  476. Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
  477. If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
  478. An optional `request` argument gives access to the complete request object.
  479. '''
  480. with example(get_decorator):
  481. from starlette import requests, responses
  482. @ui.get('/another/route/{id}')
  483. def produce_plain_response(id: str, request: requests.Request):
  484. return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
  485. ui.link('Try yet another route!', 'another/route/42')
  486. sessions = '''#### Sessions
  487. `ui.page` provides an optional `on_connect` argument to register a callback.
  488. It is invoked for each new connection to the page.
  489. 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).
  490. It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
  491. '''
  492. with example(sessions):
  493. from collections import Counter
  494. from datetime import datetime
  495. from starlette.requests import Request
  496. id_counter = Counter()
  497. creation = datetime.now().strftime('%H:%M, %d %B %Y')
  498. def handle_connection(request: Request):
  499. id_counter[request.session_id] += 1
  500. visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
  501. with ui.page('/session_demo', on_connect=handle_connection) as page:
  502. visits = ui.label()
  503. ui.link('Visit session demo', page)
  504. ui.run()