documentation.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. import uuid
  2. from nicegui import app, events, ui
  3. from nicegui.globals import optional_features
  4. from . import demo
  5. from .documentation_tools import element_demo, heading, intro_demo, load_demo, subheading, text_demo
  6. CONSTANT_UUID = str(uuid.uuid4())
  7. def create_intro() -> None:
  8. @intro_demo('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. def formatting_demo():
  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. @intro_demo('Common UI Elements',
  20. 'NiceGUI comes with a collection of commonly used UI elements.')
  21. def common_elements_demo():
  22. from nicegui.events import ValueChangeEventArguments
  23. def show(event: ValueChangeEventArguments):
  24. name = type(event.sender).__name__
  25. ui.notify(f'{name}: {event.value}')
  26. ui.button('Button', on_click=lambda: ui.notify('Click'))
  27. with ui.row():
  28. ui.checkbox('Checkbox', on_change=show)
  29. ui.switch('Switch', on_change=show)
  30. ui.radio(['A', 'B', 'C'], value='A', on_change=show).props('inline')
  31. with ui.row():
  32. ui.input('Text input', on_change=show)
  33. ui.select(['One', 'Two'], value='One', on_change=show)
  34. ui.link('And many more...', '/documentation').classes('mt-8')
  35. @intro_demo('Value Binding',
  36. 'Binding values between UI elements and data models is built into NiceGUI.')
  37. def binding_demo():
  38. class Demo:
  39. def __init__(self):
  40. self.number = 1
  41. demo = Demo()
  42. v = ui.checkbox('visible', value=True)
  43. with ui.column().bind_visibility_from(v, 'value'):
  44. ui.slider(min=1, max=3).bind_value(demo, 'number')
  45. ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(demo, 'number')
  46. ui.number().bind_value(demo, 'number')
  47. def create_full() -> None:
  48. heading('Basic Elements')
  49. load_demo(ui.label)
  50. load_demo(ui.icon)
  51. load_demo(ui.avatar)
  52. load_demo(ui.link)
  53. load_demo(ui.button)
  54. load_demo(ui.badge)
  55. load_demo(ui.toggle)
  56. load_demo(ui.radio)
  57. load_demo(ui.select)
  58. load_demo(ui.checkbox)
  59. load_demo(ui.switch)
  60. load_demo(ui.slider)
  61. load_demo(ui.joystick)
  62. load_demo(ui.input)
  63. load_demo(ui.textarea)
  64. load_demo(ui.number)
  65. load_demo(ui.knob)
  66. load_demo(ui.color_input)
  67. load_demo(ui.color_picker)
  68. load_demo(ui.date)
  69. load_demo(ui.time)
  70. load_demo(ui.upload)
  71. load_demo(ui.chat_message)
  72. load_demo(ui.element)
  73. heading('Markdown and HTML')
  74. load_demo(ui.markdown)
  75. load_demo(ui.mermaid)
  76. load_demo(ui.html)
  77. @text_demo('SVG',
  78. 'You can add Scalable Vector Graphics using the `ui.html` element.')
  79. def svg_demo():
  80. content = '''
  81. <svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  82. <circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
  83. <circle cx="80" cy="85" r="8" />
  84. <circle cx="120" cy="85" r="8" />
  85. <path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
  86. </svg>'''
  87. ui.html(content)
  88. heading('Images, Audio and Video')
  89. load_demo(ui.image)
  90. @text_demo('Captions and Overlays', '''
  91. By nesting elements inside a `ui.image` you can create augmentations.
  92. Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
  93. To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
  94. ''')
  95. def captions_and_overlays_demo():
  96. with ui.image('https://picsum.photos/id/29/640/360'):
  97. ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
  98. with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
  99. ui.html('''
  100. <svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
  101. <circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
  102. </svg>
  103. ''').classes('bg-transparent')
  104. load_demo(ui.interactive_image)
  105. load_demo(ui.audio)
  106. load_demo(ui.video)
  107. heading('Data Elements')
  108. load_demo(ui.table)
  109. load_demo(ui.aggrid)
  110. load_demo(ui.chart)
  111. load_demo(ui.echart)
  112. if 'matplotlib' in optional_features:
  113. load_demo(ui.pyplot)
  114. load_demo(ui.line_plot)
  115. if 'plotly' in optional_features:
  116. load_demo(ui.plotly)
  117. load_demo(ui.linear_progress)
  118. load_demo(ui.circular_progress)
  119. load_demo(ui.spinner)
  120. load_demo(ui.scene)
  121. load_demo(ui.tree)
  122. load_demo(ui.log)
  123. load_demo(ui.editor)
  124. load_demo(ui.code)
  125. load_demo(ui.json_editor)
  126. heading('Layout')
  127. load_demo(ui.card)
  128. load_demo(ui.column)
  129. load_demo(ui.row)
  130. load_demo(ui.grid)
  131. @text_demo('Clear Containers', '''
  132. To remove all elements from a row, column or card container, use can call
  133. ```py
  134. container.clear()
  135. ```
  136. Alternatively, you can remove individual elements by calling
  137. - `container.remove(element: Element)`,
  138. - `container.remove(index: int)`, or
  139. - `element.delete()`.
  140. ''')
  141. def clear_containers_demo():
  142. container = ui.row()
  143. def add_face():
  144. with container:
  145. ui.icon('face')
  146. add_face()
  147. ui.button('Add', on_click=add_face)
  148. ui.button('Remove', on_click=lambda: container.remove(0) if list(container) else None)
  149. ui.button('Clear', on_click=container.clear)
  150. load_demo(ui.expansion)
  151. load_demo(ui.scroll_area)
  152. load_demo(ui.separator)
  153. load_demo(ui.splitter)
  154. load_demo('tabs')
  155. load_demo(ui.stepper)
  156. load_demo(ui.timeline)
  157. load_demo(ui.carousel)
  158. load_demo(ui.menu)
  159. load_demo(ui.context_menu)
  160. @text_demo('Tooltips', '''
  161. Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
  162. For more artistic control you can nest tooltip elements and apply props, classes and styles.
  163. ''')
  164. def tooltips_demo():
  165. ui.label('Tooltips...').tooltip('...are shown on mouse over')
  166. with ui.button(icon='thumb_up'):
  167. ui.tooltip('I like this').classes('bg-green')
  168. load_demo(ui.notify)
  169. load_demo(ui.dialog)
  170. heading('Appearance')
  171. @text_demo('Styling', '''
  172. NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
  173. 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):
  174. Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
  175. Props with a leading `:` can contain JavaScript expressions that are evaluated on the client.
  176. You can also apply [Tailwind CSS](https://tailwindcss.com/) utility classes with the `classes` method.
  177. If you really need to apply CSS, you can use the `style` method. Here the delimiter is `;` instead of a blank space.
  178. All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
  179. ''')
  180. def design_demo():
  181. ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
  182. ui.button(icon='touch_app').props('outline round').classes('shadow-lg')
  183. ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
  184. subheading('Try styling NiceGUI elements!')
  185. ui.markdown('''
  186. Try out how
  187. [Tailwind CSS classes](https://tailwindcss.com/),
  188. [Quasar props](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components),
  189. and CSS styles affect NiceGUI elements.
  190. ''').classes('bold-links arrow-links mb-[-1rem]')
  191. with ui.row():
  192. ui.label('Select an element from those available and start styling it!').classes('mx-auto my-auto')
  193. select_element = ui.select({
  194. ui.label: 'ui.label',
  195. ui.checkbox: 'ui.checkbox',
  196. ui.switch: 'ui.switch',
  197. ui.input: 'ui.input',
  198. ui.textarea: 'ui.textarea',
  199. ui.button: 'ui.button',
  200. }, value=ui.button, on_change=lambda: live_demo_ui.refresh()).props('dense')
  201. @ui.refreshable
  202. def live_demo_ui():
  203. with ui.column().classes('w-full items-stretch gap-8 no-wrap min-[1500px]:flex-row'):
  204. with demo.python_window(classes='w-full max-w-[44rem]'):
  205. with ui.column().classes('w-full gap-4'):
  206. ui.markdown(f'''
  207. ```py
  208. from nicegui import ui
  209. element = {select_element.options[select_element.value]}('element')
  210. ```
  211. ''').classes('mb-[-0.25em]')
  212. with ui.row().classes('items-center gap-0 w-full px-2'):
  213. def handle_classes(e: events.ValueChangeEventArguments):
  214. try:
  215. element.classes(replace=e.value)
  216. except ValueError:
  217. pass
  218. ui.markdown("`element.classes('`")
  219. ui.input(on_change=handle_classes).classes('mt-[-0.5em] text-mono grow').props('dense')
  220. ui.markdown("`')`")
  221. with ui.row().classes('items-center gap-0 w-full px-2'):
  222. def handle_props(e: events.ValueChangeEventArguments):
  223. element._props = {'label': 'Button', 'color': 'primary'}
  224. try:
  225. element.props(e.value)
  226. except ValueError:
  227. pass
  228. element.update()
  229. ui.markdown("`element.props('`")
  230. ui.input(on_change=handle_props).classes('mt-[-0.5em] text-mono grow').props('dense')
  231. ui.markdown("`')`")
  232. with ui.row().classes('items-center gap-0 w-full px-2'):
  233. def handle_style(e: events.ValueChangeEventArguments):
  234. try:
  235. element.style(replace=e.value)
  236. except ValueError:
  237. pass
  238. ui.markdown("`element.style('`")
  239. ui.input(on_change=handle_style).classes('mt-[-0.5em] text-mono grow').props('dense')
  240. ui.markdown("`')`")
  241. ui.markdown('''
  242. ```py
  243. ui.run()
  244. ```
  245. ''')
  246. with demo.browser_window(classes='w-full max-w-[44rem] min-[1500px]:max-w-[20rem] min-h-[10rem] browser-window'):
  247. element: ui.element = select_element.value("element")
  248. live_demo_ui()
  249. @text_demo('Tailwind CSS', '''
  250. [Tailwind CSS](https://tailwindcss.com/) is a CSS framework for rapidly building custom user interfaces.
  251. NiceGUI provides a fluent, auto-complete friendly interface for adding Tailwind classes to UI elements.
  252. You can discover available classes by navigating the methods of the `tailwind` property.
  253. The builder pattern allows you to chain multiple classes together (as shown with "Label A").
  254. You can also call the `tailwind` property with a list of classes (as shown with "Label B").
  255. Although this is very similar to using the `classes` method, it is more convenient for Tailwind classes due to auto-completion.
  256. Last but not least, you can also predefine a style and apply it to multiple elements (labels C and D).
  257. ''')
  258. def tailwind_demo():
  259. from nicegui import Tailwind
  260. ui.label('Label A').tailwind.font_weight('extrabold').text_color('blue-600').background_color('orange-200')
  261. ui.label('Label B').tailwind('drop-shadow', 'font-bold', 'text-green-600')
  262. red_style = Tailwind().text_color('red-600').font_weight('bold')
  263. label_c = ui.label('Label C')
  264. red_style.apply(label_c)
  265. ui.label('Label D').tailwind(red_style)
  266. load_demo(ui.query)
  267. load_demo(ui.colors)
  268. load_demo(ui.dark_mode)
  269. heading('Action')
  270. load_demo(ui.timer)
  271. load_demo(ui.keyboard)
  272. load_demo('bindings')
  273. @text_demo('UI Updates', '''
  274. 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.
  275. In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
  276. The demo code shows both methods for a `ui.chart`, where it is difficult to automatically detect changes in the `options` dictionary.
  277. ''')
  278. def ui_updates_demo():
  279. from random import randint
  280. chart = ui.chart({'title': False, 'series': [{'data': [1, 2]}]}).classes('w-full h-64')
  281. def add():
  282. chart.options['series'][0]['data'].append(randint(0, 100))
  283. chart.update()
  284. def clear():
  285. chart.options['series'][0]['data'].clear()
  286. ui.update(chart)
  287. with ui.row():
  288. ui.button('Add', on_click=add)
  289. ui.button('Clear', on_click=clear)
  290. load_demo(ui.refreshable)
  291. @text_demo('Async event handlers', '''
  292. Most elements also support asynchronous event handlers.
  293. Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
  294. ''')
  295. def async_handlers_demo():
  296. import asyncio
  297. async def async_task():
  298. ui.notify('Asynchronous task started')
  299. await asyncio.sleep(5)
  300. ui.notify('Asynchronous task finished')
  301. ui.button('start async task', on_click=async_task)
  302. @text_demo('Running CPU-bound tasks', '''
  303. NiceGUI provides a `cpu_bound` function for running CPU-bound tasks in a separate process.
  304. This is useful for long-running computations that would otherwise block the event loop and make the UI unresponsive.
  305. The function returns a future that can be awaited.
  306. ''')
  307. def cpu_bound_demo():
  308. import time
  309. from nicegui import run
  310. def compute_sum(a: float, b: float) -> float:
  311. time.sleep(1) # simulate a long-running computation
  312. return a + b
  313. async def handle_click():
  314. result = await run.cpu_bound(compute_sum, 1, 2)
  315. ui.notify(f'Sum is {result}')
  316. # ui.button('Compute', on_click=handle_click)
  317. # END OF DEMO
  318. async def mock_click():
  319. import asyncio
  320. await asyncio.sleep(1)
  321. ui.notify('Sum is 3')
  322. ui.button('Compute', on_click=mock_click)
  323. @text_demo('Running I/O-bound tasks', '''
  324. NiceGUI provides an `io_bound` function for running I/O-bound tasks in a separate thread.
  325. This is useful for long-running I/O operations that would otherwise block the event loop and make the UI unresponsive.
  326. The function returns a future that can be awaited.
  327. ''')
  328. def io_bound_demo():
  329. import requests
  330. from nicegui import run
  331. async def handle_click():
  332. URL = 'https://httpbin.org/delay/1'
  333. response = await run.io_bound(requests.get, URL, timeout=3)
  334. ui.notify(f'Downloaded {len(response.content)} bytes')
  335. ui.button('Download', on_click=handle_click)
  336. heading('Pages')
  337. load_demo(ui.page)
  338. @text_demo('Auto-index page', '''
  339. Pages created with the `@ui.page` decorator are "private".
  340. Their content is re-created for each client.
  341. Thus, in the demo to the right, the displayed ID on the private page changes when the browser reloads the page.
  342. UI elements that are not wrapped in a decorated page function are placed on an automatically generated index page at route "/".
  343. This auto-index page is created once on startup and *shared* across all clients that might connect.
  344. Thus, each connected client will see the *same* elements.
  345. In the demo to the right, the displayed ID on the auto-index page remains constant when the browser reloads the page.
  346. ''')
  347. def auto_index_page():
  348. from uuid import uuid4
  349. @ui.page('/private_page')
  350. async def private_page():
  351. ui.label(f'private page with ID {uuid4()}')
  352. # ui.label(f'shared auto-index page with ID {uuid4()}')
  353. # ui.link('private page', private_page)
  354. # END OF DEMO
  355. ui.label(f'shared auto-index page with ID {CONSTANT_UUID}')
  356. ui.link('private page', private_page)
  357. @text_demo('Page Layout', '''
  358. With `ui.header`, `ui.footer`, `ui.left_drawer` and `ui.right_drawer` you can add additional layout elements to a page.
  359. The `fixed` argument controls whether the element should scroll or stay fixed on the screen.
  360. The `top_corner` and `bottom_corner` arguments indicate whether a drawer should expand to the top or bottom of the page.
  361. See <https://quasar.dev/layout/header-and-footer> and <https://quasar.dev/layout/drawer> for more information about possible props.
  362. With `ui.page_sticky` you can place an element "sticky" on the screen.
  363. See <https://quasar.dev/layout/page-sticky> for more information.
  364. ''')
  365. def page_layout_demo():
  366. @ui.page('/page_layout')
  367. def page_layout():
  368. ui.label('CONTENT')
  369. [ui.label(f'Line {i}') for i in range(100)]
  370. with ui.header(elevated=True).style('background-color: #3874c8').classes('items-center justify-between'):
  371. ui.label('HEADER')
  372. ui.button(on_click=lambda: right_drawer.toggle(), icon='menu').props('flat color=white')
  373. with ui.left_drawer(top_corner=True, bottom_corner=True).style('background-color: #d7e3f4'):
  374. ui.label('LEFT DRAWER')
  375. with ui.right_drawer(fixed=False).style('background-color: #ebf1fa').props('bordered') as right_drawer:
  376. ui.label('RIGHT DRAWER')
  377. with ui.footer().style('background-color: #3874c8'):
  378. ui.label('FOOTER')
  379. ui.link('show page with fancy layout', page_layout)
  380. load_demo(ui.open)
  381. load_demo(ui.download)
  382. load_demo('storage')
  383. @text_demo('Parameter injection', '''
  384. Thanks to FastAPI, a page function accepts optional parameters to provide
  385. [path parameters](https://fastapi.tiangolo.com/tutorial/path-params/),
  386. [query parameters](https://fastapi.tiangolo.com/tutorial/query-params/) or the whole incoming
  387. [request](https://fastapi.tiangolo.com/advanced/using-request-directly/) for accessing
  388. the body payload, headers, cookies and more.
  389. ''')
  390. def parameter_demo():
  391. @ui.page('/icon/{icon}')
  392. def icons(icon: str, amount: int = 1):
  393. ui.label(icon).classes('text-h3')
  394. with ui.row():
  395. [ui.icon(icon).classes('text-h3') for _ in range(amount)]
  396. ui.link('Star', '/icon/star?amount=5')
  397. ui.link('Home', '/icon/home')
  398. ui.link('Water', '/icon/water_drop?amount=3')
  399. load_demo(ui.run_javascript)
  400. heading('Routes')
  401. subheading('Static files')
  402. @element_demo(app.add_static_files)
  403. def add_static_files_demo():
  404. from nicegui import app
  405. app.add_static_files('/examples', 'examples')
  406. ui.label('Some NiceGUI Examples').classes('text-h5')
  407. ui.link('AI interface', '/examples/ai_interface/main.py')
  408. ui.link('Custom FastAPI app', '/examples/fastapi/main.py')
  409. ui.link('Authentication', '/examples/authentication/main.py')
  410. subheading('Media files')
  411. @element_demo(app.add_media_files)
  412. def add_media_files_demo():
  413. from pathlib import Path
  414. import requests
  415. from nicegui import app
  416. media = Path('media')
  417. # media.mkdir(exist_ok=True)
  418. # r = requests.get('https://cdn.coverr.co/videos/coverr-cloudy-sky-2765/1080p.mp4')
  419. # (media / 'clouds.mp4').write_bytes(r.content)
  420. # app.add_media_files('/my_videos', media)
  421. # ui.video('/my_videos/clouds.mp4')
  422. # END OF DEMO
  423. ui.video('https://cdn.coverr.co/videos/coverr-cloudy-sky-2765/1080p.mp4')
  424. @text_demo('API Responses', '''
  425. NiceGUI is based on [FastAPI](https://fastapi.tiangolo.com/).
  426. This means you can use all of FastAPI's features.
  427. For example, you can implement a RESTful API in addition to your graphical user interface.
  428. You simply import the `app` object from `nicegui`.
  429. 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()`.
  430. You can also return any other FastAPI response object inside a page function.
  431. For example, you can return a `RedirectResponse` to redirect the user to another page if certain conditions are met.
  432. This is used in our [authentication demo](https://github.com/zauberzeug/nicegui/tree/main/examples/authentication/main.py).
  433. ''')
  434. def fastapi_demo():
  435. import random
  436. from nicegui import app
  437. @app.get('/random/{max}')
  438. def generate_random_number(max: int):
  439. return {'min': 0, 'max': max, 'value': random.randint(0, max)}
  440. max = ui.number('max', value=100)
  441. ui.button('generate random number', on_click=lambda: ui.open(f'/random/{max.value:.0f}'))
  442. heading('Lifecycle')
  443. @text_demo('Events', '''
  444. You can register coroutines or functions to be called for the following events:
  445. - `app.on_startup`: called when NiceGUI is started or restarted
  446. - `app.on_shutdown`: called when NiceGUI is shut down or restarted
  447. - `app.on_connect`: called for each client which connects (optional argument: nicegui.Client)
  448. - `app.on_disconnect`: called for each client which disconnects (optional argument: nicegui.Client)
  449. - `app.on_exception`: called when an exception occurs (optional argument: exception)
  450. When NiceGUI is shut down or restarted, all tasks still in execution will be automatically canceled.
  451. ''')
  452. def lifecycle_demo():
  453. from datetime import datetime
  454. from nicegui import app
  455. # dt = datetime.now()
  456. def handle_connection():
  457. global dt
  458. dt = datetime.now()
  459. app.on_connect(handle_connection)
  460. label = ui.label()
  461. ui.timer(1, lambda: label.set_text(f'Last new connection: {dt:%H:%M:%S}'))
  462. # END OF DEMO
  463. global dt
  464. dt = datetime.now()
  465. subheading('Shutdown')
  466. @element_demo(app.shutdown)
  467. def shutdown_demo():
  468. from nicegui import app
  469. # ui.button('shutdown', on_click=app.shutdown)
  470. #
  471. # ui.run(reload=False)
  472. # END OF DEMO
  473. ui.button('shutdown', on_click=lambda: ui.notify(
  474. 'Nah. We do not actually shutdown the documentation server. Try it in your own app!'))
  475. @text_demo('URLs', '''
  476. You can access the list of all URLs on which the NiceGUI app is available via `app.urls`.
  477. The URLs are not available in `app.on_startup` because the server is not yet running.
  478. Instead, you can access them in a page function or register a callback with `app.urls.on_change`.
  479. ''')
  480. def urls_demo():
  481. from nicegui import app
  482. # @ui.page('/')
  483. # def index():
  484. # for url in app.urls:
  485. # ui.link(url, target=url)
  486. # END OF DEMO
  487. ui.link('https://nicegui.io', target='https://nicegui.io')
  488. heading('NiceGUI Fundamentals')
  489. @text_demo('Auto-context', '''
  490. In order to allow writing intuitive UI descriptions, NiceGUI automatically tracks the context in which elements are created.
  491. This means that there is no explicit `parent` parameter.
  492. Instead the parent context is defined using a `with` statement.
  493. It is also passed to event handlers and timers.
  494. In the demo, the label "Card content" is added to the card.
  495. And because the `ui.button` is also added to the card, the label "Click!" will also be created in this context.
  496. The label "Tick!", which is added once after one second, is also added to the card.
  497. This design decision allows for easily creating modular components that keep working after moving them around in the UI.
  498. For example, you can move label and button somewhere else, maybe wrap them in another container, and the code will still work.
  499. ''')
  500. def auto_context_demo():
  501. with ui.card():
  502. ui.label('Card content')
  503. ui.button('Add label', on_click=lambda: ui.label('Click!'))
  504. ui.timer(1.0, lambda: ui.label('Tick!'), once=True)
  505. load_demo('generic_events')
  506. heading('Configuration')
  507. load_demo(ui.run)
  508. @text_demo('Native Mode', '''
  509. You can enable native mode for NiceGUI by specifying `native=True` in the `ui.run` function.
  510. To customize the initial window size and display mode, use the `window_size` and `fullscreen` parameters respectively.
  511. Additionally, you can provide extra keyword arguments via `app.native.window_args` and `app.native.start_args`.
  512. Pick any parameter as it is defined by the internally used [pywebview module](https://pywebview.flowrl.com/guide/api.html)
  513. for the `webview.create_window` and `webview.start` functions.
  514. Note that these keyword arguments will take precedence over the parameters defined in `ui.run`.
  515. In native mode the `app.native.main_window` object allows you to access the underlying window.
  516. It is an async version of [`Window` from pywebview](https://pywebview.flowrl.com/guide/api.html#window-object).
  517. ''', tab=lambda: ui.label('NiceGUI'))
  518. def native_mode_demo():
  519. from nicegui import app
  520. app.native.window_args['resizable'] = False
  521. app.native.start_args['debug'] = True
  522. ui.label('app running in native mode')
  523. # ui.button('enlarge', on_click=lambda: app.native.main_window.resize(1000, 700))
  524. #
  525. # ui.run(native=True, window_size=(400, 300), fullscreen=False)
  526. # END OF DEMO
  527. ui.button('enlarge', on_click=lambda: ui.notify('window will be set to 1000x700 in native mode'))
  528. # Show a helpful workaround until issue is fixed upstream.
  529. # For more info see: https://github.com/r0x0r/pywebview/issues/1078
  530. ui.markdown('''
  531. If webview has trouble finding required libraries, you may get an error relating to "WebView2Loader.dll".
  532. To work around this issue, try moving the DLL file up a directory, e.g.:
  533. * from `.venv/Lib/site-packages/webview/lib/x64/WebView2Loader.dll`
  534. * to `.venv/Lib/site-packages/webview/lib/WebView2Loader.dll`
  535. ''')
  536. @text_demo('Environment Variables', '''
  537. You can set the following environment variables to configure NiceGUI:
  538. - `MATPLOTLIB` (default: true) can be set to `false` to avoid the potentially costly import of Matplotlib.
  539. This will make `ui.pyplot` and `ui.line_plot` unavailable.
  540. - `NICEGUI_STORAGE_PATH` (default: local ".nicegui") can be set to change the location of the storage files.
  541. - `MARKDOWN_CONTENT_CACHE_SIZE` (default: 1000): The maximum number of Markdown content snippets that are cached in memory.
  542. - `NO_NETIFACES` (default: `false`): Can be set to `true` to hide the netifaces startup warning (e.g. in docker container).
  543. ''')
  544. def env_var_demo():
  545. from nicegui.elements import markdown
  546. ui.label(f'Markdown content cache size is {markdown.prepare_content.cache_info().maxsize}')
  547. heading('Deployment')
  548. subheading('Server Hosting')
  549. ui.markdown('''
  550. 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.
  551. 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.
  552. 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.
  553. 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.
  554. With this command you can launch the script `main.py` in the current directory on the public port 80:
  555. ''').classes('bold-links arrow-links')
  556. with demo.bash_window(classes='max-w-lg w-full h-44'):
  557. ui.markdown('''
  558. ```bash
  559. docker run -it --restart always \\
  560. -p 80:8080 \\
  561. -e PUID=$(id -u) \\
  562. -e PGID=$(id -g) \\
  563. -v $(pwd)/:/app/ \\
  564. zauberzeug/nicegui:latest
  565. ```
  566. ''')
  567. ui.markdown('''
  568. The demo assumes `main.py` uses the port 8080 in the `ui.run` command (which is the default).
  569. 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.
  570. Of course this can also be written in a Docker compose file:
  571. ''')
  572. with demo.python_window('docker-compose.yml', classes='max-w-lg w-full h-60'):
  573. ui.markdown('''
  574. ```yaml
  575. app:
  576. image: zauberzeug/nicegui:latest
  577. restart: always
  578. ports:
  579. - 80:8080
  580. environment:
  581. - PUID=1000 # change this to your user id
  582. - PGID=1000 # change this to your group id
  583. volumes:
  584. - ./:/app/
  585. ```
  586. ''')
  587. ui.markdown('''
  588. There are other handy features in the Docker image like non-root user execution and signal pass-through.
  589. For more details we recommend to have a look at our [Docker example](https://github.com/zauberzeug/nicegui/tree/main/examples/docker_image).
  590. ''').classes('bold-links arrow-links')
  591. ui.markdown('''
  592. You can provide SSL certificates directly using [FastAPI](https://fastapi.tiangolo.com/deployment/https/).
  593. 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.
  594. See our development [docker-compose.yml](https://github.com/zauberzeug/nicegui/blob/main/docker-compose.yml) as an example.
  595. You may also have a look at [our demo for using a custom FastAPI app](https://github.com/zauberzeug/nicegui/tree/main/examples/fastapi).
  596. This will allow you to do very flexible deployments as described in the [FastAPI documentation](https://fastapi.tiangolo.com/deployment/).
  597. Note that there are additional steps required to allow multiple workers.
  598. ''').classes('bold-links arrow-links')
  599. subheading('Package for Installation')
  600. ui.markdown('''
  601. NiceGUI apps can also be bundled into an executable with [PyInstaller](https://www.pyinstaller.org/).
  602. This allows you to distribute your app as a single file that can be executed on any computer.
  603. Just take care your `ui.run` command does not use the `reload` argument.
  604. Running the `build.py` below will create an executable `myapp` in the `dist` folder:
  605. ''').classes('bold-links arrow-links')
  606. with ui.row().classes('w-full items-stretch'):
  607. with demo.python_window(classes='max-w-lg w-full'):
  608. ui.markdown('''
  609. ```python
  610. from nicegui import native_mode, ui
  611. ui.label('Hello from PyInstaller')
  612. ui.run(reload=False, port=native_mode.find_open_port())
  613. ```
  614. ''')
  615. with demo.python_window('build.py', classes='max-w-lg w-full'):
  616. ui.markdown('''
  617. ```python
  618. import os
  619. import subprocess
  620. from pathlib import Path
  621. import nicegui
  622. cmd = [
  623. 'python',
  624. '-m', 'PyInstaller',
  625. 'main.py', # your main file with ui.run()
  626. '--name', 'myapp', # name of your app
  627. '--onefile',
  628. #'--windowed', # prevent console appearing, only use with ui.run(native=True, ...)
  629. '--add-data', f'{Path(nicegui.__file__).parent}{os.pathsep}nicegui'
  630. ]
  631. subprocess.call(cmd)
  632. ```
  633. ''')
  634. ui.markdown('''
  635. **Packaging Tips**
  636. - When building a PyInstaller app, your main script can use a native window (rather than a browser window) by
  637. using `ui.run(reload=False, native=True)`.
  638. The `native` parameter can be `True` or `False` depending on whether you want a native window or to launch a
  639. page in the user's browser - either will work in the PyInstaller generated app.
  640. - Specifying `--windowed` to PyInstaller will prevent a terminal console from appearing.
  641. However you should only use this option if you have also specified `native=True` in your `ui.run` command.
  642. Without a terminal console the user won't be able to exit the app by pressing Ctrl-C.
  643. With the `native=True` option, the app will automatically close when the window is closed, as expected.
  644. - Specifying `--windowed` to PyInstaller will create an `.app` file on Mac which may be more convenient to distribute.
  645. When you double-click the app to run it, it will not show any console output.
  646. You can also run the app from the command line with `./myapp.app/Contents/MacOS/myapp` to see the console output.
  647. - Specifying `--onefile` to PyInstaller will create a single executable file.
  648. Whilst convenient for distribution, it will be slower to start up.
  649. This is not NiceGUI's fault but just the way Pyinstaller zips things into a single file, then unzips everything
  650. into a temporary directory before running.
  651. You can mitigate this by removing `--onefile` from the PyInstaller command,
  652. and zip up the generated `dist` directory yourself, distribute it,
  653. and your end users can unzip once and be good to go,
  654. without the constant expansion of files due to the `--onefile` flag.
  655. - Summary of user experience for different options:
  656. | PyInstaller | `ui.run(...)` | Explanation |
  657. | :--- | :--- | :--- |
  658. | `onefile` | `native=False` | Single executable generated in `dist/`, runs in browser |
  659. | `onefile` | `native=True` | Single executable generated in `dist/`, runs in popup window |
  660. | `onefile` and `windowed` | `native=True` | Single executable generated in `dist/` (on Mac a proper `dist/myapp.app` generated incl. icon), runs in popup window, no console appears |
  661. | `onefile` and `windowed` | `native=False` | Avoid (no way to exit the app) |
  662. | Specify neither | | A `dist/myapp` directory created which can be zipped manually and distributed; run with `dist/myapp/myapp` |
  663. - If you are using a Python virtual environment, ensure you `pip install pyinstaller` within your virtual environment
  664. so that the correct PyInstaller is used, or you may get broken apps due to the wrong version of PyInstaller being picked up.
  665. That is why the build script invokes PyInstaller using `python -m PyInstaller` rather than just `pyinstaller`.
  666. ''').classes('bold-links arrow-links')
  667. with demo.bash_window(classes='max-w-lg w-full h-42 self-center'):
  668. ui.markdown('''
  669. ```bash
  670. python -m venv venv
  671. source venv/bin/activate
  672. pip install nicegui
  673. pip install pyinstaller
  674. ```
  675. ''')
  676. ui.markdown('''
  677. **Note:**
  678. If you're getting an error "TypeError: a bytes-like object is required, not 'str'", try adding the following lines to the top of your `main.py` file:
  679. ```py
  680. import sys
  681. sys.stdout = open('logs.txt', 'w')
  682. ```
  683. See <https://github.com/zauberzeug/nicegui/issues/681> for more information.
  684. ''').classes('bold-links arrow-links')
  685. subheading('NiceGUI On Air')
  686. ui.markdown('''
  687. By using `ui.run(on_air=True)` you can share your local app with others over the internet 🧞.
  688. When accessing the on-air URL, all libraries (like Vue, Quasar, ...) are loaded from our CDN.
  689. Thereby only the raw content and events need to be transmitted by your local app.
  690. This makes it blazing fast even if your app only has a poor internet connection (e.g. a mobile robot in the field).
  691. By setting `on_air=True` you will get a random URL which is valid for 1 hour.
  692. If you sign-up at <https://on-air.nicegui.io> you get a token which could be used to identify your device: `ui.run(on_air='<your token>'`).
  693. This will give you a fixed URL and the possibility to protect remote access with a passphrase.
  694. Currently On Air is available as a tech preview and can be used free of charge (for now).
  695. We will gradually improve stability, introduce payment options and extend the service with multi-device management, remote terminal access and more.
  696. Please let us know your feedback on [GitHub](https://github.com/zauberzeug/nicegui/discussions),
  697. [Reddit](https://www.reddit.com/r/nicegui/), or [Discord](https://discord.gg/TEpFeAaF4f).
  698. **Data Privacy:**
  699. We take your privacy very serious.
  700. NiceGUI On Air does not log or store any content of the relayed data.
  701. ''').classes('bold-links arrow-links')
  702. ui.element('div').classes('h-32')