api_docs_and_examples.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. import inspect
  2. import re
  3. from typing import Callable, Union
  4. import docutils.core
  5. from nicegui import ui
  6. from nicegui.auto_context import Context
  7. from nicegui.elements.markdown import apply_tailwind
  8. from nicegui.task_logger import create_task
  9. REGEX_H4 = re.compile(r'<h4.*?>(.*?)</h4>')
  10. SPECIAL_CHARACTERS = re.compile('[^(a-z)(A-Z)(0-9)-]')
  11. class example:
  12. def __init__(self, content: Union[Callable, type, str], tight: bool = False) -> None:
  13. self.content = content
  14. self.markdown_classes = f'mr-8 w-full flex-none lg:w-{48 if tight else 80} xl:w-80'
  15. self.rendering_classes = f'w-{48 if tight else 64} flex-none lg:mt-12'
  16. self.source_classes = f'w-80 flex-grow overflow-auto lg:mt-12'
  17. def __call__(self, f: Callable) -> Callable:
  18. with ui.row().classes('flex w-full'):
  19. if isinstance(self.content, str):
  20. self._add_html_anchor(ui.markdown(self.content).classes(self.markdown_classes))
  21. else:
  22. doc = self.content.__doc__ or self.content.__init__.__doc__
  23. html: str = docutils.core.publish_parts(doc, writer_name='html')['html_body']
  24. html = html.replace('<p>', '<h4>', 1)
  25. html = html.replace('</p>', '</h4>', 1)
  26. html = apply_tailwind(html)
  27. self._add_html_anchor(ui.html(html).classes(self.markdown_classes))
  28. with ui.card().classes(self.rendering_classes):
  29. f()
  30. code = inspect.getsource(f).splitlines()
  31. while not code[0].startswith(' ' * 8):
  32. del code[0]
  33. code = [l[8:] for l in code]
  34. while code[0].startswith('global '):
  35. del code[0]
  36. code.insert(0, '```python')
  37. code.insert(1, 'from nicegui import ui')
  38. if code[2].split()[0] not in ['from', 'import']:
  39. code.insert(2, '')
  40. for l, line in enumerate(code):
  41. if line.startswith('# ui.'):
  42. code[l] = line[2:]
  43. if line.startswith('# ui.run('):
  44. break
  45. else:
  46. code.append('')
  47. code.append('ui.run()')
  48. code.append('```')
  49. code = '\n'.join(code)
  50. ui.markdown(code).classes(self.source_classes)
  51. return f
  52. def _add_html_anchor(self, element: ui.html) -> None:
  53. html = element.content
  54. match = REGEX_H4.search(html)
  55. if not match:
  56. return
  57. headline = match.groups()[0].strip()
  58. headline_id = SPECIAL_CHARACTERS.sub('_', headline).lower()
  59. if not headline_id:
  60. return
  61. icon = '<span class="material-icons">link</span>'
  62. anchor = f'<a href="reference#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
  63. html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
  64. html = html.replace('</h4>', f' {anchor}</h4>', 1)
  65. element.view.inner_html = html
  66. def create_intro() -> None:
  67. # add docutils css to webpage
  68. ui.add_head_html(docutils.core.publish_parts('', writer_name='html')['stylesheet'])
  69. @example('''#### Hello, World!
  70. Creating a user interface with NiceGUI is as simple as writing a single line of code.
  71. ''', tight=True)
  72. def hello_world_example():
  73. ui.label('Hello, world!')
  74. ui.markdown('Have a look at the full <br/> [API reference](reference)!')
  75. @example('''#### Common UI Elements
  76. NiceGUI comes with a collection of commonly used UI elements.
  77. ''', tight=True)
  78. def common_elements_example():
  79. ui.button('Button', on_click=lambda: ui.notify('Click'))
  80. ui.checkbox('Checkbox', on_change=lambda e: ui.notify('Checked' if e.value else 'Unchecked'))
  81. ui.switch('Switch', on_change=lambda e: ui.notify('Switched' if e.value else 'Unswitched'))
  82. ui.input('Text input', on_change=lambda e: ui.notify(e.value))
  83. ui.radio(['A', 'B'], value='A', on_change=lambda e: ui.notify(e.value)).props('inline')
  84. ui.select(['One', 'Two'], value='One', on_change=lambda e: ui.notify(e.value))
  85. ui.link('And many more...', '/reference').classes('text-lg')
  86. @example('''#### Value Binding
  87. Binding values between UI elements or [to data models](http://127.0.0.1:8080/reference#bindings) is built into NiceGUI.
  88. ''', tight=True)
  89. def binding_example():
  90. slider = ui.slider(min=0, max=100, value=50)
  91. ui.number('Value').bind_value(slider, 'value').classes('fit')
  92. def create_full() -> None:
  93. # add docutils css to webpage
  94. ui.add_head_html(docutils.core.publish_parts('', writer_name='html')['stylesheet'])
  95. ui.markdown('## API Documentation and Examples')
  96. def h3(text: str) -> None:
  97. ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
  98. h3('Basic Elements')
  99. @example(ui.label)
  100. def label_example():
  101. ui.label('some label')
  102. @example(ui.icon)
  103. def icon_example():
  104. ui.icon('thumb_up')
  105. @example(ui.link)
  106. def link_example():
  107. ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
  108. @example(ui.button)
  109. def button_example():
  110. ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
  111. @example(ui.badge)
  112. def badge_example():
  113. with ui.button('Click me!', on_click=lambda: badge.set_text(int(badge.text) + 1)):
  114. badge = ui.badge('0', color='red').props('floating')
  115. @example(ui.toggle)
  116. def toggle_example():
  117. toggle1 = ui.toggle([1, 2, 3], value=1)
  118. toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
  119. @example(ui.radio)
  120. def radio_example():
  121. radio1 = ui.radio([1, 2, 3], value=1).props('inline')
  122. radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
  123. @example(ui.select)
  124. def select_example():
  125. select1 = ui.select([1, 2, 3], value=1)
  126. select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
  127. @example(ui.checkbox)
  128. def checkbox_example():
  129. checkbox = ui.checkbox('check me')
  130. ui.label('Check!').bind_visibility_from(checkbox, 'value')
  131. @example(ui.switch)
  132. def switch_example():
  133. switch = ui.switch('switch me')
  134. ui.label('Switch!').bind_visibility_from(switch, 'value')
  135. @example(ui.slider)
  136. def slider_example():
  137. slider = ui.slider(min=0, max=100, value=50).props('label')
  138. ui.label().bind_text_from(slider, 'value')
  139. @example(ui.joystick)
  140. def joystick_example():
  141. ui.joystick(color='blue', size=50,
  142. on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
  143. on_end=lambda msg: coordinates.set_text('0, 0'))
  144. coordinates = ui.label('0, 0')
  145. @example(ui.input)
  146. def input_example():
  147. ui.input(label='Text', placeholder='press ENTER to apply',
  148. on_change=lambda e: input_result.set_text('you typed: ' + e.value))
  149. input_result = ui.label()
  150. @example(ui.number)
  151. def number_example():
  152. ui.number(label='Number', value=3.1415927, format='%.2f',
  153. on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
  154. number_result = ui.label()
  155. @example(ui.color_input)
  156. def color_input_example():
  157. color_label = ui.label('Change my color!')
  158. ui.color_input(label='Color', value='#000000',
  159. on_change=lambda e: color_label.style(f'color:{e.value}'))
  160. @example(ui.color_picker)
  161. def color_picker_example():
  162. picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
  163. button = ui.button(on_click=picker.open).props('icon=colorize')
  164. @example(ui.upload)
  165. def upload_example():
  166. ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
  167. h3('Markdown and HTML')
  168. @example(ui.markdown)
  169. def markdown_example():
  170. ui.markdown('''This is **Markdown**.''')
  171. @example(ui.html)
  172. def html_example():
  173. ui.html('This is <strong>HTML</strong>.')
  174. @example('''#### SVG
  175. You can add Scalable Vector Graphics using the `ui.html` element.
  176. ''')
  177. def svg_example():
  178. content = '''
  179. <svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  180. <circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
  181. <circle cx="80" cy="85" r="8" />
  182. <circle cx="120" cy="85" r="8" />
  183. <path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
  184. </svg>'''
  185. ui.html(content)
  186. h3('Images')
  187. @example(ui.image)
  188. def image_example():
  189. ui.image('http://placeimg.com/640/360/tech')
  190. @example('''#### Captions and Overlays
  191. By nesting elements inside a `ui.image` you can create augmentations.
  192. Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
  193. To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
  194. ''')
  195. def captions_and_overlays_example():
  196. with ui.image('http://placeimg.com/640/360/nature'):
  197. ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
  198. with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
  199. content = '''
  200. <svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
  201. <circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
  202. </svg>'''
  203. ui.html(content).style('background:transparent')
  204. @example(ui.interactive_image)
  205. def interactive_image_example():
  206. from nicegui.events import MouseEventArguments
  207. def mouse_handler(e: MouseEventArguments):
  208. color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
  209. ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
  210. ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
  211. src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
  212. ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
  213. h3('Data Elements')
  214. @example(ui.table)
  215. def table_example():
  216. table = ui.table({
  217. 'columnDefs': [
  218. {'headerName': 'Name', 'field': 'name'},
  219. {'headerName': 'Age', 'field': 'age'},
  220. ],
  221. 'rowData': [
  222. {'name': 'Alice', 'age': 18},
  223. {'name': 'Bob', 'age': 21},
  224. {'name': 'Carol', 'age': 42},
  225. ],
  226. }).classes('max-h-40')
  227. def update():
  228. table.options.rowData[0].age += 1
  229. table.update()
  230. ui.button('Update', on_click=update)
  231. @example(ui.chart)
  232. def chart_example():
  233. from numpy.random import random
  234. chart = ui.chart({
  235. 'title': False,
  236. 'chart': {'type': 'bar'},
  237. 'xAxis': {'categories': ['A', 'B']},
  238. 'series': [
  239. {'name': 'Alpha', 'data': [0.1, 0.2]},
  240. {'name': 'Beta', 'data': [0.3, 0.4]},
  241. ],
  242. }).classes('w-full h-64')
  243. def update():
  244. chart.options.series[0].data[:] = random(2)
  245. chart.update()
  246. ui.button('Update', on_click=update)
  247. @example(ui.plot)
  248. def plot_example():
  249. import numpy as np
  250. from matplotlib import pyplot as plt
  251. with ui.plot(figsize=(2.5, 1.8)):
  252. x = np.linspace(0.0, 5.0)
  253. y = np.cos(2 * np.pi * x) * np.exp(-x)
  254. plt.plot(x, y, '-')
  255. plt.xlabel('time (s)')
  256. plt.ylabel('Damped oscillation')
  257. @example(ui.line_plot)
  258. def line_plot_example():
  259. global line_checkbox
  260. from datetime import datetime
  261. import numpy as np
  262. line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8), update_every=5) \
  263. .with_legend(['sin', 'cos'], loc='upper center', ncol=2)
  264. def update_line_plot() -> None:
  265. now = datetime.now()
  266. x = now.timestamp()
  267. y1 = np.sin(x)
  268. y2 = np.cos(x)
  269. line_plot.push([now], [[y1], [y2]])
  270. line_updates = ui.timer(0.1, update_line_plot, active=False)
  271. line_checkbox = ui.checkbox('active').bind_value(line_updates, 'active')
  272. @example(ui.linear_progress)
  273. def linear_progress_example():
  274. slider = ui.slider(min=0, max=1, step=0.01, value=0.5)
  275. ui.linear_progress().bind_value_from(slider, 'value')
  276. @example(ui.circular_progress)
  277. def circular_progress_example():
  278. slider = ui.slider(min=0, max=1, step=0.01, value=0.5)
  279. ui.circular_progress().bind_value_from(slider, 'value')
  280. @example(ui.scene)
  281. def scene_example():
  282. with ui.scene(width=225, height=225) as scene:
  283. scene.sphere().material('#4488ff')
  284. scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
  285. scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
  286. with scene.group().move(z=2):
  287. scene.box().move(x=2)
  288. scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
  289. scene.box(wireframe=True).material('#888888').move(x=2, y=2)
  290. scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
  291. scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
  292. logo = 'https://avatars.githubusercontent.com/u/2843826'
  293. scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
  294. [[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
  295. teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
  296. scene.stl(teapot).scale(0.2).move(-3, 4)
  297. scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
  298. scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
  299. @example(ui.tree)
  300. def tree_example():
  301. ui.tree([
  302. {'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
  303. {'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
  304. ], label_key='id', on_select=lambda e: ui.notify(e.value))
  305. @example(ui.log)
  306. def log_example():
  307. from datetime import datetime
  308. log = ui.log(max_lines=10).classes('w-full h-16')
  309. ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime('%X.%f')[:-5]))
  310. h3('Layout')
  311. @example(ui.card)
  312. def card_example():
  313. with ui.card().tight():
  314. ui.image('http://placeimg.com/640/360/nature')
  315. with ui.card_section():
  316. ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
  317. @example(ui.column)
  318. def column_example():
  319. with ui.column():
  320. ui.label('label 1')
  321. ui.label('label 2')
  322. ui.label('label 3')
  323. @example(ui.row)
  324. def row_example():
  325. with ui.row():
  326. ui.label('label 1')
  327. ui.label('label 2')
  328. ui.label('label 3')
  329. @example('''#### Clear Containers
  330. To remove all elements from a row, column or card container, use the `clear()` method.
  331. Alternatively, you can remove individual elements with `remove(element)`, where `element` is an Element or an index.
  332. ''')
  333. def clear_containers_example():
  334. container = ui.row()
  335. def add_face():
  336. with container:
  337. ui.icon('face')
  338. add_face()
  339. ui.button('Add', on_click=add_face)
  340. ui.button('Remove', on_click=lambda: container.remove(0))
  341. ui.button('Clear', on_click=container.clear)
  342. @example(ui.expansion)
  343. def expansion_example():
  344. with ui.expansion('Expand!', icon='work').classes('w-full'):
  345. ui.label('inside the expansion')
  346. @example(ui.menu)
  347. def menu_example():
  348. choice = ui.label('Try the menu.')
  349. with ui.menu() as menu:
  350. ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
  351. ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
  352. ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
  353. ui.menu_separator()
  354. ui.menu_item('Close', on_click=menu.close)
  355. ui.button('Open menu', on_click=menu.open)
  356. @example('''#### Tooltips
  357. Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
  358. ''')
  359. def tooltips_example():
  360. ui.label('Tooltips...').tooltip('...are shown on mouse over')
  361. ui.button().props('icon=thumb_up').tooltip('I like this')
  362. @example(ui.notify)
  363. def notify_example():
  364. ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
  365. @example(ui.dialog)
  366. def dialog_example():
  367. with ui.dialog() as dialog, ui.card():
  368. ui.label('Hello world!')
  369. ui.button('Close', on_click=dialog.close)
  370. ui.button('Open a dialog', on_click=dialog.open)
  371. @example('''#### Awaitable dialog
  372. Dialogs can be awaited.
  373. Use the `submit` method to close the dialog and return a result.
  374. Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
  375. ''')
  376. def async_dialog_example():
  377. with ui.dialog() as dialog, ui.card():
  378. ui.label('Are you sure?')
  379. with ui.row():
  380. ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
  381. ui.button('No', on_click=lambda: dialog.submit('No'))
  382. async def show():
  383. result = await dialog
  384. ui.notify(f'You chose {result}')
  385. ui.button('Await a dialog', on_click=show)
  386. h3('Appearance')
  387. @example('''#### Styling
  388. NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
  389. 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):
  390. Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
  391. You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
  392. If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
  393. All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
  394. ''')
  395. def design_example():
  396. ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
  397. ui.button().props('icon=touch_app outline round').classes('shadow-lg')
  398. ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
  399. @example(ui.colors)
  400. def colors_example():
  401. ui.colors()
  402. ui.button('Default', on_click=lambda: ui.colors())
  403. ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
  404. h3('Action')
  405. @example('''#### Lifecycle
  406. You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
  407. - `ui.on_startup`: Called when NiceGUI is started or restarted.
  408. - `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
  409. - `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
  410. - `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
  411. When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
  412. ''')
  413. def lifecycle_example():
  414. global countdown
  415. import asyncio
  416. l = ui.label()
  417. async def countdown():
  418. for i in [5, 4, 3, 2, 1, 0]:
  419. l.text = f'{i}...' if i else 'Take-off!'
  420. await asyncio.sleep(1)
  421. # ui.on_connect(countdown)
  422. @example(ui.timer)
  423. def timer_example():
  424. from datetime import datetime
  425. with ui.row().classes('items-center'):
  426. clock = ui.label()
  427. t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime('%X.%f')[:-5]))
  428. ui.checkbox('active').bind_value(t, 'active')
  429. with ui.row():
  430. def lazy_update() -> None:
  431. new_text = datetime.now().strftime('%X.%f')[:-5]
  432. if lazy_clock.text[:8] == new_text[:8]:
  433. return
  434. lazy_clock.text = new_text
  435. lazy_clock = ui.label()
  436. ui.timer(interval=0.1, callback=lazy_update)
  437. @example(ui.keyboard)
  438. def keyboard_example():
  439. from nicegui.events import KeyEventArguments
  440. def handle_key(e: KeyEventArguments):
  441. if e.key == 'f' and not e.action.repeat:
  442. if e.action.keyup:
  443. ui.notify('f was just released')
  444. elif e.action.keydown:
  445. ui.notify('f was just pressed')
  446. if e.modifiers.shift and e.action.keydown:
  447. if e.key.arrow_left:
  448. ui.notify('going left')
  449. elif e.key.arrow_right:
  450. ui.notify('going right')
  451. elif e.key.arrow_up:
  452. ui.notify('going up')
  453. elif e.key.arrow_down:
  454. ui.notify('going down')
  455. keyboard = ui.keyboard(on_key=handle_key)
  456. ui.label('Key events can be caught globally by using the keyboard element.')
  457. ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
  458. @example('''#### Bindings
  459. NiceGUI is able to directly bind UI elements to models.
  460. Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
  461. Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
  462. To define a one-way binding use the `_from` and `_to` variants of these methods.
  463. Just pass a property of the model as parameter to these methods to create the binding.
  464. ''')
  465. def bindings_example():
  466. class Demo:
  467. def __init__(self):
  468. self.number = 1
  469. demo = Demo()
  470. v = ui.checkbox('visible', value=True)
  471. with ui.column().bind_visibility_from(v, 'value'):
  472. ui.slider(min=1, max=3).bind_value(demo, 'number')
  473. ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
  474. ui.number().bind_value(demo, 'number')
  475. @example('''#### UI Updates
  476. 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.
  477. In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
  478. The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
  479. ''')
  480. def ui_updates_example():
  481. from random import randint
  482. def add():
  483. numbers.options.rowData.append({'numbers': randint(0, 100)})
  484. numbers.update()
  485. def clear():
  486. numbers.options.rowData.clear()
  487. ui.update(numbers)
  488. numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
  489. ui.button('Add', on_click=add)
  490. ui.button('Clear', on_click=clear)
  491. @example('''#### Async event handlers
  492. Most elements also support asynchronous event handlers.
  493. Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
  494. ''')
  495. def async_handlers_example():
  496. import asyncio
  497. async def async_task():
  498. ui.notify('Asynchronous task started')
  499. await asyncio.sleep(5)
  500. ui.notify('Asynchronous task finished')
  501. ui.button('start async task', on_click=async_task)
  502. h3('Pages')
  503. @example(ui.page)
  504. def page_example():
  505. @ui.page('/other_page')
  506. def other_page():
  507. ui.label('Welcome to the other side')
  508. ui.link('Back to main page', '#page')
  509. @ui.page('/dark_page', dark=True)
  510. def dark_page():
  511. ui.label('Welcome to the dark side')
  512. ui.link('Back to main page', '#page')
  513. ui.link('Visit other page', other_page)
  514. ui.link('Visit dark page', dark_page)
  515. @example('''#### Shared and Private Pages
  516. By default, pages created with the `@ui.page` decorator are "private".
  517. Their content is re-created for each client.
  518. Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
  519. With `shared=True` you can create a shared page.
  520. Its content is created once at startup and each client sees the *same* elements.
  521. Here, the displayed ID remains constant when the browser reloads the page.
  522. #### Index Page
  523. All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
  524. 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.
  525. ''')
  526. def shared_and_private_pages_example():
  527. from uuid import uuid4
  528. @ui.page('/private_page')
  529. async def private_page():
  530. ui.label(f'private page with ID {uuid4()}')
  531. @ui.page('/shared_page', shared=True)
  532. async def shared_page():
  533. ui.label(f'shared page with ID {uuid4()}')
  534. ui.link('private page', private_page)
  535. ui.link('shared page', shared_page)
  536. @example('''#### Pages with Path Parameters
  537. Page routes can contain parameters like [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/>).
  538. If type-annotated, they are automatically converted to bool, int, float and complex values.
  539. If the page function expects a `request` argument, the request object is automatically provided.
  540. ''')
  541. def page_with_path_parameters_example():
  542. @ui.page('/repeat/{word}/{count}')
  543. def page(word: str, count: int):
  544. ui.label(word * count)
  545. ui.link('Say hi to Santa!', 'repeat/Ho! /3')
  546. @example('''#### Yielding for Page-Ready
  547. This is a handy alternative to the `on_page_ready` callback of the `@ui.page` decorator.
  548. If a `yield` statement is provided in a page builder function, all code below that statement is executed after the page is ready.
  549. This allows you to execute JavaScript; which is only possible after the page has been loaded (see [#112](https://github.com/zauberzeug/nicegui/issues/112)).
  550. Also it is possible to do async stuff while the user already sees the content which was added before the yield statement.
  551. The yield statement returns `nicegui.events.PageEvent`.
  552. This contains the websocket of the client.
  553. ''')
  554. def yield_page_ready_example():
  555. import asyncio
  556. from typing import Generator
  557. from nicegui.events import PageEvent
  558. @ui.page('/yield_page_ready')
  559. async def yield_page_ready() -> Generator[None, PageEvent, None]:
  560. ui.label('This text is displayed immediately.')
  561. page_ready = yield
  562. await ui.run_javascript('document.title = "JavaScript-Controlled Title")')
  563. await asyncio.sleep(2)
  564. ui.label('This text is displayed 2 seconds after the page has been fully loaded.')
  565. ui.label(f'The IP address {page_ready.socket.client.host} could be obtained from the websocket.')
  566. ui.link('show page-ready code after yield', '/yield_page_ready')
  567. @example('''#### Page Layout
  568. With `ui.header`, `ui.footer`, `ui.left_drawer` and `ui.right_drawer` you can add additional layout elements to a page.
  569. The `fixed` argument controls whether the element should scroll or stay fixed on the screen.
  570. The `top_corner` and `bottom_corner` arguments indicate whether a drawer should expand to the top or bottom of the page.
  571. See <https://quasar.dev/layout/header-and-footer> and <https://quasar.dev/layout/drawer> for more information about possible props like
  572. `elevated`, `bordered` and many more.
  573. With `ui.page_sticky` you can place an element "sticky" on the screen.
  574. See <https://quasar.dev/layout/page-sticky> for more information.
  575. ''')
  576. def page_layout_example():
  577. @ui.page('/page_layout')
  578. async def page_layout():
  579. ui.label('CONTENT')
  580. [ui.label(f'Line {i}') for i in range(100)]
  581. with ui.header().style('background-color: #3874c8').props('elevated'):
  582. ui.label('HEADER')
  583. with ui.left_drawer(top_corner=True, bottom_corner=True).style('background-color: #d7e3f4'):
  584. ui.label('LEFT DRAWER')
  585. with ui.right_drawer(fixed=False).style('background-color: #ebf1fa').props('bordered'):
  586. ui.label('RIGHT DRAWER')
  587. with ui.footer().style('background-color: #3874c8'):
  588. ui.label('FOOTER')
  589. ui.link('show page with fancy layout', page_layout)
  590. @example(ui.open)
  591. def ui_open_example():
  592. @ui.page('/yet_another_page')
  593. def yet_another_page():
  594. ui.label('Welcome to yet another page')
  595. ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
  596. ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
  597. @example('''#### Sessions
  598. `ui.page` provides an optional `on_connect` argument to register a callback.
  599. It is invoked for each new connection to the page.
  600. 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).
  601. It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
  602. ''')
  603. def sessions_example():
  604. from collections import Counter
  605. from datetime import datetime
  606. from starlette.requests import Request
  607. id_counter = Counter()
  608. creation = datetime.now().strftime('%H:%M, %d %B %Y')
  609. def handle_connection(request: Request):
  610. id_counter[request.session_id] += 1
  611. visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
  612. @ui.page('/session_demo', on_connect=handle_connection)
  613. def session_demo():
  614. global visits
  615. visits = ui.label()
  616. ui.link('Visit session demo', session_demo)
  617. @example('''#### JavaScript
  618. With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
  619. The asynchronous function will return after the command(s) are executed.
  620. The result of the execution is returned as a dictionary containing the response string per websocket.
  621. You can also set `respond=False` to send a command without waiting for a response.
  622. ''')
  623. def javascript_example():
  624. async def alert():
  625. await ui.run_javascript('alert("Hello!")', respond=False)
  626. async def get_date():
  627. response = await ui.run_javascript('Date()')
  628. for socket, time in response.items():
  629. ui.notify(f'Browser time on host {socket.client.host}: {time}')
  630. ui.button('fire and forget', on_click=alert)
  631. ui.button('receive result', on_click=get_date)
  632. h3('Routes')
  633. @example(ui.get)
  634. def get_example():
  635. from starlette import requests, responses
  636. @ui.get('/another/route/{id}')
  637. def produce_plain_response(id: str, request: requests.Request):
  638. return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
  639. ui.link('Try yet another route!', 'another/route/42')
  640. @example(ui.add_static_files)
  641. def add_static_files_example():
  642. ui.add_static_files('/examples', 'examples')
  643. ui.link('Slideshow Example (raw file)', 'examples/slideshow/main.py')
  644. with ui.image('examples/slideshow/slides/slide1.jpg'):
  645. ui.label('first image from slideshow').classes('absolute-bottom text-subtitle2')
  646. @example(ui.add_route)
  647. def add_route_example():
  648. import starlette
  649. ui.add_route(starlette.routing.Route(
  650. '/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
  651. ))
  652. ui.link('Try the new route!', 'new/route')
  653. h3('Configuration')
  654. @example('''#### ui.run
  655. You can call `ui.run()` with optional arguments:
  656. - `host` (default: `'0.0.0.0'`)
  657. - `port` (default: `8080`)
  658. - `title` (default: `'NiceGUI'`)
  659. - `favicon`: relative filepath to a favicon (default: `None`, NiceGUI icon will be used)
  660. - `dark`: whether to use Quasar's dark mode (default: `False`, use `None` for "auto" mode)
  661. - `main_page_classes`: configure Quasar classes of main page (default: `'q-pa-md column items-start'`)
  662. - `binding_refresh_interval`: time between binding updates (default: `0.1` seconds, bigger is more cpu friendly)
  663. - `show`: automatically open the ui in a browser tab (default: `True`)
  664. - `reload`: automatically reload the ui on file changes (default: `True`)
  665. - `uvicorn_logging_level`: logging level for uvicorn server (default: `'warning'`)
  666. - `uvicorn_reload_dirs`: string with comma-separated list for directories to be monitored (default is current working directory only)
  667. - `uvicorn_reload_includes`: string with comma-separated list of glob-patterns which trigger reload on modification (default: `'.py'`)
  668. - `uvicorn_reload_excludes`: string with comma-separated list of glob-patterns which should be ignored for reload (default: `'.*, .py[cod], .sw.*, ~*'`)
  669. - `exclude`: comma-separated string to exclude elements (with corresponding JavaScript libraries) to save bandwidth
  670. (possible entries: chart, colors, interactive_image, keyboard, log, joystick, scene, table)
  671. The environment variables `HOST` and `PORT` can also be used to configure NiceGUI.
  672. To avoid the potentially costly import of Matplotlib, you set the environment variable `MATPLOTLIB=false`.
  673. This will make `ui.plot` and `ui.line_plot` unavailable.
  674. ''')
  675. def ui_run_example():
  676. ui.label('dark page on port 7000 without reloading')
  677. # ui.run(dark=True, port=7000, reload=False)
  678. # HACK: turn expensive line plot off after 10 seconds
  679. def handle_change(self, msg):
  680. def turn_off():
  681. line_checkbox.value = False
  682. ui.notify('Turning off that line plot to save resources on our live demo server. 😎')
  683. line_checkbox.value = msg.value
  684. if msg.value:
  685. with Context(line_checkbox.view):
  686. ui.timer(10.0, turn_off, once=True)
  687. line_checkbox.update()
  688. return False
  689. line_checkbox.view.on('input', handle_change)
  690. # HACK: start countdown here to avoid using global lifecycle hook
  691. create_task(countdown(), name='countdown')