example.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import inspect
  2. import re
  3. from typing import Callable, Optional, Union
  4. import docutils.core
  5. from nicegui import ui
  6. from nicegui.elements.markdown import apply_tailwind
  7. REGEX_H4 = re.compile(r'<h4.*?>(.*?)</h4>')
  8. SPECIAL_CHARACTERS = re.compile('[^(a-z)(A-Z)(0-9)-]')
  9. PYTHON_BGCOLOR = '#e3e9f2'
  10. PYTHON_COLOR = '#eff5ff'
  11. BASH_BGCOLOR = '#dcdcdc'
  12. BASH_COLOR = '#e8e8e8'
  13. BROWSER_BGCOLOR = '#f2f2f2'
  14. BROWSER_COLOR = '#ffffff'
  15. class example:
  16. def __init__(self, content: Union[Callable, type, str], browser_title: Optional[str] = None) -> None:
  17. self.content = content
  18. self.browser_title = browser_title
  19. def __call__(self, f: Callable) -> Callable:
  20. with ui.column().classes('w-full mb-8'):
  21. if isinstance(self.content, str):
  22. documentation = ui.markdown(self.content)
  23. else:
  24. doc = self.content.__doc__ or self.content.__init__.__doc__
  25. html: str = docutils.core.publish_parts(doc, writer_name='html5_polyglot')['html_body']
  26. html = html.replace('<p>', '<h4>', 1)
  27. html = html.replace('</p>', '</h4>', 1)
  28. html = html.replace('param ', '')
  29. html = apply_tailwind(html)
  30. documentation = ui.html(html)
  31. _add_html_anchor(documentation.classes('text-lg documentation bold-links'))
  32. with ui.column().classes('w-full items-stretch gap-8 no-wrap xl:flex-row'):
  33. code = inspect.getsource(f).split('# END OF EXAMPLE')[0].strip().splitlines()
  34. indentation = len(code[0].split('@example')[0]) + 4
  35. while not code[0].startswith(' ' * indentation):
  36. del code[0]
  37. code = [l[indentation:] for l in code]
  38. code.insert(0, '```python')
  39. code.insert(1, 'from nicegui import ui')
  40. if code[2].split()[0] not in ['from', 'import']:
  41. code.insert(2, '')
  42. for l, line in enumerate(code):
  43. if line.startswith('# ui.'):
  44. code[l] = line[2:]
  45. if line.startswith('# ui.run('):
  46. break
  47. else:
  48. code.append('')
  49. code.append('ui.run()')
  50. code.append('```')
  51. code = '\n'.join(code)
  52. with python_window(classes='w-full max-w-[48rem]'):
  53. ui.markdown(code)
  54. with browser_window(self.browser_title, classes='w-full max-w-[48rem] xl:max-w-[20rem] min-h-[10rem] browser-window'):
  55. f()
  56. return f
  57. def _add_html_anchor(element: ui.html) -> None:
  58. html = element.content
  59. match = REGEX_H4.search(html)
  60. if not match:
  61. return
  62. headline = match.groups()[0].strip()
  63. headline_id = SPECIAL_CHARACTERS.sub('_', headline).lower()
  64. if not headline_id:
  65. return
  66. icon = '<span class="material-icons">link</span>'
  67. link = f'<a href="reference#{headline_id}" class="hover:text-black" style="color: #ddd">{icon}</a>'
  68. target = f'<div id="{headline_id}" style="position: relative; top: -90px"></div>'
  69. html = html.replace('<h4', f'{target}<h4', 1)
  70. html = html.replace('</h4>', f' {link}</h4>', 1)
  71. element.content = html
  72. def _window_header(bgcolor: str) -> ui.row():
  73. return ui.row().classes(f'w-full h-8 p-2 bg-[{bgcolor}]')
  74. def _dots() -> None:
  75. with ui.row().classes('gap-1 relative left-[1px] top-[1px]'):
  76. ui.icon('circle').classes('text-[13px] text-red-400')
  77. ui.icon('circle').classes('text-[13px] text-yellow-400')
  78. ui.icon('circle').classes('text-[13px] text-green-400')
  79. def _title(title: str) -> None:
  80. ui.label(title).classes('text-sm text-gray-600 absolute left-1/2 top-[6px]').style('transform: translateX(-50%)')
  81. def _tab(name: str, color: str, bgcolor: str) -> None:
  82. with ui.row().classes('gap-0'):
  83. with ui.label().classes(f'w-2 h-[24px] bg-[{color}]'):
  84. ui.label().classes(f'w-full h-full bg-[{bgcolor}] rounded-br-[6px]')
  85. ui.label(name).classes(f'text-sm text-gray-600 px-6 py-1 h-[24px] rounded-t-[6px] bg-[{color}]')
  86. with ui.label().classes(f'w-2 h-[24px] bg-[{color}]'):
  87. ui.label().classes(f'w-full h-full bg-[{bgcolor}] rounded-bl-[6px]')
  88. def window(color: str, bgcolor: str, *, title: str = '', tab: str = '', classes: str = '') -> ui.column:
  89. with ui.card().classes(f'no-wrap bg-[{color}] rounded-xl p-0 gap-0 {classes}') \
  90. .style('box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1)'):
  91. with _window_header(bgcolor):
  92. _dots()
  93. if title:
  94. _title(title)
  95. if tab:
  96. _tab(tab, color, bgcolor)
  97. return ui.column().classes('w-full h-full overflow-auto')
  98. def python_window(*, classes: str = '') -> ui.card:
  99. return window(PYTHON_COLOR, PYTHON_BGCOLOR, title='main.py', classes=classes).classes('p-2')
  100. def bash_window(*, classes: str = '') -> ui.card:
  101. return window(BASH_COLOR, BASH_BGCOLOR, title='bash', classes=classes).classes('p-2')
  102. def browser_window(title: Optional[str] = None, *, classes: str = '') -> ui.card:
  103. return window(BROWSER_COLOR, BROWSER_BGCOLOR, tab=title or 'NiceGUI', classes=classes).classes('p-4')