demo.py 4.5 KB

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