example.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. import inspect
  2. import re
  3. from typing import Callable, 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. class example:
  10. def __init__(self, content: Union[Callable, type, str]) -> None:
  11. self.content = content
  12. self.markdown_classes = f'w-full max-w-screen-lg flex-none'
  13. self.rendering_classes = f'w-80 text-lg'
  14. self.source_classes = f'w-[43rem] overflow-auto'
  15. def __call__(self, f: Callable) -> Callable:
  16. with ui.row().classes('q-mb-xl'):
  17. if isinstance(self.content, str):
  18. _add_html_anchor(ui.markdown(self.content).classes(self.markdown_classes))
  19. else:
  20. doc = self.content.__doc__ or self.content.__init__.__doc__
  21. html: str = docutils.core.publish_parts(doc, writer_name='html5_polyglot')['html_body']
  22. html = html.replace('<p>', '<h4>', 1)
  23. html = html.replace('</p>', '</h4>', 1)
  24. html = html.replace('param ', '')
  25. html = apply_tailwind(html)
  26. _add_html_anchor(ui.html(html).classes(self.markdown_classes))
  27. with ui.row().classes('items-stretch max-w-screen-lg'):
  28. code = inspect.getsource(f).splitlines()
  29. indentation = len(code[0].split('@example')[0]) + 4
  30. while not code[0].startswith(' ' * indentation):
  31. del code[0]
  32. code = [l[indentation:] for l in code]
  33. while code[0].startswith('global '):
  34. del code[0]
  35. code.insert(0, '```python')
  36. code.insert(1, 'from nicegui import ui')
  37. if code[2].split()[0] not in ['from', 'import']:
  38. code.insert(2, '')
  39. for l, line in enumerate(code):
  40. if line.startswith('# ui.'):
  41. code[l] = line[2:]
  42. if line.startswith('# ui.run('):
  43. break
  44. else:
  45. code.append('')
  46. code.append('ui.run()')
  47. code.append('```')
  48. code = '\n'.join(code)
  49. with python_window().classes(self.source_classes):
  50. ui.markdown(code)
  51. with browser_window().classes(self.rendering_classes):
  52. f()
  53. return f
  54. def _add_html_anchor(element: ui.html) -> None:
  55. html = element.content
  56. match = REGEX_H4.search(html)
  57. if not match:
  58. return
  59. headline = match.groups()[0].strip()
  60. headline_id = SPECIAL_CHARACTERS.sub('_', headline).lower()
  61. if not headline_id:
  62. return
  63. icon = '<span class="material-icons">link</span>'
  64. anchor = f'<a href="reference#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
  65. html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
  66. html = html.replace('</h4>', f' {anchor}</h4>', 1)
  67. element.content = html
  68. def _add_dots() -> None:
  69. with ui.row().classes('gap-1').style('transform: translate(-6px, -6px)'):
  70. ui.icon('circle').style('font-size: 75%').classes('text-red-400')
  71. ui.icon('circle').style('font-size: 75%').classes('text-yellow-400')
  72. ui.icon('circle').style('font-size: 75%').classes('text-green-400')
  73. def window(color: str) -> ui.card:
  74. with ui.card().style(f'box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); background: {color}') as card:
  75. _add_dots()
  76. return card
  77. def python_window() -> ui.card:
  78. return window('#eff5ff')
  79. def browser_window() -> ui.card:
  80. with ui.card().classes('h-fill').style(f'box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); background: white') as card:
  81. with ui.row().classes('mb-2 items-center gap-2').style('margin: -8px; width: calc(100% + 16px); margin-bottom: 8px'):
  82. ui.icon('arrow_back').classes('text-gray-300')
  83. ui.icon('arrow_forward').classes('text-gray-300')
  84. ui.icon('refresh').classes('text-gray-300')
  85. ui.label('http://localhost:8080/').classes('grow text-xs text-gray-400 bg-gray-100 px-3 py-1 rounded-full')
  86. return card
  87. def bash_window() -> ui.card:
  88. return window('#e8e8e8')
  89. def css_for_examples() -> str:
  90. return '''
  91. dl {
  92. display: grid;
  93. grid-template-columns: max-content auto;
  94. }
  95. dt {
  96. grid-column-start: 1;
  97. margin-right: 1em;
  98. font-weight: bold;
  99. }
  100. dd {
  101. grid-column-start: 2;
  102. }
  103. '''