documentation_tools.py 7.8 KB

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