tools.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. import importlib
  2. import inspect
  3. import re
  4. from typing import Callable, Optional, Union
  5. import docutils.core
  6. from nicegui import context, 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 context.get_client().elements.values() if isinstance(element, ui.left_drawer)][0]
  17. def heading(text: str, *, make_menu_entry: bool = True) -> None:
  18. ui.link_target(create_anchor_name(text))
  19. ui.html(f'<em>{text}</em>').classes('mt-8 text-3xl font-weight-500')
  20. if make_menu_entry:
  21. with get_menu():
  22. ui.label(text).classes('font-bold mt-4')
  23. def subheading(text: str, *, make_menu_entry: bool = True, more_link: Optional[str] = None) -> None:
  24. name = create_anchor_name(text)
  25. ui.html(f'<div id="{name}"></div>').style('position: relative; top: -90px')
  26. with ui.row().classes('gap-2 items-center relative'):
  27. if more_link:
  28. ui.link(text, f'documentation/{more_link}').classes('text-2xl')
  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('!!document.querySelector("div.q-drawer__backdrop")', timeout=5.0):
  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, tab: Optional[Union[str, Callable]] = None) -> None:
  50. self.title = title
  51. self.explanation = explanation
  52. self.make_menu_entry = True
  53. self.tab = tab
  54. def __call__(self, f: Callable) -> Callable:
  55. subheading(self.title, make_menu_entry=self.make_menu_entry)
  56. ui.markdown(self.explanation).classes('bold-links arrow-links')
  57. f.tab = self.tab
  58. return demo(f)
  59. class intro_demo(text_demo):
  60. def __init__(self, title: str, explanation: str) -> None:
  61. super().__init__(title, explanation)
  62. self.make_menu_entry = False
  63. class element_demo:
  64. def __init__(self, element_class: Union[Callable, type, str]) -> None:
  65. if isinstance(element_class, str):
  66. module = importlib.import_module(f'website.documentation.more.{element_class}_documentation')
  67. element_class = getattr(module, 'main_demo')
  68. self.element_class = element_class
  69. def __call__(self, f: Callable, *, more_link: Optional[str] = None) -> Callable:
  70. doc = f.__doc__ or self.element_class.__doc__ or self.element_class.__init__.__doc__
  71. title, documentation = doc.split('\n', 1)
  72. with ui.column().classes('w-full mb-8 gap-2'):
  73. if more_link:
  74. subheading(title, more_link=more_link)
  75. render_docstring(documentation, with_params=more_link is None)
  76. result = demo(f)
  77. if more_link:
  78. ui.markdown(f'See [more...](documentation/{more_link})').classes('bold-links arrow-links')
  79. return result
  80. def load_demo(api: Union[type, Callable, str]) -> None:
  81. name = api if isinstance(api, str) else pascal_to_snake(api.__name__)
  82. try:
  83. module = importlib.import_module(f'website.documentation.more.{name}_documentation')
  84. except ModuleNotFoundError:
  85. module = importlib.import_module(f'website.documentation.more.{name.replace("_", "")}_documentation')
  86. element_demo(api)(getattr(module, 'main_demo'), more_link=name)
  87. def is_method_or_property(cls: type, attribute_name: str) -> bool:
  88. attribute = cls.__dict__.get(attribute_name, None)
  89. return (
  90. inspect.isfunction(attribute) or
  91. inspect.ismethod(attribute) or
  92. isinstance(attribute, property) or
  93. isinstance(attribute, BindableProperty)
  94. )
  95. def generate_class_doc(class_obj: type) -> None:
  96. mro = [base for base in class_obj.__mro__ if base.__module__.startswith('nicegui.')]
  97. ancestors = mro[1:]
  98. attributes = {}
  99. for base in reversed(mro):
  100. for name in dir(base):
  101. if not name.startswith('_') and is_method_or_property(base, name):
  102. attributes[name] = getattr(base, name, None)
  103. properties = {name: attribute for name, attribute in attributes.items() if not callable(attribute)}
  104. methods = {name: attribute for name, attribute in attributes.items() if callable(attribute)}
  105. if properties:
  106. subheading('Properties')
  107. with ui.column().classes('gap-2'):
  108. for name, property in sorted(properties.items()):
  109. ui.markdown(f'**`{name}`**`{generate_property_signature_description(property)}`')
  110. if property.__doc__:
  111. render_docstring(property.__doc__).classes('ml-8')
  112. if methods:
  113. subheading('Methods')
  114. with ui.column().classes('gap-2'):
  115. for name, method in sorted(methods.items()):
  116. ui.markdown(f'**`{name}`**`{generate_method_signature_description(method)}`')
  117. if method.__doc__:
  118. render_docstring(method.__doc__).classes('ml-8')
  119. if ancestors:
  120. subheading('Inherited from')
  121. with ui.column().classes('gap-2'):
  122. for ancestor in ancestors:
  123. ui.markdown(f'- `{ancestor.__name__}`')
  124. def generate_method_signature_description(method: Callable) -> str:
  125. param_strings = []
  126. for param in inspect.signature(method).parameters.values():
  127. param_string = param.name
  128. if param_string == 'self':
  129. continue
  130. if param.annotation != inspect.Parameter.empty:
  131. param_type = inspect.formatannotation(param.annotation)
  132. param_string += f''': {param_type.strip("'")}'''
  133. if param.default != inspect.Parameter.empty:
  134. param_string += f' = [...]' if callable(param.default) else f' = {repr(param.default)}'
  135. if param.kind == inspect.Parameter.VAR_POSITIONAL:
  136. param_string = f'*{param_string}'
  137. param_strings.append(param_string)
  138. method_signature = ', '.join(param_strings)
  139. description = f'({method_signature})'
  140. return_annotation = inspect.signature(method).return_annotation
  141. if return_annotation != inspect.Parameter.empty:
  142. return_type = inspect.formatannotation(return_annotation)
  143. description += f''' -> {return_type.strip("'").replace("typing_extensions.", "").replace("typing.", "")}'''
  144. return description
  145. def generate_property_signature_description(property: Optional[property]) -> str:
  146. description = ''
  147. if property is None:
  148. return ': BindableProperty'
  149. if property.fget:
  150. return_annotation = inspect.signature(property.fget).return_annotation
  151. if return_annotation != inspect.Parameter.empty:
  152. return_type = inspect.formatannotation(return_annotation)
  153. description += f': {return_type}'
  154. if property.fset:
  155. description += ' (settable)'
  156. if property.fdel:
  157. description += ' (deletable)'
  158. return description