documentation_tools.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. import importlib
  2. import inspect
  3. import re
  4. from pathlib import Path
  5. from typing import Callable, Optional, Union
  6. import docutils.core
  7. from nicegui import globals, ui
  8. from nicegui.elements.markdown import apply_tailwind
  9. from .demo import demo
  10. SPECIAL_CHARACTERS = re.compile('[^(a-z)(A-Z)(0-9)-]')
  11. def remove_indentation(text: str) -> str:
  12. """Remove indentation from a multi-line string based on the indentation of the first line."""
  13. lines = text.splitlines()
  14. while lines and not lines[0].strip():
  15. lines.pop(0)
  16. if not lines:
  17. return ''
  18. indentation = len(lines[0]) - len(lines[0].lstrip())
  19. return '\n'.join(line[indentation:] for line in lines)
  20. def pascal_to_snake(name: str) -> str:
  21. return re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower()
  22. def create_anchor_name(text: str) -> str:
  23. return SPECIAL_CHARACTERS.sub('_', text).lower()
  24. def get_menu() -> ui.left_drawer:
  25. return [element for element in globals.get_client().elements.values() if isinstance(element, ui.left_drawer)][0]
  26. def heading(text: str, *, make_menu_entry: bool = True) -> None:
  27. ui.html(f'<em>{text}</em>').classes('mt-8 text-3xl font-weight-500')
  28. if make_menu_entry:
  29. with get_menu():
  30. ui.label(text).classes('font-bold mt-4')
  31. def subheading(text: str, *, make_menu_entry: bool = True) -> None:
  32. name = create_anchor_name(text)
  33. ui.html(f'<div id="{name}"></div>').style('position: relative; top: -90px')
  34. with ui.row().classes('gap-2 items-center'):
  35. ui.label(text).classes('text-2xl')
  36. with ui.link(target=f'#{name}'):
  37. ui.icon('link', size='sm').classes('text-gray-400 hover:text-gray-800')
  38. if make_menu_entry:
  39. with get_menu() as menu:
  40. async def click():
  41. if await ui.run_javascript(f'!!document.querySelector("div.q-drawer__backdrop")'):
  42. menu.hide()
  43. ui.open(f'#{name}')
  44. ui.link(text, target=f'#{name}').props('data-close-overlay').on('click', click)
  45. def markdown(text: str) -> ui.markdown:
  46. return ui.markdown(remove_indentation(text))
  47. class text_demo:
  48. def __init__(self, title: str, explanation: str) -> None:
  49. self.title = title
  50. self.explanation = explanation
  51. self.make_menu_entry = True
  52. def __call__(self, f: Callable) -> Callable:
  53. subheading(self.title, make_menu_entry=self.make_menu_entry)
  54. markdown(self.explanation)
  55. return demo()(f)
  56. class intro_demo(text_demo):
  57. def __init__(self, title: str, explanation: str) -> None:
  58. super().__init__(title, explanation)
  59. self.make_menu_entry = False
  60. class element_demo:
  61. def __init__(self, element_class: Union[Callable, type], browser_title: Optional[str] = None) -> None:
  62. self.element_class = element_class
  63. self.browser_title = browser_title
  64. def __call__(self, f: Callable, *, more_link: Optional[str] = None) -> Callable:
  65. doc = self.element_class.__doc__ or self.element_class.__init__.__doc__
  66. title, documentation = doc.split('\n', 1)
  67. documentation = remove_indentation(documentation)
  68. documentation = documentation.replace('param ', '')
  69. html = docutils.core.publish_parts(documentation, writer_name='html5_polyglot')['html_body']
  70. html = apply_tailwind(html)
  71. with ui.column().classes('w-full mb-8 gap-2'):
  72. subheading(title)
  73. ui.html(html).classes('documentation bold-links arrow-links')
  74. wrapped = demo(browser_title=self.browser_title)(f)
  75. if more_link:
  76. ui.markdown(f'[More...](documentation/{more_link})').classes('bold-links mt-2')
  77. return wrapped
  78. def load_demo(element_class: type) -> None:
  79. name = pascal_to_snake(element_class.__name__)
  80. try:
  81. module = importlib.import_module(f'website.more_documentation.{name}_documentation')
  82. except ModuleNotFoundError:
  83. module = importlib.import_module(f'website.more_documentation.{name.replace("_", "")}_documentation')
  84. element_demo(element_class)(getattr(module, 'main_demo'), more_link=name)
  85. def generate_class_doc(class_obj: type) -> None:
  86. class_name = pascal_to_snake(class_obj.__name__)
  87. methods = [method for name, method in class_obj.__dict__.items() if not name.startswith('_') and callable(method)]
  88. if methods:
  89. subheading('Methods')
  90. with ui.column().classes('gap-2'):
  91. for method in methods:
  92. ui.markdown(f'`{class_name}.`**`{method.__name__}`**`{generate_method_signature_description(method)}`')
  93. if method.__doc__:
  94. markdown(method.__doc__).classes('ml-4')
  95. def generate_method_signature_description(method: Callable) -> str:
  96. param_strings = []
  97. for param in inspect.signature(method).parameters.values():
  98. param_string = param.name
  99. if param_string == 'self':
  100. continue
  101. if param.annotation != inspect.Parameter.empty:
  102. param_type = inspect.formatannotation(param.annotation)
  103. param_string += f': {param_type}'
  104. if param.default != inspect.Parameter.empty:
  105. param_string += f' = {param.default}'
  106. if param.kind == inspect.Parameter.VAR_POSITIONAL:
  107. param_string = f'*{param_string}'
  108. param_strings.append(param_string)
  109. method_signature = ', '.join(param_strings)
  110. description = f'({method_signature})'
  111. return_annotation = inspect.signature(method).return_annotation
  112. if return_annotation != inspect.Parameter.empty:
  113. return_type = inspect.formatannotation(return_annotation)
  114. return_description = f' -> {return_type}'
  115. description += return_description
  116. return description