main.py 2.2 KB

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