example.py 6.0 KB

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