main.py 24 KB

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