api_docs_and_examples.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. import inspect
  2. import re
  3. from contextlib import contextmanager
  4. from typing import Callable, Union
  5. import docutils.core
  6. from nicegui import ui
  7. REGEX_H4 = re.compile(r'<h4.*?>(.*?)</h4>')
  8. SPECIAL_CHARACTERS = re.compile('[^(a-z)(A-Z)(0-9)-]')
  9. @contextmanager
  10. def example(content: Union[Callable, type, str]):
  11. callFrame = inspect.currentframe().f_back.f_back
  12. begin = callFrame.f_lineno
  13. def add_html_anchor(element: ui.html):
  14. html = element.content
  15. match = REGEX_H4.search(html)
  16. if not match:
  17. return
  18. headline = match.groups()[0].strip()
  19. headline_id = SPECIAL_CHARACTERS.sub('_', headline).lower()
  20. if not headline_id:
  21. return
  22. icon = '<span class="material-icons">link</span>'
  23. anchor = f'<a href="reference#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
  24. html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
  25. html = html.replace('</h4>', f' {anchor}</h4>', 1)
  26. element.view.inner_html = html
  27. with ui.row().classes('flex w-full'):
  28. if isinstance(content, str):
  29. add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
  30. else:
  31. doc = content.__doc__ or content.__init__.__doc__
  32. html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
  33. html = html.replace('<p>', '<h4>', 1)
  34. html = html.replace('</p>', '</h4>', 1)
  35. html = ui.markdown.apply_tailwind(html)
  36. add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
  37. try:
  38. with ui.card().classes('mt-12 w-2/12'):
  39. with ui.column().classes('flex w-full'):
  40. yield
  41. finally:
  42. code: str = open(__file__).read()
  43. end = begin + 1
  44. lines = code.splitlines()
  45. while True:
  46. end += 1
  47. if end >= len(lines):
  48. break
  49. if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
  50. break
  51. code = lines[begin:end]
  52. code = [l[8:] for l in code]
  53. code.insert(0, '```python')
  54. code.insert(1, 'from nicegui import ui')
  55. if code[2].split()[0] not in ['from', 'import']:
  56. code.insert(2, '')
  57. if code[-1].startswith('#ui.run'):
  58. code[-1] = code[-1][1:]
  59. else:
  60. code.append('ui.run()')
  61. code.append('```')
  62. code = '\n'.join(code)
  63. ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
  64. def create():
  65. ui.markdown('## API Documentation and Examples')
  66. def h3(text: str) -> None:
  67. ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
  68. h3('Basic Elements')
  69. with example(ui.label):
  70. ui.label('some label')
  71. with example(ui.icon):
  72. ui.icon('thumb_up')
  73. with example(ui.link):
  74. ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
  75. with example(ui.button):
  76. ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
  77. with example(ui.toggle):
  78. toggle1 = ui.toggle([1, 2, 3], value=1)
  79. toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
  80. with example(ui.radio):
  81. radio1 = ui.radio([1, 2, 3], value=1).props('inline')
  82. radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
  83. with example(ui.select):
  84. select1 = ui.select([1, 2, 3], value=1)
  85. select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
  86. with example(ui.checkbox):
  87. checkbox = ui.checkbox('check me')
  88. ui.label('Check!').bind_visibility_from(checkbox, 'value')
  89. with example(ui.switch):
  90. switch = ui.switch('switch me')
  91. ui.label('Switch!').bind_visibility_from(switch, 'value')
  92. with example(ui.slider):
  93. slider = ui.slider(min=0, max=100, value=50).props('label')
  94. ui.label().bind_text_from(slider, 'value')
  95. with example(ui.joystick):
  96. ui.joystick(color='blue', size=50,
  97. on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
  98. on_end=lambda msg: coordinates.set_text('0, 0'))
  99. coordinates = ui.label('0, 0')
  100. with example(ui.input):
  101. ui.input(label='Text', placeholder='press ENTER to apply',
  102. on_change=lambda e: input_result.set_text('you typed: ' + e.value))
  103. input_result = ui.label()
  104. with example(ui.number):
  105. ui.number(label='Number', value=3.1415927, format='%.2f',
  106. on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
  107. number_result = ui.label()
  108. with example(ui.color_input):
  109. color_label = ui.label('Change my color!')
  110. ui.color_input(label='Color', value='#000000',
  111. on_change=lambda e: color_label.style(f'color:{e.value}'))
  112. with example(ui.color_picker):
  113. picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
  114. button = ui.button(on_click=picker.open).props('icon=colorize')
  115. with example(ui.upload):
  116. ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
  117. h3('Markdown and HTML')
  118. with example(ui.markdown):
  119. ui.markdown('''This is **Markdown**.''')
  120. with example(ui.html):
  121. ui.html('This is <strong>HTML</strong>.')
  122. svg = '''#### SVG
  123. You can add Scalable Vector Graphics using the `ui.html` element.
  124. '''
  125. with example(svg):
  126. content = '''
  127. <svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  128. <circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
  129. <circle cx="80" cy="85" r="8" />
  130. <circle cx="120" cy="85" r="8" />
  131. <path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
  132. </svg>'''
  133. ui.html(content)
  134. h3('Images')
  135. with example(ui.image):
  136. ui.image('http://placeimg.com/640/360/tech')
  137. captions_and_overlays = '''#### Captions and Overlays
  138. By nesting elements inside a `ui.image` you can create augmentations.
  139. Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
  140. To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
  141. '''
  142. with example(captions_and_overlays):
  143. with ui.image('http://placeimg.com/640/360/nature'):
  144. ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
  145. with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
  146. content = '''
  147. <svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
  148. <circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
  149. </svg>'''
  150. ui.html(content).style('background:transparent')
  151. with example(ui.interactive_image):
  152. from nicegui.events import MouseEventArguments
  153. def mouse_handler(e: MouseEventArguments):
  154. color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
  155. ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
  156. ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
  157. src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
  158. ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
  159. h3('Data Elements')
  160. with example(ui.table):
  161. table = ui.table({
  162. 'columnDefs': [
  163. {'headerName': 'Name', 'field': 'name'},
  164. {'headerName': 'Age', 'field': 'age'},
  165. ],
  166. 'rowData': [
  167. {'name': 'Alice', 'age': 18},
  168. {'name': 'Bob', 'age': 21},
  169. {'name': 'Carol', 'age': 42},
  170. ],
  171. }).classes('max-h-40')
  172. def update():
  173. table.options.rowData[0].age += 1
  174. table.update()
  175. ui.button('Update', on_click=update)
  176. with example(ui.chart):
  177. from numpy.random import random
  178. chart = ui.chart({
  179. 'title': False,
  180. 'chart': {'type': 'bar'},
  181. 'xAxis': {'categories': ['A', 'B']},
  182. 'series': [
  183. {'name': 'Alpha', 'data': [0.1, 0.2]},
  184. {'name': 'Beta', 'data': [0.3, 0.4]},
  185. ],
  186. }).classes('max-w-full h-64')
  187. def update():
  188. chart.options.series[0].data[:] = random(2)
  189. chart.update()
  190. ui.button('Update', on_click=update)
  191. with example(ui.plot):
  192. import numpy as np
  193. from matplotlib import pyplot as plt
  194. with ui.plot(figsize=(2.5, 1.8)):
  195. x = np.linspace(0.0, 5.0)
  196. y = np.cos(2 * np.pi * x) * np.exp(-x)
  197. plt.plot(x, y, '-')
  198. plt.xlabel('time (s)')
  199. plt.ylabel('Damped oscillation')
  200. with example(ui.line_plot):
  201. from datetime import datetime
  202. import numpy as np
  203. line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
  204. .with_legend(['sin', 'cos'], loc='upper center', ncol=2)
  205. def update_line_plot() -> None:
  206. now = datetime.now()
  207. x = now.timestamp()
  208. y1 = np.sin(x)
  209. y2 = np.cos(x)
  210. line_plot.push([now], [[y1], [y2]])
  211. line_updates = ui.timer(0.1, update_line_plot, active=False)
  212. ui.checkbox('active').bind_value(line_updates, 'active')
  213. with example(ui.scene):
  214. with ui.scene(width=200, height=200) as scene:
  215. scene.sphere().material('#4488ff')
  216. scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
  217. scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
  218. with scene.group().move(z=2):
  219. box1 = scene.box().move(x=2)
  220. scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
  221. scene.box(wireframe=True).material('#888888').move(x=2, y=2)
  222. scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
  223. scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
  224. logo = "https://avatars.githubusercontent.com/u/2843826"
  225. scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
  226. [[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
  227. teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
  228. scene.stl(teapot).scale(0.2).move(-3, 4)
  229. scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
  230. scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
  231. with example(ui.tree):
  232. ui.tree([
  233. {'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
  234. {'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
  235. ], label_key='id', on_select=lambda e: ui.notify(e.value))
  236. with example(ui.log):
  237. from datetime import datetime
  238. log = ui.log(max_lines=10).classes('h-16')
  239. ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
  240. h3('Layout')
  241. with example(ui.card):
  242. with ui.card().tight():
  243. ui.image('http://placeimg.com/640/360/nature')
  244. with ui.card_section():
  245. ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
  246. with example(ui.column):
  247. with ui.column():
  248. ui.label('label 1')
  249. ui.label('label 2')
  250. ui.label('label 3')
  251. with example(ui.row):
  252. with ui.row():
  253. ui.label('label 1')
  254. ui.label('label 2')
  255. ui.label('label 3')
  256. clear_containers = '''#### Clear Containers
  257. To remove all elements from a row, column or card container, use the `clear()` method.
  258. '''
  259. with example(clear_containers):
  260. container = ui.row()
  261. def add_face():
  262. with container:
  263. ui.icon('face')
  264. add_face()
  265. ui.button('Add', on_click=add_face)
  266. ui.button('Clear', on_click=container.clear)
  267. with example(ui.expansion):
  268. with ui.expansion('Expand!', icon='work').classes('w-full'):
  269. ui.label('inside the expansion')
  270. with example(ui.menu):
  271. choice = ui.label('Try the menu.')
  272. with ui.menu() as menu:
  273. ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
  274. ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
  275. ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
  276. ui.menu_separator()
  277. ui.menu_item('Close', on_click=menu.close)
  278. ui.button('Open menu', on_click=menu.open)
  279. tooltips = '''#### Tooltips
  280. Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
  281. '''
  282. with example(tooltips):
  283. ui.label('Tooltips...').tooltip('...are shown on mouse over')
  284. ui.button().props('icon=thumb_up').tooltip('I like this')
  285. with example(ui.notify):
  286. ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
  287. with example(ui.dialog):
  288. with ui.dialog() as dialog, ui.card():
  289. ui.label('Hello world!')
  290. ui.button('Close', on_click=dialog.close)
  291. ui.button('Open a dialog', on_click=dialog.open)
  292. async_dialog = '''#### Awaitable dialog
  293. Dialogs can be awaited.
  294. Use the `submit` method to close the dialog and return a result.
  295. Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
  296. '''
  297. with example(async_dialog):
  298. with ui.dialog() as dialog, ui.card():
  299. ui.label('Are you sure?')
  300. with ui.row():
  301. ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
  302. ui.button('No', on_click=lambda: dialog.submit('No'))
  303. async def show():
  304. result = await dialog
  305. ui.notify(f'You chose {result}')
  306. ui.button('Await a dialog', on_click=show)
  307. h3('Appearance')
  308. design = '''#### Styling
  309. NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
  310. 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):
  311. Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
  312. You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
  313. If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
  314. All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
  315. '''
  316. with example(design):
  317. ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
  318. ui.button().props('icon=touch_app outline round').classes('shadow-lg')
  319. ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
  320. with example(ui.colors):
  321. ui.colors()
  322. ui.button('Default', on_click=lambda: ui.colors())
  323. ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
  324. h3('Action')
  325. lifecycle = '''#### Lifecycle
  326. You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
  327. - `ui.on_startup`: Called when NiceGUI is started or restarted.
  328. - `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
  329. - `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
  330. - `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
  331. - `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
  332. When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
  333. '''
  334. with example(lifecycle):
  335. import asyncio
  336. import time
  337. l = ui.label()
  338. async def run_clock():
  339. while True:
  340. l.text = f'unix time: {time.time():.1f}'
  341. await asyncio.sleep(1)
  342. ui.on_startup(run_clock)
  343. ui.on_connect(lambda: l.set_text('new connection'))
  344. with example(ui.timer):
  345. from datetime import datetime
  346. with ui.row().classes('items-center'):
  347. clock = ui.label()
  348. t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
  349. ui.checkbox('active').bind_value(t, 'active')
  350. with ui.row():
  351. def lazy_update() -> None:
  352. new_text = datetime.now().strftime('%X.%f')[:-5]
  353. if lazy_clock.text[:8] == new_text[:8]:
  354. return
  355. lazy_clock.text = new_text
  356. lazy_clock = ui.label()
  357. ui.timer(interval=0.1, callback=lazy_update)
  358. with example(ui.keyboard):
  359. from nicegui.events import KeyEventArguments
  360. def handle_key(e: KeyEventArguments):
  361. if e.key == 'f' and not e.action.repeat:
  362. if e.action.keyup:
  363. ui.notify('f was just released')
  364. elif e.action.keydown:
  365. ui.notify('f was just pressed')
  366. if e.modifiers.shift and e.action.keydown:
  367. if e.key.arrow_left:
  368. ui.notify('going left')
  369. elif e.key.arrow_right:
  370. ui.notify('going right')
  371. elif e.key.arrow_up:
  372. ui.notify('going up')
  373. elif e.key.arrow_down:
  374. ui.notify('going down')
  375. keyboard = ui.keyboard(on_key=handle_key)
  376. ui.label('Key events can be caught globally by using the keyboard element.')
  377. ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
  378. bindings = '''#### Bindings
  379. NiceGUI is able to directly bind UI elements to models.
  380. Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
  381. Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
  382. To define a one-way binding use the `_from` and `_to` variants of these methods.
  383. Just pass a property of the model as parameter to these methods to create the binding.
  384. '''
  385. with example(bindings):
  386. class Demo:
  387. def __init__(self):
  388. self.number = 1
  389. demo = Demo()
  390. v = ui.checkbox('visible', value=True)
  391. with ui.column().bind_visibility_from(v, 'value'):
  392. ui.slider(min=1, max=3).bind_value(demo, 'number')
  393. ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
  394. ui.number().bind_value(demo, 'number')
  395. ui_updates = '''#### UI Updates
  396. 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.
  397. In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
  398. The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
  399. '''
  400. with example(ui_updates):
  401. from random import randint
  402. def add():
  403. numbers.options.rowData.append({'numbers': randint(0, 100)})
  404. numbers.update()
  405. def clear():
  406. numbers.options.rowData.clear()
  407. ui.update(numbers)
  408. numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
  409. ui.button('Add', on_click=add)
  410. ui.button('Clear', on_click=clear)
  411. async_handlers = '''#### Async event handlers
  412. Most elements also support asynchronous event handlers.
  413. Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
  414. '''
  415. with example(async_handlers):
  416. import asyncio
  417. async def async_task():
  418. ui.notify('Asynchronous task started')
  419. await asyncio.sleep(5)
  420. ui.notify('Asynchronous task finished')
  421. ui.button('start async task', on_click=async_task)
  422. h3('Pages')
  423. with example(ui.page):
  424. @ui.page('/other_page')
  425. def other_page():
  426. ui.label('Welcome to the other side')
  427. ui.link('Back to main page', '#page')
  428. @ui.page('/dark_page', dark=True)
  429. def dark_page():
  430. ui.label('Welcome to the dark side')
  431. ui.link('Back to main page', '#page')
  432. ui.link('Visit other page', other_page)
  433. ui.link('Visit dark page', dark_page)
  434. shared_and_private_pages = '''#### Shared and Private Pages
  435. By default, pages created with the `@ui.page` decorator are "private".
  436. Their content is re-created for each client.
  437. Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
  438. With `shared=True` you can create a shared page.
  439. Its content is created once at startup and each client sees the *same* elements.
  440. Here, the displayed ID remains constant when the browser reloads the page.
  441. #### Index page
  442. All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
  443. To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
  444. '''
  445. with example(shared_and_private_pages):
  446. from uuid import uuid4
  447. @ui.page('/private_page')
  448. async def private_page():
  449. ui.label(f'private page with ID {uuid4()}')
  450. @ui.page('/shared_page', shared=True)
  451. async def shared_page():
  452. ui.label(f'shared page with ID {uuid4()}')
  453. ui.link('private page', private_page)
  454. ui.link('shared page', shared_page)
  455. with example(ui.open):
  456. @ui.page('/yet_another_page')
  457. def yet_another_page():
  458. ui.label('Welcome to yet another page')
  459. ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
  460. ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
  461. sessions = '''#### Sessions
  462. `ui.page` provides an optional `on_connect` argument to register a callback.
  463. It is invoked for each new connection to the page.
  464. The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
  465. It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
  466. '''
  467. with example(sessions):
  468. from collections import Counter
  469. from datetime import datetime
  470. from starlette.requests import Request
  471. id_counter = Counter()
  472. creation = datetime.now().strftime('%H:%M, %d %B %Y')
  473. def handle_connection(request: Request):
  474. id_counter[request.session_id] += 1
  475. visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
  476. @ui.page('/session_demo', on_connect=handle_connection)
  477. def session_demo():
  478. global visits
  479. visits = ui.label()
  480. ui.link('Visit session demo', session_demo)
  481. javascript = '''#### JavaScript
  482. With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
  483. The asynchronous function will return after sending the command.
  484. With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
  485. The asynchronous function will only return after receiving the result.
  486. '''
  487. with example(javascript):
  488. async def run_javascript():
  489. await ui.run_javascript('alert("Hello!")')
  490. async def await_javascript():
  491. response = await ui.await_javascript('Date()')
  492. ui.notify(f'Browser time: {response}')
  493. ui.button('run JavaScript', on_click=run_javascript)
  494. ui.button('await JavaScript', on_click=await_javascript)
  495. h3('Routes')
  496. with example(ui.get):
  497. from starlette import requests, responses
  498. @ui.get('/another/route/{id}')
  499. def produce_plain_response(id: str, request: requests.Request):
  500. return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
  501. ui.link('Try yet another route!', 'another/route/42')
  502. with example(ui.add_static_files):
  503. ui.add_static_files('/examples', 'examples')
  504. ui.link('Slideshow Example (raw file)', 'examples/slideshow/main.py')
  505. with ui.image('examples/slideshow/slides/slide1.jpg'):
  506. ui.label('first image from slideshow').classes('absolute-bottom text-subtitle2')
  507. with example(ui.add_route):
  508. import starlette
  509. ui.add_route(starlette.routing.Route(
  510. '/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
  511. ))
  512. ui.link('Try the new route!', 'new/route')
  513. h3('Configuration')
  514. ui_run = '''#### ui.run
  515. You can call `ui.run()` with optional arguments:
  516. - `host` (default: `'0.0.0.0'`)
  517. - `port` (default: `8080`)
  518. - `title` (default: `'NiceGUI'`)
  519. - `favicon` (default: `'favicon.ico'`)
  520. - `dark`: whether to use Quasar's dark mode (default: `False`, use `None` for "auto" mode)
  521. - `main_page_classes`: configure Quasar classes of main page (default: `'q-ma-md column items-start'`)
  522. - `binding_refresh_interval`: time between binding updates (default: `0.1` seconds, bigger is more cpu friendly)
  523. - `show`: automatically open the ui in a browser tab (default: `True`)
  524. - `reload`: automatically reload the ui on file changes (default: `True`)
  525. - `uvicorn_logging_level`: logging level for uvicorn server (default: `'warning'`)
  526. - `uvicorn_reload_dirs`: string with comma-separated list for directories to be monitored (default is current working directory only)
  527. - `uvicorn_reload_includes`: string with comma-separated list of glob-patterns which trigger reload on modification (default: `'.py'`)
  528. - `uvicorn_reload_excludes`: string with comma-separated list of glob-patterns which should be ignored for reload (default: `'.*, .py[cod], .sw.*, ~*'`)
  529. - `exclude`: comma-separated string to exclude elements (with corresponding JavaScript libraries) to save bandwidth
  530. (possible entries: chart, colors, custom_example, interactive_image, keyboard, log, joystick, scene, table)
  531. The environment variables `HOST` and `PORT` can also be used to configure NiceGUI.
  532. To avoid the potentially costly import of Matplotlib, you set the environment variable `MATPLOTLIB=false`.
  533. This will make `ui.plot` and `ui.line_plot` unavailable.
  534. '''
  535. with example(ui_run):
  536. ui.label('dark page on port 7000 without reloading')
  537. #ui.run(dark=True, port=7000, reload=False)