1
0

api_docs_and_examples.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. import inspect
  2. import re
  3. from contextlib import contextmanager
  4. from typing import Callable, Union
  5. import docutils.core
  6. from nicegui import globals, ui
  7. from nicegui.task_logger import create_task
  8. REGEX_H4 = re.compile(r'<h4.*?>(.*?)</h4>')
  9. SPECIAL_CHARACTERS = re.compile('[^(a-z)(A-Z)(0-9)-]')
  10. @contextmanager
  11. def example(content: Union[Callable, type, str], first_col=4) -> None:
  12. callFrame = inspect.currentframe().f_back.f_back
  13. begin = callFrame.f_lineno
  14. def add_html_anchor(element: ui.html):
  15. html = element.content
  16. match = REGEX_H4.search(html)
  17. if not match:
  18. return
  19. headline = match.groups()[0].strip()
  20. headline_id = SPECIAL_CHARACTERS.sub('_', headline).lower()
  21. if not headline_id:
  22. return
  23. icon = '<span class="material-icons">link</span>'
  24. anchor = f'<a href="reference#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
  25. html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
  26. html = html.replace('</h4>', f' {anchor}</h4>', 1)
  27. element.view.inner_html = html
  28. with ui.row().classes('flex w-full'):
  29. if isinstance(content, str):
  30. add_html_anchor(ui.markdown(content).classes(f'mr-8 w-{first_col}/12'))
  31. else:
  32. doc = content.__doc__ or content.__init__.__doc__
  33. html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
  34. html = html.replace('<p>', '<h4>', 1)
  35. html = html.replace('</p>', '</h4>', 1)
  36. html = ui.markdown.apply_tailwind(html)
  37. add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
  38. try:
  39. with ui.card().classes('mt-12 w-2/12'):
  40. with ui.column().classes('flex w-full'):
  41. yield
  42. finally:
  43. code: str = open(__file__).read()
  44. end = begin + 1
  45. lines = code.splitlines()
  46. while True:
  47. end += 1
  48. if end >= len(lines):
  49. break
  50. if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
  51. break
  52. code = lines[begin:end]
  53. code = [l[8:] for l in code]
  54. code.insert(0, '```python')
  55. code.insert(1, 'from nicegui import ui')
  56. if code[2].split()[0] not in ['from', 'import']:
  57. code.insert(2, '')
  58. for l, line in enumerate(code):
  59. if line.startswith('# ui.'):
  60. code[l] = line[2:]
  61. break
  62. else:
  63. code.append('ui.run()')
  64. code.append('```')
  65. code = '\n'.join(code)
  66. ui.markdown(code).classes(f'mt-12 w-{9-first_col}/12 overflow-auto')
  67. def create_intro() -> None:
  68. # add docutils css to webpage
  69. ui.add_head_html(docutils.core.publish_parts('', writer_name='html')['stylesheet'])
  70. hello_world = '''#### Hello, World!
  71. Creating a user interface with NiceGUI is as simple as writing a single line of code.
  72. '''
  73. with example(hello_world, first_col=2):
  74. ui.label('Hello, world!')
  75. ui.markdown('Have a look at the full <br/> [API reference](reference)!')
  76. common_elements = '''#### Common UI Elements
  77. NiceGUI comes with a collection of commonly used UI elements.
  78. '''
  79. with example(common_elements, first_col=2):
  80. ui.button('Button', on_click=lambda: ui.notify('Click'))
  81. ui.checkbox('Checkbox', on_change=lambda e: ui.notify('Checked' if e.value else 'Unchecked'))
  82. ui.switch('Switch', on_change=lambda e: ui.notify('Switched' if e.value else 'Unswitched'))
  83. ui.input('Text input', on_change=lambda e: ui.notify(e.value))
  84. ui.radio(['A', 'B'], value='A', on_change=lambda e: ui.notify(e.value)).props('inline')
  85. ui.select(['One', 'Two'], value='One', on_change=lambda e: ui.notify(e.value))
  86. ui.link('And many more...', '/reference').classes('text-lg')
  87. binding = '''#### Value Binding
  88. Binding values between UI elements or [to data models](http://127.0.0.1:8080/reference#bindings) is built into NiceGUI.
  89. '''
  90. with example(binding, first_col=2):
  91. slider = ui.slider(min=0, max=100, value=50)
  92. ui.number('Value').bind_value(slider, 'value').classes('fit')
  93. # HACK: this comment prevents another blank line sneaking into the example above
  94. def create_full() -> None:
  95. # add docutils css to webpage
  96. ui.add_head_html(docutils.core.publish_parts('', writer_name='html')['stylesheet'])
  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), update_every=5) \
  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. line_checkbox = 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). See [Yield for Page Ready](#yield_for_page_ready) as an alternative.
  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. l = ui.label()
  369. async def countdown():
  370. for i in [5, 4, 3, 2, 1, 0]:
  371. l.text = f'{i}...' if i else 'Take-off!'
  372. await asyncio.sleep(1)
  373. # ui.on_connect(countdown)
  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. import asyncio
  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')
  453. with example(ui.page):
  454. @ui.page('/other_page')
  455. def other_page():
  456. ui.label('Welcome to the other side')
  457. ui.link('Back to main page', '#page')
  458. @ui.page('/dark_page', dark=True)
  459. def dark_page():
  460. ui.label('Welcome to the dark side')
  461. ui.link('Back to main page', '#page')
  462. ui.link('Visit other page', other_page)
  463. ui.link('Visit dark page', dark_page)
  464. shared_and_private_pages = '''#### Shared and Private Pages
  465. By default, pages created with the `@ui.page` decorator are "private".
  466. Their content is re-created for each client.
  467. Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
  468. With `shared=True` you can create a shared page.
  469. Its content is created once at startup and each client sees the *same* elements.
  470. Here, the displayed ID remains constant when the browser reloads the page.
  471. #### Index Page
  472. All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
  473. 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.
  474. '''
  475. with example(shared_and_private_pages):
  476. from uuid import uuid4
  477. @ui.page('/private_page')
  478. async def private_page():
  479. ui.label(f'private page with ID {uuid4()}')
  480. @ui.page('/shared_page', shared=True)
  481. async def shared_page():
  482. ui.label(f'shared page with ID {uuid4()}')
  483. ui.link('private page', private_page)
  484. ui.link('shared page', shared_page)
  485. page_with_path_parameters = '''#### Pages with Path Parameters
  486. Page routes can contain parameters like [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/>).
  487. If type-annotated, they are automatically converted to bool, int, float and complex values.
  488. If the page function expects a `request` argument, the request object is automatically provided.
  489. '''
  490. with example(page_with_path_parameters):
  491. @ui.page('/repeat/{word}/{count}')
  492. def page(word: str, count: int):
  493. ui.label(word * count)
  494. ui.link('Say hi to Santa!', 'repeat/Ho! /3')
  495. yield_page_ready = '''#### Yielding for Page-Ready
  496. This is a handy alternative to the `on_page_ready` callback (either as parameter of `@ui.page` or via `ui.on_page_ready` function).
  497. If a `yield` statement is provided in a page builder function, all code below that statement is executed after the page is ready.
  498. This allows you to execute JavaScript; which is only possible after the page has been loaded (see [#112](https://github.com/zauberzeug/nicegui/issues/112)).
  499. Also it is possible to do async stuff while the user already sees the content added before the yield statement.
  500. '''
  501. with example(yield_page_ready):
  502. @ui.page('/yield_page_ready')
  503. async def yield_page_ready():
  504. ui.label('This text is displayed immediately.')
  505. yield
  506. ui.run_javascript('document.title = "JavaScript-Controlled Title")')
  507. await asyncio.sleep(3)
  508. ui.label('This text is displayed 3 seconds after the page has been fully loaded.')
  509. ui.link('show page-ready code after yield', '/yield_page_ready')
  510. with example(ui.open):
  511. @ui.page('/yet_another_page')
  512. def yet_another_page():
  513. ui.label('Welcome to yet another page')
  514. ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
  515. ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
  516. sessions = '''#### Sessions
  517. `ui.page` provides an optional `on_connect` argument to register a callback.
  518. It is invoked for each new connection to the page.
  519. 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).
  520. It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
  521. '''
  522. with example(sessions):
  523. from collections import Counter
  524. from datetime import datetime
  525. from starlette.requests import Request
  526. id_counter = Counter()
  527. creation = datetime.now().strftime('%H:%M, %d %B %Y')
  528. def handle_connection(request: Request):
  529. id_counter[request.session_id] += 1
  530. visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
  531. @ui.page('/session_demo', on_connect=handle_connection)
  532. def session_demo():
  533. global visits
  534. visits = ui.label()
  535. ui.link('Visit session demo', session_demo)
  536. javascript = '''#### JavaScript
  537. With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
  538. The asynchronous function will return after the command(s) are executed.
  539. The result of the execution is returned as a dictionary containing the response string per websocket.
  540. You can also set `respond=False` to send a command without waiting for a response.
  541. '''
  542. with example(javascript):
  543. async def alert():
  544. await ui.run_javascript('alert("Hello!")', respond=False)
  545. async def get_date():
  546. response = await ui.run_javascript('Date()')
  547. for socket, time in response.items():
  548. ui.notify(f'Browser time on host {socket.client.host}: {time}')
  549. ui.button('fire and forget', on_click=alert)
  550. ui.button('receive result', on_click=get_date)
  551. h3('Routes')
  552. with example(ui.get):
  553. from starlette import requests, responses
  554. @ui.get('/another/route/{id}')
  555. def produce_plain_response(id: str, request: requests.Request):
  556. return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
  557. ui.link('Try yet another route!', 'another/route/42')
  558. with example(ui.add_static_files):
  559. ui.add_static_files('/examples', 'examples')
  560. ui.link('Slideshow Example (raw file)', 'examples/slideshow/main.py')
  561. with ui.image('examples/slideshow/slides/slide1.jpg'):
  562. ui.label('first image from slideshow').classes('absolute-bottom text-subtitle2')
  563. with example(ui.add_route):
  564. import starlette
  565. ui.add_route(starlette.routing.Route(
  566. '/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
  567. ))
  568. ui.link('Try the new route!', 'new/route')
  569. h3('Configuration')
  570. ui_run = '''#### ui.run
  571. You can call `ui.run()` with optional arguments:
  572. - `host` (default: `'0.0.0.0'`)
  573. - `port` (default: `8080`)
  574. - `title` (default: `'NiceGUI'`)
  575. - `favicon` (default: `'favicon.ico'`)
  576. - `dark`: whether to use Quasar's dark mode (default: `False`, use `None` for "auto" mode)
  577. - `main_page_classes`: configure Quasar classes of main page (default: `'q-ma-md column items-start'`)
  578. - `binding_refresh_interval`: time between binding updates (default: `0.1` seconds, bigger is more cpu friendly)
  579. - `show`: automatically open the ui in a browser tab (default: `True`)
  580. - `reload`: automatically reload the ui on file changes (default: `True`)
  581. - `uvicorn_logging_level`: logging level for uvicorn server (default: `'warning'`)
  582. - `uvicorn_reload_dirs`: string with comma-separated list for directories to be monitored (default is current working directory only)
  583. - `uvicorn_reload_includes`: string with comma-separated list of glob-patterns which trigger reload on modification (default: `'.py'`)
  584. - `uvicorn_reload_excludes`: string with comma-separated list of glob-patterns which should be ignored for reload (default: `'.*, .py[cod], .sw.*, ~*'`)
  585. - `exclude`: comma-separated string to exclude elements (with corresponding JavaScript libraries) to save bandwidth
  586. (possible entries: chart, colors, interactive_image, keyboard, log, joystick, scene, table)
  587. The environment variables `HOST` and `PORT` can also be used to configure NiceGUI.
  588. To avoid the potentially costly import of Matplotlib, you set the environment variable `MATPLOTLIB=false`.
  589. This will make `ui.plot` and `ui.line_plot` unavailable.
  590. '''
  591. with example(ui_run):
  592. ui.label('dark page on port 7000 without reloading')
  593. # ui.run(dark=True, port=7000, reload=False)
  594. # HACK: turn expensive line plot off after 10 seconds
  595. def handle_change(self, msg):
  596. def turn_off():
  597. line_checkbox.value = False
  598. ui.notify('Turning off that line plot to save resources on our live demo server. 😎')
  599. line_checkbox.value = msg.value
  600. if msg.value:
  601. with globals.within_view(line_checkbox.view):
  602. ui.timer(10.0, turn_off, once=True)
  603. line_checkbox.update()
  604. return False
  605. line_checkbox.view.on('input', handle_change)
  606. # HACK: start countdown here to avoid using global lifecycle hook
  607. create_task(countdown(), name='countdown')