demo.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import inspect
  2. import re
  3. from typing import Callable, Optional, Union
  4. import isort
  5. from nicegui import helpers, json, ui
  6. from .intersection_observer import IntersectionObserver as intersection_observer
  7. from .windows import browser_window, python_window
  8. UNCOMMENT_PATTERN = re.compile(r'^(\s*)# ?')
  9. def _uncomment(text: str) -> str:
  10. return UNCOMMENT_PATTERN.sub(r'\1', text) # NOTE: non-executed lines should be shown in the code examples
  11. def demo(f: Callable, *, lazy: bool = True, tab: Optional[Union[str, Callable]] = None) -> Callable:
  12. """Render a callable as a demo with Python code and browser window."""
  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', 1)[0].strip().splitlines()
  15. code = [line for line in code if not line.endswith('# HIDE')]
  16. while not code[0].strip().startswith(('def', '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. full_code = isort.code('\n'.join(code), no_sections=True, lines_after_imports=1)
  31. with python_window(classes='w-full max-w-[44rem]'):
  32. ui.markdown(f'````python\n{full_code}\n````')
  33. ui.icon('content_copy', size='xs') \
  34. .classes('absolute right-2 top-10 opacity-10 hover:opacity-80 cursor-pointer') \
  35. .on('click', js_handler=f'() => navigator.clipboard.writeText({json.dumps(full_code)})') \
  36. .on('click', lambda: ui.notify('Copied to clipboard', type='positive', color='primary'), [])
  37. with browser_window(title=tab,
  38. classes='w-full max-w-[44rem] min-[1500px]:max-w-[20rem] min-h-[10rem] browser-window') as window:
  39. if lazy:
  40. spinner = ui.spinner(size='lg').props('thickness=2')
  41. async def handle_intersection():
  42. window.remove(spinner)
  43. if helpers.is_coroutine_function(f):
  44. await f()
  45. else:
  46. f()
  47. intersection_observer(on_intersection=handle_intersection)
  48. else:
  49. assert not helpers.is_coroutine_function(f), 'async functions are not supported in non-lazy demos'
  50. f()
  51. return f