main.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/env python3
  2. from nicegui import ui, wp
  3. from contextlib import contextmanager
  4. import inspect
  5. from nicegui.elements.element import Element
  6. import sys
  7. import docutils.core
  8. # add docutils css to webpage
  9. wp.head_html += docutils.core.publish_parts('', writer_name='html')['stylesheet']
  10. @contextmanager
  11. def example(element: Element):
  12. callFrame = inspect.currentframe().f_back.f_back
  13. begin = callFrame.f_lineno
  14. with ui.row(classes='flex w-full'):
  15. doc = element.__init__.__doc__
  16. if doc:
  17. html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
  18. html = html.replace('<p>', '<h3>', 1)
  19. html = html.replace('</p>', '</h3>', 1)
  20. ui.html(html, classes='mr-8 w-4/12')
  21. else:
  22. ui.label(element.__name__, 'h5')
  23. with ui.card(classes='mt-12 w-2/12'):
  24. yield
  25. callFrame = inspect.currentframe().f_back.f_back
  26. end = callFrame.f_lineno
  27. code = inspect.getsource(sys.modules[__name__])
  28. code = code.splitlines()[begin:end]
  29. code = [l[4:] for l in code]
  30. code.insert(0, '```python')
  31. code.insert(1, 'from nicegui import ui')
  32. code.append('```')
  33. code = '\n'.join(code)
  34. ui.markdown(code, classes='mt-12 w-5/12 overflow-auto')
  35. with open('README.md', 'r') as file:
  36. ui.markdown(file.read())
  37. with example(ui.timer):
  38. from datetime import datetime
  39. clock = ui.label()
  40. t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X")))
  41. ui.checkbox('active').bind_value(t.active)
  42. with example(ui.button):
  43. def button_increment():
  44. global button_count
  45. button_count += 1
  46. button_result.set_text(f'pressed: {button_count}')
  47. button_count = 0
  48. ui.button('Button', on_click=button_increment)
  49. button_result = ui.label('pressed: 0')
  50. with example(ui.input):
  51. ui.input(
  52. label='Text',
  53. placeholder='press ENTER to apply',
  54. on_change=lambda e: result.set_text('you typed: ' + e.value)
  55. )
  56. result = ui.label('')