demo.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import inspect
  2. import re
  3. from typing import Callable, Optional, Union
  4. import isort
  5. from nicegui import ui
  6. from .intersection_observer import IntersectionObserver as intersection_observer
  7. PYTHON_BGCOLOR = '#00000010'
  8. PYTHON_COLOR = '#eef5fb'
  9. BASH_BGCOLOR = '#00000010'
  10. BASH_COLOR = '#e8e8e8'
  11. BROWSER_BGCOLOR = '#00000010'
  12. BROWSER_COLOR = '#ffffff'
  13. uncomment_pattern = re.compile(r'^(\s*)# ?')
  14. def uncomment(text: str) -> str:
  15. """non-executed lines should be shown in the code examples"""
  16. return uncomment_pattern.sub(r'\1', text)
  17. def demo(f: Callable) -> Callable:
  18. with ui.column().classes('w-full items-stretch gap-8 no-wrap min-[1500px]:flex-row'):
  19. code = inspect.getsource(f).split('# END OF DEMO')[0].strip().splitlines()
  20. code = [line for line in code if not line.endswith("# HIDE")]
  21. while not code[0].strip().startswith('def') and not code[0].strip().startswith('async def'):
  22. del code[0]
  23. del code[0]
  24. if code[0].strip().startswith('"""'):
  25. while code[0].strip() != '"""':
  26. del code[0]
  27. del code[0]
  28. indentation = len(code[0]) - len(code[0].lstrip())
  29. code = [line[indentation:] for line in code]
  30. code = ['from nicegui import ui'] + [uncomment(line) for line in code]
  31. code = ['' if line == '#' else line for line in code]
  32. if not code[-1].startswith('ui.run('):
  33. code.append('')
  34. code.append('ui.run()')
  35. code = isort.code('\n'.join(code), no_sections=True, lines_after_imports=1)
  36. with python_window(classes='w-full max-w-[44rem]'):
  37. async def copy_code():
  38. await ui.run_javascript('navigator.clipboard.writeText(`' + code + '`)', respond=False)
  39. ui.notify('Copied to clipboard', type='positive', color='primary')
  40. ui.markdown(f'````python\n{code}\n````')
  41. ui.icon('content_copy', size='xs') \
  42. .classes('absolute right-2 top-10 opacity-10 hover:opacity-80 cursor-pointer') \
  43. .on('click', copy_code)
  44. with browser_window(title=getattr(f, 'tab', None),
  45. classes='w-full max-w-[44rem] min-[1500px]:max-w-[20rem] min-h-[10rem] browser-window'):
  46. intersection_observer(on_intersection=f)
  47. return f
  48. def _window_header(bgcolor: str) -> ui.row():
  49. return ui.row().classes(f'w-full h-8 p-2 bg-[{bgcolor}]')
  50. def _dots() -> None:
  51. with ui.row().classes('gap-1 relative left-[1px] top-[1px]'):
  52. ui.icon('circle').classes('text-[13px] text-red-400')
  53. ui.icon('circle').classes('text-[13px] text-yellow-400')
  54. ui.icon('circle').classes('text-[13px] text-green-400')
  55. def _title(title: str) -> None:
  56. ui.label(title).classes('text-sm text-gray-600 absolute left-1/2 top-[6px]').style('transform: translateX(-50%)')
  57. def _tab(content: Union[str, Callable], color: str, bgcolor: str) -> None:
  58. with ui.row().classes('gap-0'):
  59. with ui.label().classes(f'w-2 h-[24px] bg-[{color}]'):
  60. ui.label().classes(f'w-full h-full bg-[{bgcolor}] rounded-br-[6px]')
  61. with ui.row().classes(f'text-sm text-gray-600 px-6 py-1 h-[24px] rounded-t-[6px] bg-[{color}] items-center gap-2'):
  62. if callable(content):
  63. content()
  64. else:
  65. ui.label(content)
  66. with ui.label().classes(f'w-2 h-[24px] bg-[{color}]'):
  67. ui.label().classes(f'w-full h-full bg-[{bgcolor}] rounded-bl-[6px]')
  68. def window(color: str, bgcolor: str, *,
  69. title: str = '', tab: Union[str, Callable] = '', classes: str = '') -> ui.column:
  70. with ui.card().classes(f'no-wrap bg-[{color}] rounded-xl p-0 gap-0 {classes}') \
  71. .style('box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1)'):
  72. with _window_header(bgcolor):
  73. _dots()
  74. if title:
  75. _title(title)
  76. if tab:
  77. _tab(tab, color, bgcolor)
  78. return ui.column().classes('w-full h-full overflow-auto')
  79. def python_window(title: Optional[str] = None, *, classes: str = '') -> ui.card:
  80. return window(PYTHON_COLOR, PYTHON_BGCOLOR, title=title or 'main.py', classes=classes).classes('p-2 python-window')
  81. def bash_window(*, classes: str = '') -> ui.card:
  82. return window(BASH_COLOR, BASH_BGCOLOR, title='bash', classes=classes).classes('p-2 bash-window')
  83. def browser_window(title: Optional[Union[str, Callable]] = None, *, classes: str = '') -> ui.card:
  84. return window(BROWSER_COLOR, BROWSER_BGCOLOR, tab=title or 'NiceGUI', classes=classes).classes('p-4 browser-window')