main.py 28 KB

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