1
0

reference.py 43 KB

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