documentation_tools.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. import importlib
  2. import inspect
  3. import re
  4. from typing import Callable, Optional, Union
  5. import docutils.core
  6. from nicegui import globals, ui
  7. from nicegui.binding import BindableProperty
  8. from nicegui.elements.markdown import apply_tailwind, remove_indentation
  9. from .demo import demo
  10. SPECIAL_CHARACTERS = re.compile('[^(a-z)(A-Z)(0-9)-]')
  11. def pascal_to_snake(name: str) -> str:
  12. return re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower()
  13. def create_anchor_name(text: str) -> str:
  14. return SPECIAL_CHARACTERS.sub('_', text).lower()
  15. def get_menu() -> ui.left_drawer:
  16. return [element for element in globals.get_client().elements.values() if isinstance(element, ui.left_drawer)][0]
  17. def heading(text: str, *, make_menu_entry: bool = True) -> None:
  18. ui.html(f'<em>{text}</em>').classes('mt-8 text-3xl font-weight-500')
  19. if make_menu_entry:
  20. with get_menu():
  21. ui.label(text).classes('font-bold mt-4')
  22. def subheading(text: str, *, make_menu_entry: bool = True, more_link: Optional[str] = None) -> None:
  23. name = create_anchor_name(text)
  24. ui.html(f'<div id="{name}"></div>').style('position: relative; top: -90px')
  25. with ui.row().classes('gap-2 items-center relative'):
  26. if more_link:
  27. with ui.link(text, f'documentation/{more_link}').classes('text-2xl'):
  28. ui.icon('open_in_new', size='0.75em').classes('mb-1 ml-2')
  29. else:
  30. ui.label(text).classes('text-2xl')
  31. with ui.link(target=f'#{name}').classes('absolute').style('transform: translateX(-150%)'):
  32. ui.icon('link', size='sm').classes('opacity-10 hover:opacity-80')
  33. if make_menu_entry:
  34. with get_menu() as menu:
  35. async def click():
  36. if await ui.run_javascript(f'!!document.querySelector("div.q-drawer__backdrop")'):
  37. menu.hide()
  38. ui.open(f'#{name}')
  39. ui.link(text, target=f'#{name}').props('data-close-overlay').on('click', click)
  40. def render_docstring(doc: str, with_params: bool = True) -> ui.html:
  41. doc = remove_indentation(doc)
  42. doc = doc.replace('param ', '')
  43. html = docutils.core.publish_parts(doc, writer_name='html5_polyglot')['html_body']
  44. html = apply_tailwind(html)
  45. if not with_params:
  46. html = re.sub(r'<dl class=".* simple">.*?</dl>', '', html, flags=re.DOTALL)
  47. return ui.html(html).classes('documentation bold-links arrow-links')
  48. class text_demo:
  49. def __init__(self, title: str, explanation: str) -> None:
  50. self.title = title
  51. self.explanation = explanation
  52. self.make_menu_entry = True
  53. def __call__(self, f: Callable) -> Callable:
  54. subheading(self.title, make_menu_entry=self.make_menu_entry)
  55. ui.markdown(self.explanation).classes('bold-links arrow-links')
  56. return demo()(f)
  57. class intro_demo(text_demo):
  58. def __init__(self, title: str, explanation: str) -> None:
  59. super().__init__(title, explanation)
  60. self.make_menu_entry = False
  61. class element_demo:
  62. def __init__(self, element_class: Union[Callable, type], browser_title: Optional[str] = None) -> None:
  63. self.element_class = element_class
  64. self.browser_title = browser_title
  65. def __call__(self, f: Callable, *, more_link: Optional[str] = None) -> Callable:
  66. doc = self.element_class.__doc__ or self.element_class.__init__.__doc__
  67. title, documentation = doc.split('\n', 1)
  68. with ui.column().classes('w-full mb-8 gap-2'):
  69. subheading(title, more_link=more_link)
  70. render_docstring(documentation, with_params=more_link is None)
  71. return demo(browser_title=self.browser_title)(f)
  72. def load_demo(api: Union[type, Callable]) -> None:
  73. name = pascal_to_snake(api.__name__)
  74. try:
  75. module = importlib.import_module(f'website.more_documentation.{name}_documentation')
  76. except ModuleNotFoundError:
  77. module = importlib.import_module(f'website.more_documentation.{name.replace("_", "")}_documentation')
  78. element_demo(api)(getattr(module, 'main_demo'), more_link=name)
  79. def is_method_or_property(cls: type, attribute_name: str) -> bool:
  80. attribute = cls.__dict__.get(attribute_name, None)
  81. return (
  82. inspect.isfunction(attribute) or
  83. inspect.ismethod(attribute) or
  84. isinstance(attribute, property) or
  85. isinstance(attribute, BindableProperty)
  86. )
  87. def generate_class_doc(class_obj: type) -> None:
  88. mro = [base for base in class_obj.__mro__ if base.__module__.startswith('nicegui.')]
  89. ancestors = mro[1:]
  90. attributes = {}
  91. for base in reversed(mro):
  92. for name in dir(base):
  93. if not name.startswith('_') and is_method_or_property(base, name):
  94. attributes[name] = getattr(base, name, None)
  95. properties = {name: attribute for name, attribute in attributes.items() if not callable(attribute)}
  96. methods = {name: attribute for name, attribute in attributes.items() if callable(attribute)}
  97. if properties:
  98. subheading('Properties')
  99. with ui.column().classes('gap-2'):
  100. for name, property in sorted(properties.items()):
  101. ui.markdown(f'**`{name}`**`{generate_property_signature_description(property)}`')
  102. if property.__doc__:
  103. render_docstring(property.__doc__).classes('ml-8')
  104. if methods:
  105. subheading('Methods')
  106. with ui.column().classes('gap-2'):
  107. for name, method in sorted(methods.items()):
  108. ui.markdown(f'**`{name}`**`{generate_method_signature_description(method)}`')
  109. if method.__doc__:
  110. render_docstring(method.__doc__).classes('ml-8')
  111. if ancestors:
  112. subheading('Inherited from')
  113. with ui.column().classes('gap-2'):
  114. for ancestor in ancestors:
  115. ui.markdown(f'- `{ancestor.__name__}`')
  116. def generate_method_signature_description(method: Callable) -> str:
  117. param_strings = []
  118. for param in inspect.signature(method).parameters.values():
  119. param_string = param.name
  120. if param_string == 'self':
  121. continue
  122. if param.annotation != inspect.Parameter.empty:
  123. param_type = inspect.formatannotation(param.annotation)
  124. param_string += f''': {param_type.strip("'")}'''
  125. if param.default != inspect.Parameter.empty:
  126. param_string += f' = [...]' if callable(param.default) else f' = {repr(param.default)}'
  127. if param.kind == inspect.Parameter.VAR_POSITIONAL:
  128. param_string = f'*{param_string}'
  129. param_strings.append(param_string)
  130. method_signature = ', '.join(param_strings)
  131. description = f'({method_signature})'
  132. return_annotation = inspect.signature(method).return_annotation
  133. if return_annotation != inspect.Parameter.empty:
  134. return_type = inspect.formatannotation(return_annotation)
  135. description += f''' -> {return_type.strip("'").replace("typing_extensions.", "").replace("typing.", "")}'''
  136. return description
  137. def generate_property_signature_description(property: Optional[property]) -> str:
  138. description = ''
  139. if property is None:
  140. return ': BindableProperty'
  141. if property.fget:
  142. return_annotation = inspect.signature(property.fget).return_annotation
  143. if return_annotation != inspect.Parameter.empty:
  144. return_type = inspect.formatannotation(return_annotation)
  145. description += f': {return_type}'
  146. if property.fset:
  147. description += ' (settable)'
  148. if property.fdel:
  149. description += ' (deletable)'
  150. return description