Преглед изворни кода

Merge pull request #2561 from ZeroCool940711/add_ui_rst

Add reStructuredText (ui.rst) element and documentation.
Rodja Trappe пре 1 година
родитељ
комит
fdab7b8088

+ 35 - 0
nicegui/elements/restructured_text.py

@@ -0,0 +1,35 @@
+import os
+from functools import lru_cache
+
+from docutils.core import publish_parts
+
+from .markdown import Markdown, remove_indentation
+
+
+class ReStructuredText(Markdown):
+
+    def __init__(self, content: str = '') -> None:
+        """ReStructuredText
+
+        Renders ReStructuredText onto the page.
+
+        :param content: the ReStructuredText content to be displayed
+        """
+        super().__init__(content=content)
+
+    def _handle_content_change(self, content: str) -> None:
+        html = prepare_content(content)
+        if self._props.get('innerHTML') != html:
+            self._props['innerHTML'] = html
+            self.run_method('update', html)
+
+
+@lru_cache(maxsize=int(os.environ.get('RST_CONTENT_CACHE_SIZE', '1000')))
+def prepare_content(content: str) -> str:
+    """Render ReStructuredText content to HTML."""
+    html = publish_parts(
+        remove_indentation(content),
+        writer_name='html4',
+        settings_overrides={'syntax_highlight': 'short'},
+    )
+    return html["html_body"].replace('<div class="document"', '<div class="codehilite"')

+ 2 - 0
nicegui/ui.py

@@ -59,6 +59,7 @@ __all__ = [
     'pyplot',
     'query',
     'radio',
+    'restructured_text',
     'row',
     'scene',
     'scroll_area',
@@ -170,6 +171,7 @@ from .elements.progress import LinearProgress as linear_progress
 from .elements.pyplot import Pyplot as pyplot
 from .elements.query import Query as query
 from .elements.radio import Radio as radio
+from .elements.restructured_text import ReStructuredText as restructured_text
 from .elements.row import Row as row
 from .elements.scene import Scene as scene
 from .elements.scroll_area import ScrollArea as scroll_area

+ 16 - 0
tests/test_restructured_text.py

@@ -0,0 +1,16 @@
+from nicegui import ui
+from nicegui.testing import Screen
+
+
+def test_restructured_text(screen: Screen):
+    rst = ui.restructured_text('This is **reStructuredText**')
+
+    screen.open('/')
+    element = screen.find('This is')
+    assert element.text == 'This is reStructuredText'
+    assert element.get_attribute('innerHTML') == 'This is <strong>reStructuredText</strong>'
+
+    rst.set_content('New **content**')
+    element = screen.find('New')
+    assert element.text == 'New content'
+    assert element.get_attribute('innerHTML') == 'New <strong>content</strong>'

+ 1 - 1
website/documentation/content/overview.py

@@ -76,7 +76,7 @@ doc.text('Customization', '''
 
 tiles = [
     (section_text_elements, '''
-        Elements like `ui.label`, `ui.markdown` and `ui.html` can be used to display text and other content.
+        Elements like `ui.label`, `ui.markdown`, `ui.restructured_text` and `ui.html` can be used to display text and other content.
     '''),
     (section_controls, '''
         NiceGUI provides a variety of elements for user interaction, e.g. `ui.button`, `ui.slider`, `ui.inputs`, etc.

+ 68 - 0
website/documentation/content/restructured_text_documentation.py

@@ -0,0 +1,68 @@
+from nicegui import ui
+
+from . import doc
+
+
+@doc.demo(ui.restructured_text)
+def main_demo() -> None:
+    ui.restructured_text('This is **reStructuredText**.')
+
+
+@doc.demo('reStructuredText with indentation', '''
+    You can indent reStructuredText elements to create a hierarchy.
+    Common indentation is automatically stripped from the beginning of each line to preserve the relative indentation,
+    so you can indent multiline strings.
+''')
+def rst_with_indentation():
+    ui.restructured_text('''
+        This is an example of a reStructuredText paragraph with several indentation levels.
+
+        You can use multiple levels of indentation to structure your content.
+        Each level of indentation represents a different level of hierarchy.
+
+        - Level 1
+            - Level 2
+                - Level 3
+                    - Level 4
+                        - Level 5
+    ''')
+
+
+@doc.demo('reStructuredText with code blocks', '''
+    You can use code blocks to show code examples.
+    If you specify the language, the code will be syntax-highlighted.
+    See [this link](https://docs.typo3.org/m/typo3/docs-how-to-document/main/en-us/WritingReST/Reference/Code/Codeblocks.html#writing-rest-codeblocks-available-lexers) for a list of supported languages.
+''')
+def rst_with_code_blocks():
+    ui.restructured_text('''
+        .. code-block:: python3
+        
+            from nicegui import ui
+
+            ui.label('Hello World!')
+
+            ui.run()
+    ''')
+
+
+@doc.demo('reStructuredText with tables', '''
+    See the [sphinx documentation](https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html#tables)
+    for more information about reStructuredText tables.
+''')
+def rst_tables():
+    ui.restructured_text('''
+        +-------+-------+---------+--------+
+        | A     | B     | A and B | A or B |
+        +=======+=======+=========+========+
+        | False | False | False   | False  |
+        +-------+-------+---------+--------+
+        | True  | False | False   | True   |
+        +-------+-------+---------+--------+
+        | False | True  | False   | True   |
+        +-------+-------+---------+--------+
+        | True  | True  | True    | True   |
+        +-------+-------+---------+--------+
+    ''')
+
+
+doc.reference(ui.restructured_text)

+ 1 - 0
website/documentation/content/section_configuration_deployment.py

@@ -68,6 +68,7 @@ doc.text('', '''
         This will make `ui.pyplot` and `ui.line_plot` unavailable.
     - `NICEGUI_STORAGE_PATH` (default: local ".nicegui") can be set to change the location of the storage files.
     - `MARKDOWN_CONTENT_CACHE_SIZE` (default: 1000): The maximum number of Markdown content snippets that are cached in memory.
+    - `RST_CONTENT_CACHE_SIZE` (default: 1000): The maximum number of ReStructuredText content snippets that are cached in memory.
 ''')
 def env_var_demo():
     from nicegui.elements import markdown

+ 2 - 1
website/documentation/content/section_text_elements.py

@@ -1,5 +1,5 @@
 from . import (chat_message_documentation, doc, element_documentation, html_documentation, label_documentation,
-               link_documentation, markdown_documentation, mermaid_documentation)
+               link_documentation, markdown_documentation, mermaid_documentation, restructured_text_documentation)
 
 doc.title('*Text* Elements')
 
@@ -8,5 +8,6 @@ doc.intro(link_documentation)
 doc.intro(chat_message_documentation)
 doc.intro(element_documentation)
 doc.intro(markdown_documentation)
+doc.intro(restructured_text_documentation)
 doc.intro(mermaid_documentation)
 doc.intro(html_documentation)