action_events.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. from nicegui import app, ui
  2. from ...model import SectionDocumentation
  3. from ..more.generic_events_documentation import GenericEventsDocumentation
  4. from ..more.keyboard_documentation import KeyboardDocumentation
  5. from ..more.refreshable_documentation import RefreshableDocumentation
  6. from ..more.run_javascript_documentation import RunJavascriptDocumentation
  7. from ..more.storage_documentation import StorageDocumentation
  8. from ..more.timer_documentation import TimerDocumentation
  9. class ActionEventsDocumentation(SectionDocumentation, title='Action & *Events*', name='action_events'):
  10. def content(self) -> None:
  11. self.intro(TimerDocumentation())
  12. self.intro(KeyboardDocumentation())
  13. @self.demo('UI Updates', '''
  14. NiceGUI tries to automatically synchronize the state of UI elements with the client,
  15. e.g. when a label text, an input value or style/classes/props of an element have changed.
  16. In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
  17. The demo code shows both methods for a `ui.echart`, where it is difficult to automatically detect changes in the `options` dictionary.
  18. ''')
  19. def ui_updates_demo():
  20. from random import random
  21. chart = ui.echart({
  22. 'xAxis': {'type': 'value'},
  23. 'yAxis': {'type': 'value'},
  24. 'series': [{'type': 'line', 'data': [[0, 0], [1, 1]]}],
  25. })
  26. def add():
  27. chart.options['series'][0]['data'].append([random(), random()])
  28. chart.update()
  29. def clear():
  30. chart.options['series'][0]['data'].clear()
  31. ui.update(chart)
  32. with ui.row():
  33. ui.button('Add', on_click=add)
  34. ui.button('Clear', on_click=clear)
  35. self.intro(RefreshableDocumentation())
  36. @self.demo('Async event handlers', '''
  37. Most elements also support asynchronous event handlers.
  38. Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
  39. ''')
  40. def async_handlers_demo():
  41. import asyncio
  42. async def async_task():
  43. ui.notify('Asynchronous task started')
  44. await asyncio.sleep(5)
  45. ui.notify('Asynchronous task finished')
  46. ui.button('start async task', on_click=async_task)
  47. self.intro(GenericEventsDocumentation())
  48. @self.demo('Running CPU-bound tasks', '''
  49. NiceGUI provides a `cpu_bound` function for running CPU-bound tasks in a separate process.
  50. This is useful for long-running computations that would otherwise block the event loop and make the UI unresponsive.
  51. The function returns a future that can be awaited.
  52. ''')
  53. def cpu_bound_demo():
  54. import time
  55. from nicegui import run
  56. def compute_sum(a: float, b: float) -> float:
  57. time.sleep(1) # simulate a long-running computation
  58. return a + b
  59. async def handle_click():
  60. result = await run.cpu_bound(compute_sum, 1, 2)
  61. ui.notify(f'Sum is {result}')
  62. # ui.button('Compute', on_click=handle_click)
  63. # END OF DEMO
  64. async def mock_click():
  65. import asyncio
  66. await asyncio.sleep(1)
  67. ui.notify('Sum is 3')
  68. ui.button('Compute', on_click=mock_click)
  69. @self.demo('Running I/O-bound tasks', '''
  70. NiceGUI provides an `io_bound` function for running I/O-bound tasks in a separate thread.
  71. This is useful for long-running I/O operations that would otherwise block the event loop and make the UI unresponsive.
  72. The function returns a future that can be awaited.
  73. ''')
  74. def io_bound_demo():
  75. import requests
  76. from nicegui import run
  77. async def handle_click():
  78. URL = 'https://httpbin.org/delay/1'
  79. response = await run.io_bound(requests.get, URL, timeout=3)
  80. ui.notify(f'Downloaded {len(response.content)} bytes')
  81. ui.button('Download', on_click=handle_click)
  82. self.intro(RunJavascriptDocumentation())
  83. @self.demo('Events', '''
  84. You can register coroutines or functions to be called for the following events:
  85. - `app.on_startup`: called when NiceGUI is started or restarted
  86. - `app.on_shutdown`: called when NiceGUI is shut down or restarted
  87. - `app.on_connect`: called for each client which connects (optional argument: nicegui.Client)
  88. - `app.on_disconnect`: called for each client which disconnects (optional argument: nicegui.Client)
  89. - `app.on_exception`: called when an exception occurs (optional argument: exception)
  90. When NiceGUI is shut down or restarted, all tasks still in execution will be automatically canceled.
  91. ''')
  92. def lifecycle_demo():
  93. from datetime import datetime
  94. from nicegui import app
  95. # dt = datetime.now()
  96. def handle_connection():
  97. global dt
  98. dt = datetime.now()
  99. app.on_connect(handle_connection)
  100. label = ui.label()
  101. ui.timer(1, lambda: label.set_text(f'Last new connection: {dt:%H:%M:%S}'))
  102. # END OF DEMO
  103. global dt
  104. dt = datetime.now()
  105. @self.demo(app.shutdown)
  106. def shutdown_demo():
  107. from nicegui import app
  108. # ui.button('shutdown', on_click=app.shutdown)
  109. #
  110. # ui.run(reload=False)
  111. # END OF DEMO
  112. ui.button('shutdown', on_click=lambda: ui.notify(
  113. 'Nah. We do not actually shutdown the documentation server. Try it in your own app!'))
  114. self.intro(StorageDocumentation())