reference.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. from typing import Dict
  2. from nicegui import ui
  3. from .example import example
  4. def create_intro() -> None:
  5. @example('''#### Styling
  6. While having reasonable defaults, you can still modify the look of your app with CSS as well as Tailwind and Quasar classes.
  7. ''')
  8. def formatting_example():
  9. ui.icon('thumb_up')
  10. ui.markdown('''This is **Markdown**.''')
  11. ui.html('This is <strong>HTML</strong>.')
  12. with ui.row():
  13. ui.label('CSS').style('color: #888; font-weight: bold')
  14. ui.label('Tailwind').classes('font-serif')
  15. ui.label('Quasar').classes('q-ml-xl')
  16. ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
  17. @example('''#### Common UI Elements
  18. NiceGUI comes with a collection of commonly used UI elements.
  19. ''')
  20. def common_elements_example():
  21. from nicegui.events import ValueChangeEventArguments
  22. def show(event: ValueChangeEventArguments):
  23. name = type(event.sender).__name__
  24. ui.notify(f'{name}: {event.value}')
  25. ui.button('Button', on_click=lambda: ui.notify('Click'))
  26. with ui.row():
  27. ui.checkbox('Checkbox', on_change=show)
  28. ui.switch('Switch', on_change=show)
  29. ui.radio(['A', 'B', 'C'], value='A', on_change=show).props('inline')
  30. with ui.row():
  31. ui.input('Text input', on_change=show)
  32. ui.select(['One', 'Two'], value='One', on_change=show)
  33. ui.link('And many more...', '/reference').classes('mt-8')
  34. @example('''#### Value Binding
  35. Binding values between UI elements and data models is built into NiceGUI.
  36. ''')
  37. def binding_example():
  38. class Demo:
  39. def __init__(self):
  40. self.number = 1
  41. demo = Demo()
  42. v = ui.checkbox('visible', value=True)
  43. with ui.column().bind_visibility_from(v, 'value'):
  44. ui.slider(min=1, max=3).bind_value(demo, 'number')
  45. ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(demo, 'number')
  46. ui.number().bind_value(demo, 'number')
  47. def create_full() -> None:
  48. def h3(text: str) -> None:
  49. ui.html(f'<em>{text}</em>').classes('mt-8 text-3xl font-weight-500')
  50. h3('Basic Elements')
  51. @example(ui.label)
  52. def label_example():
  53. ui.label('some label')
  54. @example(ui.icon)
  55. def icon_example():
  56. ui.icon('thumb_up')
  57. @example(ui.link)
  58. def link_example():
  59. ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
  60. @example(ui.button)
  61. def button_example():
  62. ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
  63. @example(ui.badge)
  64. def badge_example():
  65. with ui.button('Click me!', on_click=lambda: badge.set_text(int(badge.text) + 1)):
  66. badge = ui.badge('0', color='red').props('floating')
  67. @example(ui.toggle)
  68. def toggle_example():
  69. toggle1 = ui.toggle([1, 2, 3], value=1)
  70. toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
  71. @example(ui.radio)
  72. def radio_example():
  73. radio1 = ui.radio([1, 2, 3], value=1).props('inline')
  74. radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
  75. @example(ui.select)
  76. def select_example():
  77. select1 = ui.select([1, 2, 3], value=1)
  78. select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
  79. @example(ui.checkbox)
  80. def checkbox_example():
  81. checkbox = ui.checkbox('check me')
  82. ui.label('Check!').bind_visibility_from(checkbox, 'value')
  83. @example(ui.switch)
  84. def switch_example():
  85. switch = ui.switch('switch me')
  86. ui.label('Switch!').bind_visibility_from(switch, 'value')
  87. @example(ui.slider)
  88. def slider_example():
  89. slider = ui.slider(min=0, max=100, value=50).props('label')
  90. ui.label().bind_text_from(slider, 'value')
  91. @example(ui.joystick)
  92. def joystick_example():
  93. ui.joystick(color='blue', size=50,
  94. on_move=lambda e: coordinates.set_text(f"{e.x:.3f}, {e.y:.3f}"),
  95. on_end=lambda _: coordinates.set_text('0, 0'))
  96. coordinates = ui.label('0, 0')
  97. @example(ui.input)
  98. def input_example():
  99. ui.input(label='Text', placeholder='start typing',
  100. on_change=lambda e: input_result.set_text('you typed: ' + e.value))
  101. input_result = ui.label()
  102. @example(ui.number)
  103. def number_example():
  104. ui.number(label='Number', value=3.1415927, format='%.2f',
  105. on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
  106. number_result = ui.label()
  107. @example(ui.color_input)
  108. def color_input_example():
  109. color_label = ui.label('Change my color!')
  110. ui.color_input(label='Color', value='#000000',
  111. on_change=lambda e: color_label.style(f'color:{e.value}'))
  112. @example(ui.color_picker)
  113. def color_picker_example():
  114. picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
  115. button = ui.button(on_click=picker.open).props('icon=colorize')
  116. @example(ui.upload)
  117. def upload_example():
  118. ui.upload(on_upload=lambda e: ui.notify(f'{e.files[0].size} bytes'))
  119. h3('Markdown and HTML')
  120. @example(ui.markdown)
  121. def markdown_example():
  122. ui.markdown('''This is **Markdown**.''')
  123. @example(ui.html)
  124. def html_example():
  125. ui.html('This is <strong>HTML</strong>.')
  126. @example('''#### SVG
  127. You can add Scalable Vector Graphics using the `ui.html` element.
  128. ''')
  129. def svg_example():
  130. content = '''
  131. <svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  132. <circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
  133. <circle cx="80" cy="85" r="8" />
  134. <circle cx="120" cy="85" r="8" />
  135. <path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
  136. </svg>'''
  137. ui.html(content)
  138. h3('Images')
  139. @example(ui.image)
  140. def image_example():
  141. ui.image('http://placeimg.com/640/360/tech')
  142. @example('''#### Captions and Overlays
  143. By nesting elements inside a `ui.image` you can create augmentations.
  144. Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
  145. To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
  146. ''')
  147. def captions_and_overlays_example():
  148. with ui.image('http://placeimg.com/640/360/nature'):
  149. ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
  150. with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
  151. ui.html('''
  152. <svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
  153. <circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
  154. </svg>
  155. ''').classes('bg-transparent')
  156. @example(ui.interactive_image)
  157. def interactive_image_example():
  158. from nicegui.events import MouseEventArguments
  159. def mouse_handler(e: MouseEventArguments):
  160. color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
  161. ii.content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
  162. ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
  163. src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
  164. ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
  165. h3('Data Elements')
  166. @example(ui.table)
  167. def table_example():
  168. table = ui.table({
  169. 'columnDefs': [
  170. {'headerName': 'Name', 'field': 'name'},
  171. {'headerName': 'Age', 'field': 'age'},
  172. ],
  173. 'rowData': [
  174. {'name': 'Alice', 'age': 18},
  175. {'name': 'Bob', 'age': 21},
  176. {'name': 'Carol', 'age': 42},
  177. ],
  178. }).classes('max-h-40')
  179. def update():
  180. table.options['rowData'][0]['age'] += 1
  181. table.update()
  182. ui.button('Update', on_click=update)
  183. @example(ui.chart)
  184. def chart_example():
  185. from numpy.random import random
  186. chart = ui.chart({
  187. 'title': False,
  188. 'chart': {'type': 'bar'},
  189. 'xAxis': {'categories': ['A', 'B']},
  190. 'series': [
  191. {'name': 'Alpha', 'data': [0.1, 0.2]},
  192. {'name': 'Beta', 'data': [0.3, 0.4]},
  193. ],
  194. }).classes('w-full h-64')
  195. def update():
  196. chart.options['series'][0]['data'][:] = random(2)
  197. chart.update()
  198. ui.button('Update', on_click=update)
  199. @example(ui.plot)
  200. def plot_example():
  201. import numpy as np
  202. from matplotlib import pyplot as plt
  203. with ui.plot(figsize=(3, 2)):
  204. x = np.linspace(0.0, 5.0)
  205. y = np.cos(2 * np.pi * x) * np.exp(-x)
  206. plt.plot(x, y, '-')
  207. @example(ui.line_plot)
  208. def line_plot_example():
  209. from datetime import datetime
  210. import numpy as np
  211. line_plot = ui.line_plot(n=2, limit=20, figsize=(3, 2), update_every=5) \
  212. .with_legend(['sin', 'cos'], loc='upper center', ncol=2)
  213. def update_line_plot() -> None:
  214. now = datetime.now()
  215. x = now.timestamp()
  216. y1 = np.sin(x)
  217. y2 = np.cos(x)
  218. line_plot.push([now], [[y1], [y2]])
  219. line_updates = ui.timer(0.1, update_line_plot, active=False)
  220. line_checkbox = ui.checkbox('active').bind_value(line_updates, 'active')
  221. # END OF EXAMPLE
  222. def handle_change(msg: Dict) -> None:
  223. def turn_off() -> None:
  224. line_checkbox.set_value(False)
  225. ui.notify('Turning off that line plot to save resources on our live demo server. 😎')
  226. line_checkbox.value = msg['args']
  227. if line_checkbox.value:
  228. ui.timer(10.0, turn_off, once=True)
  229. line_checkbox.on('update:model-value', handle_change)
  230. @example(ui.linear_progress)
  231. def linear_progress_example():
  232. slider = ui.slider(min=0, max=1, step=0.01, value=0.5)
  233. ui.linear_progress().bind_value_from(slider, 'value')
  234. @example(ui.circular_progress)
  235. def circular_progress_example():
  236. slider = ui.slider(min=0, max=1, step=0.01, value=0.5)
  237. ui.circular_progress().bind_value_from(slider, 'value')
  238. @example(ui.scene)
  239. def scene_example():
  240. with ui.scene(width=285, height=285) as scene:
  241. scene.sphere().material('#4488ff')
  242. scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
  243. scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
  244. with scene.group().move(z=2):
  245. scene.box().move(x=2)
  246. scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
  247. scene.box(wireframe=True).material('#888888').move(x=2, y=2)
  248. scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
  249. scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
  250. logo = 'https://avatars.githubusercontent.com/u/2843826'
  251. scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
  252. [[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
  253. teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
  254. scene.stl(teapot).scale(0.2).move(-3, 4)
  255. scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
  256. scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
  257. @example(ui.tree)
  258. def tree_example():
  259. ui.tree([
  260. {'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
  261. {'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
  262. ], label_key='id', on_select=lambda e: ui.notify(e.value))
  263. @example(ui.log)
  264. def log_example():
  265. from datetime import datetime
  266. log = ui.log(max_lines=10).classes('w-full h-20')
  267. ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime('%X.%f')[:-5]))
  268. h3('Layout')
  269. @example(ui.card)
  270. def card_example():
  271. with ui.card().tight() as card:
  272. ui.image('http://placeimg.com/640/360/nature')
  273. with ui.card_section():
  274. ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
  275. @example(ui.column)
  276. def column_example():
  277. with ui.column():
  278. ui.label('label 1')
  279. ui.label('label 2')
  280. ui.label('label 3')
  281. @example(ui.row)
  282. def row_example():
  283. with ui.row():
  284. ui.label('label 1')
  285. ui.label('label 2')
  286. ui.label('label 3')
  287. @example('''#### Clear Containers
  288. To remove all elements from a row, column or card container, use the `clear()` method.
  289. Alternatively, you can remove individual elements with `remove(element)`, where `element` is an Element or an index.
  290. ''')
  291. def clear_containers_example():
  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('Remove', on_click=lambda: container.remove(0))
  299. ui.button('Clear', on_click=container.clear)
  300. @example(ui.expansion)
  301. def expansion_example():
  302. with ui.expansion('Expand!', icon='work').classes('w-full'):
  303. ui.label('inside the expansion')
  304. @example(ui.menu)
  305. def menu_example():
  306. choice = ui.label('Try the menu.')
  307. with ui.menu() as menu:
  308. ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
  309. ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
  310. ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
  311. ui.separator()
  312. ui.menu_item('Close', on_click=menu.close)
  313. ui.button('Open menu', on_click=menu.open)
  314. @example('''#### Tooltips
  315. Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
  316. For more artistic control you can nest tooltip elements and apply props, classes and styles.
  317. ''')
  318. def tooltips_example():
  319. ui.label('Tooltips...').tooltip('...are shown on mouse over')
  320. with ui.button().props('icon=thumb_up'):
  321. ui.tooltip('I like this').classes('bg-green')
  322. @example(ui.notify)
  323. def notify_example():
  324. ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
  325. @example(ui.dialog)
  326. def dialog_example():
  327. with ui.dialog() as dialog, ui.card():
  328. ui.label('Hello world!')
  329. ui.button('Close', on_click=dialog.close)
  330. ui.button('Open a dialog', on_click=dialog.open)
  331. @example('''#### Awaitable dialog
  332. Dialogs can be awaited.
  333. Use the `submit` method to close the dialog and return a result.
  334. Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
  335. ''')
  336. def async_dialog_example():
  337. with ui.dialog() as dialog, ui.card():
  338. ui.label('Are you sure?')
  339. with ui.row():
  340. ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
  341. ui.button('No', on_click=lambda: dialog.submit('No'))
  342. async def show():
  343. result = await dialog
  344. ui.notify(f'You chose {result}')
  345. ui.button('Await a dialog', on_click=show)
  346. h3('Appearance')
  347. @example('''#### Styling
  348. NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
  349. 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):
  350. Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
  351. You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
  352. If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
  353. All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
  354. ''')
  355. def design_example():
  356. ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
  357. ui.button().props('icon=touch_app outline round').classes('shadow-lg')
  358. ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
  359. @example(ui.colors)
  360. def colors_example():
  361. ui.button('Default', on_click=lambda: ui.colors())
  362. ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
  363. h3('Action')
  364. @example('''#### Lifecycle
  365. You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
  366. - `ui.on_startup`: Called when NiceGUI is started or restarted.
  367. - `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
  368. - `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
  369. - `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
  370. When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
  371. ''', immediate=True)
  372. def lifecycle_example():
  373. import asyncio
  374. l = ui.label()
  375. async def countdown():
  376. for i in [5, 4, 3, 2, 1, 0]:
  377. l.text = f'{i}...' if i else 'Take-off!'
  378. await asyncio.sleep(1)
  379. ui.on_connect(countdown)
  380. @example(ui.timer)
  381. def timer_example():
  382. from datetime import datetime
  383. with ui.row().classes('items-center'):
  384. clock = ui.label()
  385. t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime('%X.%f')[:-5]))
  386. ui.checkbox('active').bind_value(t, 'active')
  387. with ui.row():
  388. def lazy_update() -> None:
  389. new_text = datetime.now().strftime('%X.%f')[:-5]
  390. if lazy_clock.text[:8] == new_text[:8]:
  391. return
  392. lazy_clock.text = new_text
  393. lazy_clock = ui.label()
  394. ui.timer(interval=0.1, callback=lazy_update)
  395. @example(ui.keyboard)
  396. def keyboard_example():
  397. from nicegui.events import KeyEventArguments
  398. def handle_key(e: KeyEventArguments):
  399. if e.key == 'f' and not e.action.repeat:
  400. if e.action.keyup:
  401. ui.notify('f was just released')
  402. elif e.action.keydown:
  403. ui.notify('f was just pressed')
  404. if e.modifiers.shift and e.action.keydown:
  405. if e.key.arrow_left:
  406. ui.notify('going left')
  407. elif e.key.arrow_right:
  408. ui.notify('going right')
  409. elif e.key.arrow_up:
  410. ui.notify('going up')
  411. elif e.key.arrow_down:
  412. ui.notify('going down')
  413. keyboard = ui.keyboard(on_key=handle_key)
  414. ui.label('Key events can be caught globally by using the keyboard element.')
  415. ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
  416. @example('''#### Bindings
  417. NiceGUI is able to directly bind UI elements to models.
  418. Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
  419. Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
  420. To define a one-way binding use the `_from` and `_to` variants of these methods.
  421. Just pass a property of the model as parameter to these methods to create the binding.
  422. ''')
  423. def bindings_example():
  424. class Demo:
  425. def __init__(self):
  426. self.number = 1
  427. demo = Demo()
  428. v = ui.checkbox('visible', value=True)
  429. with ui.column().bind_visibility_from(v, 'value'):
  430. ui.slider(min=1, max=3).bind_value(demo, 'number')
  431. ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(demo, 'number')
  432. ui.number().bind_value(demo, 'number')
  433. @example('''#### UI Updates
  434. 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.
  435. In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
  436. The example code shows both methods for a `ui.chart`, where it is difficult to automatically detect changes in the `options` dictionary.
  437. ''')
  438. def ui_updates_example():
  439. from random import randint
  440. chart = ui.chart({'title': False, 'series': [{'data': [1, 2]}]}).classes('w-full h-64')
  441. def add():
  442. chart.options['series'][0]['data'].append(randint(0, 100))
  443. chart.update()
  444. def clear():
  445. chart.options['series'][0]['data'].clear()
  446. ui.update(chart)
  447. with ui.row():
  448. ui.button('Add', on_click=add)
  449. ui.button('Clear', on_click=clear)
  450. @example('''#### Async event handlers
  451. Most elements also support asynchronous event handlers.
  452. Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
  453. ''')
  454. def async_handlers_example():
  455. import asyncio
  456. async def async_task():
  457. ui.notify('Asynchronous task started')
  458. await asyncio.sleep(5)
  459. ui.notify('Asynchronous task finished')
  460. ui.button('start async task', on_click=async_task)
  461. h3('Pages')
  462. @example(ui.page)
  463. def page_example():
  464. @ui.page('/other_page')
  465. def other_page():
  466. ui.label('Welcome to the other side')
  467. ui.link('Back to main page', '/#page')
  468. @ui.page('/dark_page', dark=True)
  469. def dark_page():
  470. ui.label('Welcome to the dark side')
  471. ui.link('Back to main page', '/#page')
  472. ui.link('Visit other page', other_page)
  473. ui.link('Visit dark page', dark_page)
  474. @example('''#### Auto-index page
  475. Pages created with the `@ui.page` decorator are "private".
  476. Their content is re-created for each client.
  477. Thus, in the example to the right, the displayed ID on the private page changes when the browser reloads the page.
  478. UI elements that are not wrapped in a decorated page function are placed on an automatically generated index page at route "/".
  479. This auto-index page is created once on startup and *shared* across all clients that might connect.
  480. Thus, each connected client will see the *same* elements.
  481. In the example to the right, the displayed ID on the auto-index page remains constant when the browser reloads the page.
  482. ''')
  483. def auto_index_page():
  484. from uuid import uuid4
  485. @ui.page('/private_page')
  486. async def private_page():
  487. ui.label(f'private page with ID {uuid4()}')
  488. ui.label(f'shared auto-index page with ID {uuid4()}')
  489. ui.link('private page', private_page)
  490. @example('''#### Pages with Path Parameters
  491. Page routes can contain parameters like [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/>).
  492. If type-annotated, they are automatically converted to bool, int, float and complex values.
  493. If the page function expects a `request` argument, the request object is automatically provided.
  494. ''')
  495. def page_with_path_parameters_example():
  496. @ui.page('/repeat/{word}/{count}')
  497. def page(word: str, count: int):
  498. ui.label(word * count)
  499. ui.link('Say hi to Santa!', 'repeat/Ho! /3')
  500. @example('''#### Wait for Handshake with Client
  501. To wait for a client connection, you can add a `client` argument to the decorated page function
  502. and await `client.handshake()`.
  503. All code below that statement is executed after the websocket connection between server and client has been established.
  504. For example, this allows you to run JavaScript commands; which is only possible with a client connection (see [#112](https://github.com/zauberzeug/nicegui/issues/112)).
  505. Also it is possible to do async stuff while the user already sees some content.
  506. ''')
  507. def wait_for_handshake_example():
  508. import asyncio
  509. from nicegui import Client
  510. @ui.page('/wait_for_handshake')
  511. async def wait_for_handshake(client: Client):
  512. ui.label('This text is displayed immediately.')
  513. await client.handshake()
  514. await asyncio.sleep(2)
  515. ui.label('This text is displayed 2 seconds after the page has been fully loaded.')
  516. ui.label(f'The IP address {client.ip} was obtained from the websocket.')
  517. ui.link('wait for handshake', wait_for_handshake)
  518. @example('''#### Page Layout
  519. With `ui.header`, `ui.footer`, `ui.left_drawer` and `ui.right_drawer` you can add additional layout elements to a page.
  520. The `fixed` argument controls whether the element should scroll or stay fixed on the screen.
  521. The `top_corner` and `bottom_corner` arguments indicate whether a drawer should expand to the top or bottom of the page.
  522. See <https://quasar.dev/layout/header-and-footer> and <https://quasar.dev/layout/drawer> for more information about possible props like
  523. `elevated`, `bordered` and many more.
  524. With `ui.page_sticky` you can place an element "sticky" on the screen.
  525. See <https://quasar.dev/layout/page-sticky> for more information.
  526. ''')
  527. def page_layout_example():
  528. @ui.page('/page_layout')
  529. async def page_layout():
  530. ui.label('CONTENT')
  531. [ui.label(f'Line {i}') for i in range(100)]
  532. with ui.header().style('background-color: #3874c8').props('elevated'):
  533. ui.label('HEADER')
  534. with ui.left_drawer(top_corner=True, bottom_corner=True).style('background-color: #d7e3f4'):
  535. ui.label('LEFT DRAWER')
  536. with ui.right_drawer(fixed=False).style('background-color: #ebf1fa').props('bordered'):
  537. ui.label('RIGHT DRAWER')
  538. with ui.footer().style('background-color: #3874c8'):
  539. ui.label('FOOTER')
  540. ui.link('show page with fancy layout', page_layout)
  541. @example(ui.open)
  542. def ui_open_example():
  543. @ui.page('/yet_another_page')
  544. def yet_another_page():
  545. ui.label('Welcome to yet another page')
  546. ui.button('RETURN', on_click=lambda: ui.open('/#open'))
  547. ui.button('REDIRECT', on_click=lambda: ui.open(yet_another_page))
  548. @example('''#### Sessions
  549. The optional `request` argument provides insights about the client's URL parameters etc.
  550. It also enables you to identify sessions using a [session middleware](https://www.starlette.io/middleware/#sessionmiddleware).
  551. ''')
  552. def sessions_example():
  553. import uuid
  554. from collections import Counter
  555. from datetime import datetime
  556. from starlette.middleware.sessions import SessionMiddleware
  557. from starlette.requests import Request
  558. from nicegui import app
  559. app.add_middleware(SessionMiddleware, secret_key='some_random_string')
  560. counter = Counter()
  561. start = datetime.now().strftime('%H:%M, %d %B %Y')
  562. @ui.page('/session_demo')
  563. def session_demo(request: Request):
  564. if 'id' not in request.session:
  565. request.session['id'] = str(uuid.uuid4())
  566. counter[request.session['id']] += 1
  567. ui.label(f'{len(counter)} unique views ({sum(counter.values())} overall) since {start}')
  568. ui.link('Visit session demo', session_demo)
  569. @example('''#### JavaScript
  570. With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
  571. The asynchronous function will return after the command(s) are executed.
  572. You can also set `respond=False` to send a command without waiting for a response.
  573. ''')
  574. def javascript_example():
  575. async def alert():
  576. await ui.run_javascript('alert("Hello!")', respond=False)
  577. async def get_date():
  578. time = await ui.run_javascript('Date()')
  579. ui.notify(f'Browser time: {time}')
  580. ui.button('fire and forget', on_click=alert)
  581. ui.button('receive result', on_click=get_date)
  582. h3('Configuration')
  583. @example(ui.run, browser_title='My App')
  584. def ui_run_example():
  585. ui.label('page with custom title')
  586. # ui.run(title='My App')