reference.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import inspect
  2. import re
  3. from typing import Callable, Optional
  4. import docutils.core
  5. from nicegui import binding, ui
  6. from ..style import subheading
  7. def generate_class_doc(class_obj: type) -> None:
  8. """Generate documentation for a class including all its methods and properties."""
  9. mro = [base for base in class_obj.__mro__ if base.__module__.startswith('nicegui.')]
  10. ancestors = mro[1:]
  11. attributes = {}
  12. for base in reversed(mro):
  13. for name in dir(base):
  14. if not name.startswith('_') and _is_method_or_property(base, name):
  15. attributes[name] = getattr(base, name, None)
  16. properties = {name: attribute for name, attribute in attributes.items() if not callable(attribute)}
  17. methods = {name: attribute for name, attribute in attributes.items() if callable(attribute)}
  18. if properties:
  19. subheading('Properties')
  20. with ui.column().classes('gap-2'):
  21. for name, property_ in sorted(properties.items()):
  22. ui.markdown(f'**`{name}`**`{_generate_property_signature_description(property_)}`')
  23. if property_.__doc__:
  24. _render_docstring(property_.__doc__).classes('ml-8')
  25. if methods:
  26. subheading('Methods')
  27. with ui.column().classes('gap-2'):
  28. for name, method in sorted(methods.items()):
  29. ui.markdown(f'**`{name}`**`{_generate_method_signature_description(method)}`')
  30. if method.__doc__:
  31. _render_docstring(method.__doc__).classes('ml-8')
  32. if ancestors:
  33. subheading('Inherited from')
  34. ui.markdown('\n'.join(f'- `{ancestor.__name__}`' for ancestor in ancestors))
  35. def _is_method_or_property(cls: type, attribute_name: str) -> bool:
  36. attribute = cls.__dict__.get(attribute_name, None)
  37. return (
  38. inspect.isfunction(attribute) or
  39. inspect.ismethod(attribute) or
  40. isinstance(attribute, (
  41. staticmethod,
  42. classmethod,
  43. property,
  44. binding.BindableProperty,
  45. ))
  46. )
  47. def _generate_property_signature_description(property_: Optional[property]) -> str:
  48. description = ''
  49. if property_ is None:
  50. return ': BindableProperty'
  51. if property_.fget:
  52. return_annotation = inspect.signature(property_.fget).return_annotation
  53. if return_annotation != inspect.Parameter.empty:
  54. return_type = inspect.formatannotation(return_annotation)
  55. description += f': {return_type}'
  56. if property_.fset:
  57. description += ' (settable)'
  58. if property_.fdel:
  59. description += ' (deletable)'
  60. return description
  61. def _generate_method_signature_description(method: Callable) -> str:
  62. param_strings = []
  63. for param in inspect.signature(method).parameters.values():
  64. param_string = param.name
  65. if param_string == 'self':
  66. continue
  67. if param.annotation != inspect.Parameter.empty:
  68. param_type = inspect.formatannotation(param.annotation)
  69. param_string += f''': {param_type.strip("'")}'''
  70. if param.default != inspect.Parameter.empty:
  71. param_string += ' = [...]' if callable(param.default) else f' = {repr(param.default)}'
  72. if param.kind == inspect.Parameter.VAR_POSITIONAL:
  73. param_string = f'*{param_string}'
  74. param_strings.append(param_string)
  75. method_signature = ', '.join(param_strings)
  76. description = f'({method_signature})'
  77. return_annotation = inspect.signature(method).return_annotation
  78. if return_annotation != inspect.Parameter.empty:
  79. return_type = inspect.formatannotation(return_annotation)
  80. description += f''' -> {return_type.strip("'").replace("typing_extensions.", "").replace("typing.", "")}'''
  81. return description
  82. def _render_docstring(doc: str, with_params: bool = True) -> ui.html:
  83. doc = _remove_indentation_from_docstring(doc)
  84. doc = doc.replace('param ', '')
  85. html = docutils.core.publish_parts(doc, writer_name='html5_polyglot')['html_body']
  86. if not with_params:
  87. html = re.sub(r'<dl class=".* simple">.*?</dl>', '', html, flags=re.DOTALL)
  88. return ui.html(html).classes('bold-links arrow-links nicegui-markdown')
  89. def _remove_indentation_from_docstring(text: str) -> str:
  90. lines = text.splitlines()
  91. if not lines:
  92. return ''
  93. if len(lines) == 1:
  94. return lines[0]
  95. indentation = min(len(line) - len(line.lstrip()) for line in lines[1:] if line.strip())
  96. return lines[0] + '\n'.join(line[indentation:] for line in lines[1:])