documentation.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  1. import uuid
  2. from nicegui import app, 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.element)
  71. heading('Markdown and HTML')
  72. load_demo(ui.markdown)
  73. load_demo(ui.mermaid)
  74. load_demo(ui.html)
  75. @text_demo('SVG',
  76. 'You can add Scalable Vector Graphics using the `ui.html` element.')
  77. def svg_demo():
  78. content = '''
  79. <svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  80. <circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
  81. <circle cx="80" cy="85" r="8" />
  82. <circle cx="120" cy="85" r="8" />
  83. <path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
  84. </svg>'''
  85. ui.html(content)
  86. heading('Images, Audio and Video')
  87. load_demo(ui.image)
  88. @text_demo('Captions and Overlays', '''
  89. By nesting elements inside a `ui.image` you can create augmentations.
  90. Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
  91. To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
  92. ''')
  93. def captions_and_overlays_demo():
  94. with ui.image('https://picsum.photos/id/29/640/360'):
  95. ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
  96. with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
  97. ui.html('''
  98. <svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
  99. <circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
  100. </svg>
  101. ''').classes('bg-transparent')
  102. load_demo(ui.interactive_image)
  103. load_demo(ui.audio)
  104. load_demo(ui.video)
  105. heading('Data Elements')
  106. load_demo(ui.table)
  107. load_demo(ui.aggrid)
  108. load_demo(ui.chart)
  109. load_demo(ui.pyplot)
  110. load_demo(ui.line_plot)
  111. load_demo(ui.plotly)
  112. load_demo(ui.linear_progress)
  113. load_demo(ui.circular_progress)
  114. load_demo(ui.spinner)
  115. load_demo(ui.scene)
  116. load_demo(ui.tree)
  117. load_demo(ui.log)
  118. heading('Layout')
  119. load_demo(ui.card)
  120. load_demo(ui.column)
  121. load_demo(ui.row)
  122. @text_demo('Clear Containers', '''
  123. To remove all elements from a row, column or card container, use the `clear()` method.
  124. Alternatively, you can remove individual elements with `remove(element)`, where `element` is an Element or an index.
  125. ''')
  126. def clear_containers_demo():
  127. container = ui.row()
  128. def add_face():
  129. with container:
  130. ui.icon('face')
  131. add_face()
  132. ui.button('Add', on_click=add_face)
  133. ui.button('Remove', on_click=lambda: container.remove(0))
  134. ui.button('Clear', on_click=container.clear)
  135. load_demo(ui.expansion)
  136. load_demo(ui.splitter)
  137. @text_demo('Tabs', '''
  138. The elements `ui.tabs`, `ui.tab`, `ui.tab_panels`, and `ui.tab_panel` resemble
  139. [Quasar's tabs](https://quasar.dev/vue-components/tabs)
  140. and [tab panels](https://quasar.dev/vue-components/tab-panels) API.
  141. `ui.tabs` creates a container for the tabs. This could be placed in a `ui.header` for example.
  142. `ui.tab_panels` creates a container for the tab panels with the actual content.
  143. ''')
  144. def tabs_demo():
  145. with ui.tabs() as tabs:
  146. ui.tab('Home', icon='home')
  147. ui.tab('About', icon='info')
  148. with ui.tab_panels(tabs, value='Home'):
  149. with ui.tab_panel('Home'):
  150. ui.label('This is the first tab')
  151. with ui.tab_panel('About'):
  152. ui.label('This is the second tab')
  153. load_demo(ui.menu)
  154. @text_demo('Tooltips', '''
  155. Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
  156. For more artistic control you can nest tooltip elements and apply props, classes and styles.
  157. ''')
  158. def tooltips_demo():
  159. ui.label('Tooltips...').tooltip('...are shown on mouse over')
  160. with ui.button().props('icon=thumb_up'):
  161. ui.tooltip('I like this').classes('bg-green')
  162. load_demo(ui.notify)
  163. load_demo(ui.dialog)
  164. @text_demo('Awaitable dialog', '''
  165. Dialogs can be awaited.
  166. Use the `submit` method to close the dialog and return a result.
  167. Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
  168. ''')
  169. def async_dialog_demo():
  170. with ui.dialog() as dialog, ui.card():
  171. ui.label('Are you sure?')
  172. with ui.row():
  173. ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
  174. ui.button('No', on_click=lambda: dialog.submit('No'))
  175. async def show():
  176. result = await dialog
  177. ui.notify(f'You chose {result}')
  178. ui.button('Await a dialog', on_click=show)
  179. heading('Appearance')
  180. @text_demo('Styling', '''
  181. NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
  182. 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):
  183. Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
  184. You can also apply [Tailwind CSS](https://tailwindcss.com/) utility classes with the `classes` method.
  185. If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
  186. All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
  187. ''')
  188. def design_demo():
  189. ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
  190. ui.button().props('icon=touch_app outline round').classes('shadow-lg')
  191. ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
  192. @text_demo('Tailwind CSS', '''
  193. [Tailwind CSS](https://tailwindcss.com/) is a CSS framework for rapidly building custom user interfaces.
  194. NiceGUI provides a fluent, auto-complete friendly interface for adding Tailwind classes to UI elements.
  195. You can discover available classes by navigating the methods of the `tailwind` property.
  196. The builder pattern allows you to chain multiple classes together (as shown with "Label A").
  197. You can also call the `tailwind` property with a list of classes (as shown with "Label B").
  198. Although this is very similar to using the `classes` method, it is more convenient for Tailwind classes due to auto-completion.
  199. Last but not least, you can also predefine a style and apply it to multiple elements (labels C and D).
  200. ''')
  201. def tailwind_demo():
  202. from nicegui import Tailwind
  203. ui.label('Label A').tailwind.font_weight('extrabold').text_color('blue-600').background_color('orange-200')
  204. ui.label('Label B').tailwind('drop-shadow', 'font-bold', 'text-green-600')
  205. red_style = Tailwind().text_color('red-600').font_weight('bold')
  206. label_c = ui.label('Label C')
  207. red_style.apply(label_c)
  208. ui.label('Label D').tailwind(red_style)
  209. load_demo(ui.query)
  210. load_demo(ui.colors)
  211. heading('Action')
  212. load_demo(ui.timer)
  213. load_demo(ui.keyboard)
  214. @text_demo('Bindings', '''
  215. NiceGUI is able to directly bind UI elements to models.
  216. Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
  217. Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
  218. To define a one-way binding use the `_from` and `_to` variants of these methods.
  219. Just pass a property of the model as parameter to these methods to create the binding.
  220. ''')
  221. def bindings_demo():
  222. class Demo:
  223. def __init__(self):
  224. self.number = 1
  225. demo = Demo()
  226. v = ui.checkbox('visible', value=True)
  227. with ui.column().bind_visibility_from(v, 'value'):
  228. ui.slider(min=1, max=3).bind_value(demo, 'number')
  229. ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(demo, 'number')
  230. ui.number().bind_value(demo, 'number')
  231. @text_demo('UI Updates', '''
  232. 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.
  233. In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
  234. The demo code shows both methods for a `ui.chart`, where it is difficult to automatically detect changes in the `options` dictionary.
  235. ''')
  236. def ui_updates_demo():
  237. from random import randint
  238. chart = ui.chart({'title': False, 'series': [{'data': [1, 2]}]}).classes('w-full h-64')
  239. def add():
  240. chart.options['series'][0]['data'].append(randint(0, 100))
  241. chart.update()
  242. def clear():
  243. chart.options['series'][0]['data'].clear()
  244. ui.update(chart)
  245. with ui.row():
  246. ui.button('Add', on_click=add)
  247. ui.button('Clear', on_click=clear)
  248. @text_demo('Async event handlers', '''
  249. Most elements also support asynchronous event handlers.
  250. Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
  251. ''')
  252. def async_handlers_demo():
  253. import asyncio
  254. async def async_task():
  255. ui.notify('Asynchronous task started')
  256. await asyncio.sleep(5)
  257. ui.notify('Asynchronous task finished')
  258. ui.button('start async task', on_click=async_task)
  259. heading('Pages')
  260. load_demo(ui.page)
  261. @text_demo('Auto-index page', '''
  262. Pages created with the `@ui.page` decorator are "private".
  263. Their content is re-created for each client.
  264. Thus, in the demo to the right, the displayed ID on the private page changes when the browser reloads the page.
  265. UI elements that are not wrapped in a decorated page function are placed on an automatically generated index page at route "/".
  266. This auto-index page is created once on startup and *shared* across all clients that might connect.
  267. Thus, each connected client will see the *same* elements.
  268. In the demo to the right, the displayed ID on the auto-index page remains constant when the browser reloads the page.
  269. ''')
  270. def auto_index_page():
  271. from uuid import uuid4
  272. @ui.page('/private_page')
  273. async def private_page():
  274. ui.label(f'private page with ID {uuid4()}')
  275. # ui.label(f'shared auto-index page with ID {uuid4()}')
  276. # ui.link('private page', private_page)
  277. # END OF DEMO
  278. ui.label(f'shared auto-index page with ID {CONSTANT_UUID}')
  279. ui.link('private page', private_page)
  280. @text_demo('Pages with Path Parameters', '''
  281. Page routes can contain parameters like [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/>).
  282. If type-annotated, they are automatically converted to bool, int, float and complex values.
  283. If the page function expects a `request` argument, the request object is automatically provided.
  284. The `client` argument provides access to the websocket connection, layout, etc.
  285. ''')
  286. def page_with_path_parameters_demo():
  287. @ui.page('/repeat/{word}/{count}')
  288. def page(word: str, count: int):
  289. ui.label(word * count)
  290. ui.link('Say hi to Santa!', 'repeat/Ho! /3')
  291. @text_demo('Wait for Client Connection', '''
  292. To wait for a client connection, you can add a `client` argument to the decorated page function
  293. and await `client.connected()`.
  294. All code below that statement is executed after the websocket connection between server and client has been established.
  295. 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)).
  296. Also it is possible to do async stuff while the user already sees some content.
  297. ''')
  298. def wait_for_connected_demo():
  299. import asyncio
  300. from nicegui import Client
  301. @ui.page('/wait_for_connection')
  302. async def wait_for_connection(client: Client):
  303. ui.label('This text is displayed immediately.')
  304. await client.connected()
  305. await asyncio.sleep(2)
  306. ui.label('This text is displayed 2 seconds after the page has been fully loaded.')
  307. ui.label(f'The IP address {client.ip} was obtained from the websocket.')
  308. ui.link('wait for connection', wait_for_connection)
  309. @text_demo('Page Layout', '''
  310. With `ui.header`, `ui.footer`, `ui.left_drawer` and `ui.right_drawer` you can add additional layout elements to a page.
  311. The `fixed` argument controls whether the element should scroll or stay fixed on the screen.
  312. The `top_corner` and `bottom_corner` arguments indicate whether a drawer should expand to the top or bottom of the page.
  313. See <https://quasar.dev/layout/header-and-footer> and <https://quasar.dev/layout/drawer> for more information about possible props.
  314. With `ui.page_sticky` you can place an element "sticky" on the screen.
  315. See <https://quasar.dev/layout/page-sticky> for more information.
  316. ''')
  317. def page_layout_demo():
  318. @ui.page('/page_layout')
  319. async def page_layout():
  320. ui.label('CONTENT')
  321. [ui.label(f'Line {i}') for i in range(100)]
  322. with ui.header(elevated=True).style('background-color: #3874c8').classes('items-center justify-between'):
  323. ui.label('HEADER')
  324. ui.button(on_click=lambda: right_drawer.toggle()).props('flat color=white icon=menu')
  325. with ui.left_drawer(top_corner=True, bottom_corner=True).style('background-color: #d7e3f4'):
  326. ui.label('LEFT DRAWER')
  327. with ui.right_drawer(fixed=False).style('background-color: #ebf1fa').props('bordered') as right_drawer:
  328. ui.label('RIGHT DRAWER')
  329. with ui.footer().style('background-color: #3874c8'):
  330. ui.label('FOOTER')
  331. ui.link('show page with fancy layout', page_layout)
  332. load_demo(ui.open)
  333. load_demo(ui.download)
  334. @text_demo('Sessions', '''
  335. The optional `request` argument provides insights about the client's URL parameters etc.
  336. It also enables you to identify sessions using a [session middleware](https://www.starlette.io/middleware/#sessionmiddleware).
  337. ''')
  338. def sessions_demo():
  339. import uuid
  340. from collections import Counter
  341. from datetime import datetime
  342. from starlette.middleware.sessions import SessionMiddleware
  343. from starlette.requests import Request
  344. from nicegui import app
  345. # app.add_middleware(SessionMiddleware, secret_key='some_random_string')
  346. counter = Counter()
  347. start = datetime.now().strftime('%H:%M, %d %B %Y')
  348. @ui.page('/session_demo')
  349. def session_demo(request: Request):
  350. if 'id' not in request.session:
  351. request.session['id'] = str(uuid.uuid4())
  352. counter[request.session['id']] += 1
  353. ui.label(f'{len(counter)} unique views ({sum(counter.values())} overall) since {start}')
  354. ui.link('Visit session demo', session_demo)
  355. load_demo(ui.run_javascript)
  356. heading('Routes')
  357. @element_demo(app.add_static_files)
  358. def add_static_files_demo():
  359. from nicegui import app
  360. app.add_static_files('/examples', 'examples')
  361. ui.label('Some NiceGUI Examples').classes('text-h5')
  362. ui.link('AI interface', '/examples/ai_interface/main.py')
  363. ui.link('Custom FastAPI app', '/examples/fastapi/main.py')
  364. ui.link('Authentication', '/examples/authentication/main.py')
  365. @text_demo('API Responses', '''
  366. NiceGUI is based on [FastAPI](https://fastapi.tiangolo.com/).
  367. This means you can use all of FastAPI's features.
  368. For example, you can implement a RESTful API in addition to your graphical user interface.
  369. You simply import the `app` object from `nicegui`.
  370. 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()`.
  371. You can also return any other FastAPI response object inside a page function.
  372. For example, you can return a `RedirectResponse` to redirect the user to another page if certain conditions are met.
  373. This is used in our [authentication demo](https://github.com/zauberzeug/nicegui/tree/main/examples/authentication/main.py).
  374. ''')
  375. def fastapi_demo():
  376. import random
  377. from nicegui import app
  378. @app.get('/random/{max}')
  379. def generate_random_number(max: int):
  380. return {'min': 0, 'max': max, 'value': random.randint(0, max)}
  381. max = ui.number('max', value=100)
  382. ui.button('generate random number', on_click=lambda: ui.open(f'/random/{max.value:.0f}'))
  383. heading('Lifecycle')
  384. @text_demo('Events', '''
  385. You can register coroutines or functions to be called for the following events:
  386. - `app.on_startup`: called when NiceGUI is started or restarted
  387. - `app.on_shutdown`: called when NiceGUI is shut down or restarted
  388. - `app.on_connect`: called for each client which connects (optional argument: nicegui.Client)
  389. - `app.on_disconnect`: called for each client which disconnects (optional argument: nicegui.Client)
  390. - `app.on_exception`: called when an exception occurs (optional argument: exception)
  391. When NiceGUI is shut down or restarted, all tasks still in execution will be automatically canceled.
  392. ''')
  393. def lifecycle_demo():
  394. from datetime import datetime
  395. from nicegui import app
  396. # dt = datetime.now()
  397. def handle_connection():
  398. global dt
  399. dt = datetime.now()
  400. app.on_connect(handle_connection)
  401. label = ui.label()
  402. ui.timer(1, lambda: label.set_text(f'Last new connection: {dt:%H:%M:%S}'))
  403. # END OF DEMO
  404. global dt
  405. dt = datetime.now()
  406. @element_demo(app.shutdown)
  407. def shutdown_demo():
  408. from nicegui import app
  409. # ui.button('shutdown', on_click=app.shutdown)
  410. #
  411. # ui.run(reload=False)
  412. # END OF DEMO
  413. ui.button('shutdown', on_click=lambda: ui.notify(
  414. 'Nah. We do not actually shutdown the documentation server. Try it in your own app!'))
  415. heading('NiceGUI Fundamentals')
  416. @text_demo('Auto-context', '''
  417. In order to allow writing intuitive UI descriptions, NiceGUI automatically tracks the context in which elements are created.
  418. This means that there is no explicit `parent` parameter.
  419. Instead the parent context is defined using a `with` statement.
  420. It is also passed to event handlers and timers.
  421. In the demo, the label "Card content" is added to the card.
  422. And because the `ui.button` is also added to the card, the label "Click!" will also be created in this context.
  423. The label "Tick!", which is added once after one second, is also added to the card.
  424. This design decision allows for easily creating modular components that keep working after moving them around in the UI.
  425. For example, you can move label and button somewhere else, maybe wrap them in another container, and the code will still work.
  426. ''')
  427. def auto_context_demo():
  428. with ui.card():
  429. ui.label('Card content')
  430. ui.button('Add label', on_click=lambda: ui.label('Click!'))
  431. ui.timer(1.0, lambda: ui.label('Tick!'), once=True)
  432. @text_demo('Generic Events', '''
  433. Most UI elements come with predefined events.
  434. For example, a `ui.button` like "A" in the demo has an `on_click` parameter that expects a coroutine or function.
  435. But you can also use the `on` method to register a generic event handler like for "B".
  436. This allows you to register handlers for any event that is supported by JavaScript and Quasar.
  437. 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`.
  438. Some events, like `mousemove`, are fired very often.
  439. To avoid performance issues, you can use the `throttle` parameter to only call the handler every `throttle` seconds ("D").
  440. The generic event handler can be synchronous or asynchronous and optionally takes an event dictionary as argument ("E").
  441. You can also specify which attributes of the JavaScript or Quasar event should be passed to the handler ("F").
  442. This can reduce the amount of data that needs to be transferred between the server and the client.
  443. You can also include [key modifiers](https://vuejs.org/guide/essentials/event-handling.html#key-modifiers) ("G"),
  444. modifier combinations ("H"),
  445. and [event modifiers](https://vuejs.org/guide/essentials/event-handling.html#mouse-button-modifiers) ("I").
  446. ''')
  447. def generic_events_demo():
  448. with ui.row():
  449. ui.button('A', on_click=lambda: ui.notify('You clicked the button A.'))
  450. ui.button('B').on('click', lambda: ui.notify('You clicked the button B.'))
  451. with ui.row():
  452. ui.button('C').on('mousemove', lambda: ui.notify('You moved on button C.'))
  453. ui.button('D').on('mousemove', lambda: ui.notify('You moved on button D.'), throttle=0.5)
  454. with ui.row():
  455. ui.button('E').on('mousedown', lambda e: ui.notify(str(e)))
  456. ui.button('F').on('mousedown', lambda e: ui.notify(str(e)), ['ctrlKey', 'shiftKey'])
  457. with ui.row():
  458. ui.input('G').classes('w-12').on('keydown.space', lambda: ui.notify('You pressed space.'))
  459. ui.input('H').classes('w-12').on('keydown.y.shift', lambda: ui.notify('You pressed Shift+Y'))
  460. ui.input('I').classes('w-12').on('keydown.once', lambda: ui.notify('You started typing.'))
  461. heading('Configuration')
  462. @element_demo(ui.run, browser_title='My App')
  463. def ui_run_demo():
  464. ui.label('page with custom title')
  465. # ui.run(title='My App')
  466. # HACK: switch color to white for the next demo
  467. demo_BROWSER_BGCOLOR = demo.BROWSER_BGCOLOR
  468. demo.BROWSER_BGCOLOR = '#ffffff'
  469. @text_demo('Native Mode', '''
  470. You can enable native mode for NiceGUI by specifying `native=True` in the `ui.run` function.
  471. To customize the initial window size and display mode, use the `window_size` and `fullscreen` parameters respectively.
  472. Additionally, you can provide extra keyword arguments via `app.native.window_args` and `app.native.start_args`.
  473. Pick any parameter as it is defined by the internally used [pywebview module](https://pywebview.flowrl.com/guide/api.html)
  474. for the `webview.create_window` and `webview.start` functions.
  475. Note that these keyword arguments will take precedence over the parameters defined in ui.run.
  476. ''')
  477. def native_mode_demo():
  478. from nicegui import app
  479. ui.label('app running in native mode')
  480. app.native.window_args['resizable'] = False
  481. app.native.start_args['debug'] = True
  482. # ui.run(native=True, window_size=(400, 300), fullscreen=False)
  483. # HACK: restore color
  484. demo.BROWSER_BGCOLOR = demo_BROWSER_BGCOLOR
  485. # Show a helpful workaround until issue is fixed upstream.
  486. # For more info see: https://github.com/r0x0r/pywebview/issues/1078
  487. ui.markdown('''
  488. If webview has trouble finding required libraries, you may get an error relating to "WebView2Loader.dll".
  489. To work around this issue, try moving the DLL file up a directory, e.g.:
  490. * from `.venv/Lib/site-packages/webview/lib/x64/WebView2Loader.dll`
  491. * to `.venv/Lib/site-packages/webview/lib/WebView2Loader.dll`
  492. ''')
  493. @text_demo('Environment Variables', '''
  494. You can set the following environment variables to configure NiceGUI:
  495. - `MATPLOTLIB` (default: true) can be set to `false` to avoid the potentially costly import of Matplotlib.
  496. This will make `ui.pyplot` and `ui.line_plot` unavailable.
  497. - `MARKDOWN_CONTENT_CACHE_SIZE` (default: 1000): The maximum number of Markdown content snippets that are cached in memory.
  498. ''')
  499. def env_var_demo():
  500. from nicegui.elements import markdown
  501. ui.label(f'Markdown content cache size is {markdown.prepare_content.cache_info().maxsize}')
  502. heading('Deployment')
  503. subheading('Server Hosting')
  504. ui.markdown('''
  505. 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.
  506. 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.
  507. 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.
  508. 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.
  509. With this command you can launch the script `main.py` in the current directory on the public port 80:
  510. ''').classes('bold-links arrow-links')
  511. with demo.bash_window(classes='max-w-lg w-full h-52'):
  512. ui.markdown('''
  513. ```bash
  514. docker run -p 80:8080 -v $(pwd)/:/app/ \\
  515. -d --restart always zauberzeug/nicegui:latest
  516. ```
  517. ''')
  518. ui.markdown('''
  519. The demo assumes `main.py` uses the port 8080 in the `ui.run` command (which is the default).
  520. 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.
  521. Of course this can also be written in a Docker compose file:
  522. ''')
  523. with demo.python_window('docker-compose.yml', classes='max-w-lg w-full h-52'):
  524. ui.markdown('''
  525. ```yaml
  526. app:
  527. image: zauberzeug/nicegui:latest
  528. restart: always
  529. ports:
  530. - 80:8080
  531. volumes:
  532. - ./:/app/
  533. ```
  534. ''')
  535. ui.markdown('''
  536. You can provide SSL certificates directly using [FastAPI](https://fastapi.tiangolo.com/deployment/https/).
  537. 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.
  538. See our [docker-compose.yml](https://github.com/zauberzeug/nicegui/blob/main/docker-compose.yml) as an example.
  539. You may also have a look at [our demo for using a custom FastAPI app](https://github.com/zauberzeug/nicegui/tree/main/examples/fastapi).
  540. This will allow you to do very flexible deployments as described in the [FastAPI documentation](https://fastapi.tiangolo.com/deployment/).
  541. Note that there are additional steps required to allow multiple workers.
  542. ''').classes('bold-links arrow-links')
  543. subheading('Package for Installation')
  544. ui.markdown('''
  545. NiceGUI apps can also be bundled into an executable with [PyInstaller](https://www.pyinstaller.org/).
  546. This allows you to distribute your app as a single file that can be executed on any computer.
  547. Just take care your `ui.run` command does not use the `reload` argument.
  548. Running the `build.py` below will create an executable `myapp` in the `dist` folder:
  549. ''').classes('bold-links arrow-links')
  550. with ui.row().classes('w-full items-stretch'):
  551. with demo.python_window(classes='max-w-lg w-full'):
  552. ui.markdown('''
  553. ```python
  554. from nicegui import ui
  555. ui.label('Hello from PyInstaller')
  556. ui.run(reload=False)
  557. ```
  558. ''')
  559. with demo.python_window('build.py', classes='max-w-lg w-full'):
  560. ui.markdown('''
  561. ```python
  562. import os
  563. import subprocess
  564. from pathlib import Path
  565. import nicegui
  566. cmd = [
  567. 'python',
  568. '-m', 'PyInstaller',
  569. 'main.py', # your main file with ui.run()
  570. '--name', 'myapp', # name of your app
  571. '--onefile',
  572. #'--windowed', # prevent console appearing, only use with ui.run(native=True, ...)
  573. '--add-data', f'{Path(nicegui.__file__).parent}{os.pathsep}nicegui'
  574. ]
  575. subprocess.call(cmd)
  576. ```
  577. ''')
  578. ui.markdown('''
  579. **Packaging Tips**
  580. - When building a PyInstaller app, your main script can use a native window (rather than a browser window) by
  581. using `ui.run(reload=False, native=True)`.
  582. The `native` parameter can be `True` or `False` depending on whether you want a native window or to launch a
  583. page in the user's browser - either will work in the PyInstaller generated app.
  584. - Specifying `--windowed` to PyInstaller will prevent a terminal console from appearing.
  585. However you should only use this option if you have also specified `native=True` in your `ui.run` command.
  586. Without a terminal console the user won't be able to exit the app by pressing Ctrl-C.
  587. With the `native=True` option, the app will automatically close when the window is closed, as expected.
  588. - Specifying `--windowed` to PyInstaller will create an `.app` file on Mac which may be more convenient to distribute.
  589. When you double-click the app to run it, it will not show any console output.
  590. You can also run the app from the command line with `./myapp.app/Contents/MacOS/myapp` to see the console output.
  591. - Specifying `--onefile` to PyInstaller will create a single executable file.
  592. Whilst convenient for distribution, it will be slower to start up.
  593. This is not NiceGUI's fault but just the way Pyinstaller zips things into a single file, then unzips everything
  594. into a temporary directory before running.
  595. You can mitigate this by removing `--onefile` from the PyInstaller command,
  596. and zip up the generated `dist` directory yourself, distribute it,
  597. and your end users can unzip once and be good to go,
  598. without the constant expansion of files due to the `--onefile` flag.
  599. - Summary of user experience for different options:
  600. | PyInstaller | `ui.run(...)` | Explanation |
  601. | :--- | :--- | :--- |
  602. | `onefile` | `native=False` | Single executable generated in `dist/`, runs in browser |
  603. | `onefile` | `native=True` | Single executable generated in `dist/`, runs in popup window |
  604. | `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 |
  605. | `onefile` and `windowed` | `native=False` | Avoid (no way to exit the app) |
  606. | Specify neither | | A `dist/myapp` directory created which can be zipped manually and distributed; run with `dist/myapp/myapp` |
  607. - If you are using a Python virtual environment, ensure you `pip install pyinstaller` within your virtual environment
  608. so that the correct PyInstaller is used, or you may get broken apps due to the wrong version of PyInstaller being picked up.
  609. That is why the build script invokes PyInstaller using `python -m PyInstaller` rather than just `pyinstaller`.
  610. ''').classes('bold-links arrow-links')
  611. with demo.bash_window(classes='max-w-lg w-full h-42 self-center'):
  612. ui.markdown('''
  613. ```bash
  614. python -m venv venv
  615. source venv/bin/activate
  616. pip install nicegui
  617. pip install pyinstaller
  618. ```
  619. ''')
  620. ui.markdown('''
  621. **Note:**
  622. 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:
  623. ```py
  624. import sys
  625. sys.stdout = open('logs.txt', 'w')
  626. ```
  627. See <https://github.com/zauberzeug/nicegui/issues/681> for more information.
  628. ''')
  629. ui.element('div').classes('h-32')