api.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. from __future__ import annotations
  2. import inspect
  3. import sys
  4. import types
  5. from copy import deepcopy
  6. from pathlib import Path
  7. from types import ModuleType
  8. from typing import Any, Callable, Dict, Optional, Union, overload
  9. import nicegui
  10. from nicegui import app as nicegui_app
  11. from nicegui import ui as nicegui_ui
  12. from nicegui.elements.markdown import remove_indentation
  13. from .page import DocumentationPage
  14. from .part import Demo, DocumentationPart
  15. registry: Dict[str, DocumentationPage] = {}
  16. redirects: Dict[str, str] = {}
  17. def get_page(documentation: ModuleType) -> DocumentationPage:
  18. """Return the documentation page for the given documentation module."""
  19. target_name = _removesuffix(documentation.__name__.split('.')[-1], '_documentation')
  20. assert target_name in registry, f'Documentation page {target_name} does not exist'
  21. return registry[target_name]
  22. def _get_current_page() -> DocumentationPage:
  23. frame = sys._getframe(2) # pylint: disable=protected-access
  24. module = inspect.getmodule(frame)
  25. assert module is not None and module.__file__ is not None
  26. name = _removesuffix(Path(module.__file__).stem, '_documentation')
  27. if name == 'overview':
  28. name = ''
  29. if name not in registry:
  30. registry[name] = DocumentationPage(name=name)
  31. return registry[name]
  32. def title(title_: Optional[str] = None, subtitle: Optional[str] = None) -> None:
  33. """Set the title of the current documentation page."""
  34. page = _get_current_page()
  35. page.title = title_
  36. page.subtitle = subtitle
  37. def text(title_: str, description: str) -> None:
  38. """Add a text block to the current documentation page."""
  39. _get_current_page().parts.append(DocumentationPart(title=title_, description=description))
  40. @overload
  41. def demo(title_: str,
  42. description: str, /, *,
  43. tab: Optional[Union[str, Callable]] = None,
  44. lazy: bool = True,
  45. ) -> Callable[[Callable], Callable]:
  46. ...
  47. @overload
  48. def demo(element: type, /,
  49. tab: Optional[Union[str, Callable]] = None,
  50. lazy: bool = True,
  51. ) -> Callable[[Callable], Callable]:
  52. ...
  53. @overload
  54. def demo(function: Callable, /,
  55. tab: Optional[Union[str, Callable]] = None,
  56. lazy: bool = True,
  57. ) -> Callable[[Callable], Callable]:
  58. ...
  59. def demo(*args, **kwargs) -> Callable[[Callable], Callable]:
  60. """Add a demo section to the current documentation page."""
  61. if len(args) == 2:
  62. element = None
  63. title_, description = args
  64. is_markdown = True
  65. else:
  66. element = args[0]
  67. doc = element.__doc__
  68. if isinstance(element, type) and not doc:
  69. doc = element.__init__.__doc__ # type: ignore
  70. title_, description = doc.split('\n', 1)
  71. title_ = title_.rstrip('.')
  72. is_markdown = False
  73. description = remove_indentation(description)
  74. page = _get_current_page()
  75. def decorator(function: Callable) -> Callable:
  76. if not page.parts and element:
  77. name = getattr(element, '__name__', None) or element.__class__.__name__
  78. ui_name = _find_attribute(nicegui_ui, name)
  79. app_name = _find_attribute(nicegui_app, name)
  80. if ui_name:
  81. page.title = f'ui.*{ui_name}*'
  82. elif app_name:
  83. page.title = f'app.*{app_name}*'
  84. page.parts.append(DocumentationPart(
  85. title=title_,
  86. description=description,
  87. description_format='md' if is_markdown else 'rst',
  88. demo=Demo(function=function, lazy=kwargs.get('lazy', True), tab=kwargs.get('tab')),
  89. ))
  90. return function
  91. return decorator
  92. def part(title_: str) -> Callable:
  93. """Add a custom part with arbitrary UI and descriptive markdown elements to the current documentation page.
  94. The content of any contained markdown elements will be used for search indexing.
  95. """
  96. page = _get_current_page()
  97. def decorator(function: Callable) -> Callable:
  98. with nicegui_ui.element() as container:
  99. function()
  100. elements = nicegui.ElementFilter(kind=nicegui.ui.markdown, local_scope=True)
  101. description = ''.join(e.content for e in elements if '```' not in e.content)
  102. container.delete()
  103. page.parts.append(DocumentationPart(title=title_, search_text=description, ui=function))
  104. return function
  105. return decorator
  106. def ui(function: Callable) -> Callable:
  107. """Add arbitrary UI to the current documentation page."""
  108. _get_current_page().parts.append(DocumentationPart(ui=function))
  109. return function
  110. def intro(documentation: types.ModuleType) -> None:
  111. """Add an intro section to the current documentation page."""
  112. current_page = _get_current_page()
  113. target_page = get_page(documentation)
  114. target_page.back_link = current_page.name
  115. part = deepcopy(target_page.parts[0])
  116. part.link = target_page.name
  117. current_page.parts.append(part)
  118. def reference(element: type, *,
  119. title: str = 'Reference', # pylint: disable=redefined-outer-name
  120. ) -> None:
  121. """Add a reference section to the current documentation page."""
  122. _get_current_page().parts.append(DocumentationPart(title=title, reference=element))
  123. def extra_column(function: Callable) -> Callable:
  124. """Add an extra column to the current documentation page."""
  125. _get_current_page().extra_column = function
  126. return function
  127. def _find_attribute(obj: Any, name: str) -> Optional[str]:
  128. for attr in dir(obj):
  129. if attr.lower().replace('_', '') == name.lower().replace('_', ''):
  130. return attr
  131. return None
  132. def _removesuffix(string: str, suffix: str) -> str:
  133. # NOTE: Remove this once we drop Python 3.8 support
  134. if string.endswith(suffix):
  135. return string[:-len(suffix)]
  136. return string