api.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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. from nicegui import app as nicegui_app
  10. from nicegui import ui as nicegui_ui
  11. from nicegui.elements.markdown import remove_indentation
  12. from .page import DocumentationPage
  13. from .part import Demo, DocumentationPart
  14. registry: Dict[str, DocumentationPage] = {}
  15. def get_page(documentation: ModuleType) -> DocumentationPage:
  16. """Return the documentation page for the given documentation module."""
  17. target_name = _removesuffix(documentation.__name__.split('.')[-1], '_documentation')
  18. assert target_name in registry, f'Documentation page {target_name} does not exist'
  19. return registry[target_name]
  20. def _get_current_page() -> DocumentationPage:
  21. frame = sys._getframe(2) # pylint: disable=protected-access
  22. module = inspect.getmodule(frame)
  23. assert module is not None and module.__file__ is not None
  24. name = _removesuffix(Path(module.__file__).stem, '_documentation')
  25. if name == 'overview':
  26. name = ''
  27. if name not in registry:
  28. registry[name] = DocumentationPage(name=name)
  29. return registry[name]
  30. def title(title_: Optional[str] = None, subtitle: Optional[str] = None) -> None:
  31. """Set the title of the current documentation page."""
  32. page = _get_current_page()
  33. page.title = title_
  34. page.subtitle = subtitle
  35. def text(title_: str, description: str) -> None:
  36. """Add a text block to the current documentation page."""
  37. _get_current_page().parts.append(DocumentationPart(title=title_, description=description))
  38. @overload
  39. def demo(title_: str,
  40. description: str, /, *,
  41. tab: Optional[Union[str, Callable]] = None,
  42. lazy: bool = True,
  43. ) -> Callable[[Callable], Callable]:
  44. ...
  45. @overload
  46. def demo(element: type, /,
  47. tab: Optional[Union[str, Callable]] = None,
  48. lazy: bool = True,
  49. ) -> Callable[[Callable], Callable]:
  50. ...
  51. @overload
  52. def demo(function: Callable, /,
  53. tab: Optional[Union[str, Callable]] = None,
  54. lazy: bool = True,
  55. ) -> Callable[[Callable], Callable]:
  56. ...
  57. def demo(*args, **kwargs) -> Callable[[Callable], Callable]:
  58. """Add a demo section to the current documentation page."""
  59. if len(args) == 2:
  60. element = None
  61. title_, description = args
  62. is_markdown = True
  63. else:
  64. element = args[0]
  65. doc = element.__init__.__doc__ if isinstance(element, type) else element.__doc__ # type: ignore
  66. title_, description = doc.split('\n', 1)
  67. is_markdown = False
  68. description = remove_indentation(description)
  69. page = _get_current_page()
  70. def decorator(function: Callable) -> Callable:
  71. if not page.parts and element:
  72. ui_name = _find_attribute(nicegui_ui, element.__name__)
  73. app_name = _find_attribute(nicegui_app, element.__name__)
  74. if ui_name:
  75. page.title = f'ui.*{ui_name}*'
  76. if app_name:
  77. page.title = f'app.*{app_name}*'
  78. page.parts.append(DocumentationPart(
  79. title=title_,
  80. description=description,
  81. description_format='md' if is_markdown else 'rst',
  82. demo=Demo(function=function, lazy=kwargs.get('lazy', True), tab=kwargs.get('tab')),
  83. ))
  84. return function
  85. return decorator
  86. def ui(function: Callable) -> Callable:
  87. """Add arbitrary UI to the current documentation page."""
  88. _get_current_page().parts.append(DocumentationPart(ui=function))
  89. return function
  90. def intro(documentation: types.ModuleType) -> None:
  91. """Add an intro section to the current documentation page."""
  92. current_page = _get_current_page()
  93. target_page = get_page(documentation)
  94. target_page.back_link = current_page.name
  95. part = deepcopy(target_page.parts[0])
  96. part.link = target_page.name
  97. current_page.parts.append(part)
  98. def reference(element: type, *,
  99. title: str = 'Reference', # pylint: disable=redefined-outer-name
  100. ) -> None:
  101. """Add a reference section to the current documentation page."""
  102. _get_current_page().parts.append(DocumentationPart(title=title, reference=element))
  103. def _find_attribute(obj: Any, name: str) -> Optional[str]:
  104. for attr in dir(obj):
  105. if attr.lower().replace('_', '') == name.lower().replace('_', ''):
  106. return attr
  107. return None
  108. def _removesuffix(string: str, suffix: str) -> str:
  109. # NOTE: Remove this once we drop Python 3.8 support
  110. if string.endswith(suffix):
  111. return string[:-len(suffix)]
  112. return string