reference.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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 create_anchor_name, subheading
  7. def generate_class_doc(class_obj: type, part_title: str) -> 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', anchor_name=create_anchor_name(part_title.replace('Reference', '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', anchor_name=create_anchor_name(part_title.replace('Reference', 'Methods')))
  27. with ui.column().classes('gap-2'):
  28. for name, method in sorted(methods.items()):
  29. decorator = ''
  30. if isinstance(class_obj.__dict__.get(name), staticmethod):
  31. decorator += '`@staticmethod`<br />'
  32. if isinstance(class_obj.__dict__.get(name), classmethod):
  33. decorator += '`@classmethod`<br />'
  34. ui.markdown(f'{decorator}**`{name}`**`{_generate_method_signature_description(method)}`')
  35. if method.__doc__:
  36. _render_docstring(method.__doc__).classes('ml-8')
  37. if ancestors:
  38. subheading('Inheritance', anchor_name=create_anchor_name(part_title.replace('Reference', 'Inheritance')))
  39. ui.markdown('\n'.join(f'- `{ancestor.__name__}`' for ancestor in ancestors))
  40. def _is_method_or_property(cls: type, attribute_name: str) -> bool:
  41. attribute = cls.__dict__.get(attribute_name, None)
  42. return (
  43. inspect.isfunction(attribute) or
  44. inspect.ismethod(attribute) or
  45. isinstance(attribute, (
  46. staticmethod,
  47. classmethod,
  48. property,
  49. binding.BindableProperty,
  50. ))
  51. )
  52. def _generate_property_signature_description(property_: Optional[property]) -> str:
  53. description = ''
  54. if property_ is None:
  55. return ': BindableProperty'
  56. if property_.fget:
  57. return_annotation = inspect.signature(property_.fget).return_annotation
  58. if return_annotation != inspect.Parameter.empty:
  59. return_type = inspect.formatannotation(return_annotation)
  60. description += f': {return_type}'
  61. if property_.fset:
  62. description += ' (settable)'
  63. if property_.fdel:
  64. description += ' (deletable)'
  65. return description
  66. def _generate_method_signature_description(method: Callable) -> str:
  67. param_strings = []
  68. for param in inspect.signature(method).parameters.values():
  69. param_string = param.name
  70. if param_string == 'self':
  71. continue
  72. if param.annotation != inspect.Parameter.empty:
  73. param_type = inspect.formatannotation(param.annotation)
  74. param_string += f''': {param_type.strip("'")}'''
  75. if param.default != inspect.Parameter.empty:
  76. param_string += ' = [...]' if callable(param.default) else f' = {repr(param.default)}'
  77. if param.kind == inspect.Parameter.VAR_POSITIONAL:
  78. param_string = f'*{param_string}'
  79. param_strings.append(param_string)
  80. method_signature = ', '.join(param_strings)
  81. description = f'({method_signature})'
  82. return_annotation = inspect.signature(method).return_annotation
  83. if return_annotation != inspect.Parameter.empty:
  84. return_type = inspect.formatannotation(return_annotation)
  85. description += f''' -> {return_type.strip("'").replace("typing_extensions.", "").replace("typing.", "")}'''
  86. return description
  87. def _render_docstring(doc: str) -> ui.restructured_text:
  88. doc = _remove_indentation_from_docstring(doc)
  89. return ui.restructured_text(doc).classes('bold-links arrow-links rst-param-tables')
  90. def _remove_indentation_from_docstring(text: str) -> str:
  91. lines = text.splitlines()
  92. if not lines:
  93. return ''
  94. if len(lines) == 1:
  95. return lines[0]
  96. indentation = min(len(line) - len(line.lstrip()) for line in lines[1:] if line.strip())
  97. return lines[0] + '\n' + '\n'.join(line[indentation:] for line in lines[1:])