reference.py 41 KB

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