main.py 26 KB

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