reference.py 5.3 KB

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