Sfoglia il codice sorgente

#439 refactor intro examples

Falko Schindler 2 anni fa
parent
commit
a63a72d05a
2 ha cambiato i file con 71 aggiunte e 52 eliminazioni
  1. 40 39
      website/example.py
  2. 31 13
      website/reference.py

+ 40 - 39
website/example.py

@@ -53,7 +53,7 @@ class example:
 
     def __init__(self,
                  content: Union[Callable, type, str],
-                 menu: Optional[ui.drawer],
+                 menu: Optional[ui.drawer] = None,
                  browser_title: Optional[str] = None,
                  immediate: bool = False) -> None:
         self.content = content
@@ -62,44 +62,45 @@ class example:
         self.immediate = immediate
 
     def __call__(self, f: Callable) -> Callable:
-        with ui.column().classes('w-full mb-8'):
-            if isinstance(self.content, str):
-                html = prepare_content(self.content, 'fenced-code-blocks tables')
-            else:
-                doc = self.content.__doc__ or self.content.__init__.__doc__
-                html: str = docutils.core.publish_parts(doc, writer_name='html5_polyglot')['html_body']
-                html = html.replace('<p>', '<h4>', 1)
-                html = html.replace('</p>', '</h4>', 1)
-                html = html.replace('param ', '')
-                html = apply_tailwind(html)
-            add_html_with_anchor_link(html, self.menu)
-
-            with ui.column().classes('w-full items-stretch gap-8 no-wrap min-[1500px]:flex-row'):
-                code = inspect.getsource(f).split('# END OF EXAMPLE')[0].strip().splitlines()
-                while not code[0].startswith(' ' * 8):
-                    del code[0]
-                code = ['from nicegui import ui'] + [remove_prefix(line[8:], '# ') for line in code]
-                code = ['' if line == '#' else line for line in code]
-                if not code[-1].startswith('ui.run('):
-                    code.append('')
-                    code.append('ui.run()')
-                code = isort.code('\n'.join(code), no_sections=True, lines_after_imports=1)
-                with python_window(classes='w-full max-w-[44rem]'):
-                    ui.markdown(f'```python\n{code}\n```')
-                with browser_window(self.browser_title,
-                                    classes='w-full max-w-[44rem] min-[1500px]:max-w-[20rem] min-h-[10rem] browser-window'):
-                    if self.immediate:
-                        f()
-                    else:
-                        intersection_observer(on_intersection=f)
-
-            def pascal_to_snake(name: str) -> str:
-                return re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower()
-            if isinstance(self.content, type) and self.menu:
-                name = pascal_to_snake(self.content.__name__)
-                path = Path(__file__).parent / 'more_reference' / f'{name}_reference.py'
-                if path.exists():
-                    ui.markdown(f'[More...](reference/{name})').classes('bold-links')
+        # with ui.column().classes('w-full mb-8'):
+        # if isinstance(self.content, str):
+        #     html = prepare_content(self.content, 'fenced-code-blocks tables')
+        # else:
+        #     doc = self.content.__doc__ or self.content.__init__.__doc__
+        #     html: str = docutils.core.publish_parts(doc, writer_name='html5_polyglot')['html_body']
+        #     html = html.replace('<p>', '<h4>', 1)
+        #     html = html.replace('</p>', '</h4>', 1)
+        #     html = html.replace('param ', '')
+        #     html = apply_tailwind(html)
+        # add_html_with_anchor_link(html, self.menu)
+
+        with ui.column().classes('w-full items-stretch gap-8 no-wrap min-[1500px]:flex-row'):
+            code = inspect.getsource(f).split('# END OF EXAMPLE')[0].strip().splitlines()
+            while not code[0].strip().startswith('def'):
+                del code[0]
+            del code[0]
+            code = ['from nicegui import ui'] + [remove_prefix(line[8:], '# ') for line in code]
+            code = ['' if line == '#' else line for line in code]
+            if not code[-1].startswith('ui.run('):
+                code.append('')
+                code.append('ui.run()')
+            code = isort.code('\n'.join(code), no_sections=True, lines_after_imports=1)
+            with python_window(classes='w-full max-w-[44rem]'):
+                ui.markdown(f'```python\n{code}\n```')
+            with browser_window(self.browser_title,
+                                classes='w-full max-w-[44rem] min-[1500px]:max-w-[20rem] min-h-[10rem] browser-window'):
+                if self.immediate:
+                    f()
+                else:
+                    intersection_observer(on_intersection=f)
+
+        # def pascal_to_snake(name: str) -> str:
+        #     return re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower()
+        # if isinstance(self.content, type) and self.menu:
+        #     name = pascal_to_snake(self.content.__name__)
+        #     path = Path(__file__).parent / 'more_reference' / f'{name}_reference.py'
+        #     if path.exists():
+        #         ui.markdown(f'[More...](reference/{name})').classes('bold-links')
 
         return f
 

+ 31 - 13
website/reference.py

@@ -1,5 +1,6 @@
+import re
 import uuid
-from typing import Dict
+from typing import Callable, Dict
 
 from nicegui import app, ui
 from nicegui.elements.markdown import prepare_content
@@ -9,12 +10,33 @@ from .example import add_html_with_anchor_link, bash_window, example, python_win
 
 CONSTANT_UUID = str(uuid.uuid4())
 
+SPECIAL_CHARACTERS = re.compile('[^(a-z)(A-Z)(0-9)-]')
 
-def create_intro() -> None:
-    @example('''#### Styling
 
-While having reasonable defaults, you can still modify the look of your app with CSS as well as Tailwind and Quasar classes.
-''', None)
+def heading(text: str) -> None:
+    name = SPECIAL_CHARACTERS.sub('_', text).lower()
+    target = ui.link_target(name).style('position: relative; top: -90px')
+    with ui.row().classes('gap-2 items-center'):
+        ui.label(text).classes('text-2xl')
+        with ui.link(target=f'#{target.id}'):
+            ui.icon('link', size='sm').classes('text-gray-400 hover:text-gray-800')
+
+
+class intro_example:
+
+    def __init__(self, title: str, explanation: str) -> None:
+        self.title = title
+        self.explanation = explanation
+
+    def __call__(self, f: Callable) -> Callable:
+        heading(self.title)
+        ui.label(self.explanation)
+        return example(None, None)(f)
+
+
+def create_intro() -> None:
+    @intro_example('Styling',
+                   'While having reasonable defaults, you can still modify the look of your app with CSS as well as Tailwind and Quasar classes.')
     def formatting_example():
         ui.icon('thumb_up')
         ui.markdown('This is **Markdown**.')
@@ -25,10 +47,8 @@ While having reasonable defaults, you can still modify the look of your app with
             ui.label('Quasar').classes('q-ml-xl')
         ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
 
-    @example('''#### Common UI Elements
-
-NiceGUI comes with a collection of commonly used UI elements.
-''', None)
+    @intro_example('Common UI Elements',
+                   'NiceGUI comes with a collection of commonly used UI elements.')
     def common_elements_example():
         from nicegui.events import ValueChangeEventArguments
 
@@ -46,10 +66,8 @@ NiceGUI comes with a collection of commonly used UI elements.
             ui.select(['One', 'Two'], value='One', on_change=show)
         ui.link('And many more...', '/reference').classes('mt-8')
 
-    @example('''#### Value Binding
-
-Binding values between UI elements and data models is built into NiceGUI.
-''', None)
+    @intro_example('Value Binding',
+                   'Binding values between UI elements and data models is built into NiceGUI.')
     def binding_example():
         class Demo:
             def __init__(self):