documentation.py 33 KB

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