Browse Source

add some styling for code examples

Falko Schindler 2 năm trước cách đây
mục cha
commit
b9ba3cf05a
3 tập tin đã thay đổi với 99 bổ sung87 xóa
  1. 2 85
      website/api_docs_and_examples.py
  2. 92 0
      website/example.py
  3. 5 2
      website/main.py

+ 2 - 85
website/api_docs_and_examples.py

@@ -1,88 +1,10 @@
-import inspect
-import re
-from typing import Callable, Union
-
-import docutils.core
-
 from nicegui import ui
 from nicegui.auto_context import Context
-from nicegui.elements.markdown import apply_tailwind
-from nicegui.task_logger import create_task
-
-REGEX_H4 = re.compile(r'<h4.*?>(.*?)</h4>')
-SPECIAL_CHARACTERS = re.compile('[^(a-z)(A-Z)(0-9)-]')
-
-
-class example:
-
-    def __init__(self, content: Union[Callable, type, str], tight: bool = False, skip: bool = True) -> None:
-        self.content = content
-        self.markdown_classes = f'mr-8 w-full flex-none lg:w-{48 if tight else 80} xl:w-80'
-        self.rendering_classes = f'w-{48 if tight else 64} flex-none lg:mt-12'
-        self.source_classes = f'w-80 flex-grow overflow-auto lg:mt-12'
-        self.skip = skip
-
-    def __call__(self, f: Callable) -> Callable:
-        if self.skip:
-            return
-        with ui.row().classes('flex w-full'):
-            if isinstance(self.content, str):
-                self._add_html_anchor(ui.markdown(self.content).classes(self.markdown_classes))
-            else:
-                doc = self.content.__doc__ or self.content.__init__.__doc__
-                html: str = docutils.core.publish_parts(doc, writer_name='html')['html_body']
-                html = html.replace('<p>', '<h4>', 1)
-                html = html.replace('</p>', '</h4>', 1)
-                html = apply_tailwind(html)
-                self._add_html_anchor(ui.html(html).classes(self.markdown_classes))
-
-            with ui.card().classes(self.rendering_classes):
-                f()
-
-            code = inspect.getsource(f).splitlines()
-            while not code[0].startswith(' ' * 8):
-                del code[0]
-            code = [l[8:] for l in code]
-            while code[0].startswith('global '):
-                del code[0]
-            code.insert(0, '```python')
-            code.insert(1, 'from nicegui import ui')
-            if code[2].split()[0] not in ['from', 'import']:
-                code.insert(2, '')
-            for l, line in enumerate(code):
-                if line.startswith('# ui.'):
-                    code[l] = line[2:]
-                if line.startswith('# ui.run('):
-                    break
-            else:
-                code.append('')
-                code.append('ui.run()')
-            code.append('```')
-            code = '\n'.join(code)
-            ui.markdown(code).classes(self.source_classes)
-        return f
-
-    def _add_html_anchor(self, element: ui.html) -> None:
-        html = element.content
-        match = REGEX_H4.search(html)
-        if not match:
-            return
-        headline = match.groups()[0].strip()
-        headline_id = SPECIAL_CHARACTERS.sub('_', headline).lower()
-        if not headline_id:
-            return
-
-        icon = '<span class="material-icons">link</span>'
-        anchor = f'<a href="reference#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
-        html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
-        html = html.replace('</h4>', f' {anchor}</h4>', 1)
-        element.content = html
 
+from .example import example
 
-def create_intro() -> None:
-    # add docutils CSS to webpage
-    ui.add_head_html(docutils.core.publish_parts('', writer_name='html')['stylesheet'])
 
+def create_intro() -> None:
     @example('''#### Hello, World!
 
 Creating a user interface with NiceGUI is as simple as writing a single line of code.
@@ -114,11 +36,6 @@ Binding values between UI elements or [to data models](http://127.0.0.1:8080/ref
 
 
 def create_full() -> None:
-    # add docutils CSS to webpage
-    ui.add_head_html(docutils.core.publish_parts('', writer_name='html')['stylesheet'])
-
-    ui.markdown('## API Documentation and Examples')
-
     def h3(text: str) -> None:
         ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
 

+ 92 - 0
website/example.py

@@ -0,0 +1,92 @@
+import inspect
+import re
+from typing import Callable, Union
+
+import docutils.core
+
+from nicegui import ui
+from nicegui.elements.markdown import apply_tailwind
+
+REGEX_H4 = re.compile(r'<h4.*?>(.*?)</h4>')
+SPECIAL_CHARACTERS = re.compile('[^(a-z)(A-Z)(0-9)-]')
+
+
+class example:
+
+    def __init__(self, content: Union[Callable, type, str], tight: bool = False, skip: bool = True) -> None:
+        self.content = content
+        self.markdown_classes = f'mr-8 w-full flex-none lg:w-{48 if tight else 80} xl:w-80'
+        self.rendering_classes = f'w-{48 if tight else 64} flex-none lg:mt-12'
+        self.source_classes = f'w-80 flex-grow overflow-auto lg:mt-12'
+        self.skip = skip
+
+    def __call__(self, f: Callable) -> Callable:
+        if self.skip:
+            return
+        with ui.row().classes('flex w-full'):
+            if isinstance(self.content, str):
+                self._add_html_anchor(ui.markdown(self.content).classes(self.markdown_classes))
+            else:
+                doc = self.content.__doc__ or self.content.__init__.__doc__
+                html: str = docutils.core.publish_parts(doc, writer_name='html')['html_body']
+                html = html.replace('<p>', '<h4>', 1)
+                html = html.replace('</p>', '</h4>', 1)
+                html = apply_tailwind(html)
+                self._add_html_anchor(ui.html(html).classes(self.markdown_classes))
+
+            with ui.card() \
+                    .classes(self.rendering_classes) \
+                    .style('box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1)'):
+                self._add_dots()
+                f()
+
+            code = inspect.getsource(f).splitlines()
+            while not code[0].startswith(' ' * 8):
+                del code[0]
+            code = [l[8:] for l in code]
+            while code[0].startswith('global '):
+                del code[0]
+            code.insert(0, '```python')
+            code.insert(1, 'from nicegui import ui')
+            if code[2].split()[0] not in ['from', 'import']:
+                code.insert(2, '')
+            for l, line in enumerate(code):
+                if line.startswith('# ui.'):
+                    code[l] = line[2:]
+                if line.startswith('# ui.run('):
+                    break
+            else:
+                code.append('')
+                code.append('ui.run()')
+            code.append('```')
+            code = '\n'.join(code)
+            with ui.card() \
+                    .classes(self.source_classes) \
+                    .style('box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); background: #e3eafd'):
+                self._add_dots()
+                ui.markdown(code)
+        return f
+
+    @staticmethod
+    def _add_html_anchor(element: ui.html) -> None:
+        html = element.content
+        match = REGEX_H4.search(html)
+        if not match:
+            return
+        headline = match.groups()[0].strip()
+        headline_id = SPECIAL_CHARACTERS.sub('_', headline).lower()
+        if not headline_id:
+            return
+
+        icon = '<span class="material-icons">link</span>'
+        anchor = f'<a href="reference#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
+        html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
+        html = html.replace('</h4>', f' {anchor}</h4>', 1)
+        element.content = html
+
+    @staticmethod
+    def _add_dots() -> None:
+        with ui.row().classes('gap-1').style('transform: translate(-6px, -6px)'):
+            ui.icon('circle').style('font-size: 75%').classes('text-red-400')
+            ui.icon('circle').style('font-size: 75%').classes('text-yellow-400')
+            ui.icon('circle').style('font-size: 75%').classes('text-green-400')

+ 5 - 2
website/main.py

@@ -1,6 +1,8 @@
 #!/usr/bin/env python3
 from pathlib import Path
 
+import docutils.core
+
 import website.api_docs_and_examples as api_docs_and_examples
 from nicegui import Client, ui
 
@@ -11,7 +13,8 @@ HEADER_HEIGHT = '70px'
 @ui.page('/')
 async def index(client: Client):
     ui.add_head_html('<meta name="viewport" content="width=device-width, initial-scale=1" />')
-    client.content.classes(remove='q-pa-md gap-4')
+    ui.add_head_html(docutils.core.publish_parts('', writer_name='html')['stylesheet'])
+    client.content.classes(remove='q-pa-md gap-4').style('background: #f8f8f8')
 
     with ui.header() \
             .classes('justify-between items-center') \
@@ -40,7 +43,7 @@ async def index(client: Client):
 
     with ui.row() \
             .classes('w-full q-pa-md items-center gap-32 p-32 no-wrap') \
-            .style(f'height: calc(100vh - {HEADER_HEIGHT}); background-color: {ACCENT_COLOR}'):
+            .style(f'height: calc(100vh - {HEADER_HEIGHT}); background: {ACCENT_COLOR}'):
         with ui.column().classes('gap-8'):
             ui.markdown('Create buttons, dialogs, markdown,\n\n3D scenes, plots and much more at ease.') \
                 .style('font-size: 300%; color: white; line-height: 0.9; font-weight: 500')