reference.py 33 KB

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