reference.py 30 KB

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