1
0

reference.py 4.8 KB

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