Explorar o código

#612 add syntax highlighting for code blocks in ui.markdown

Falko Schindler %!s(int64=2) %!d(string=hai) anos
pai
achega
6d67e9c972

+ 0 - 2
main.py

@@ -13,7 +13,6 @@ from pathlib import Path
 
 from fastapi import Request
 from fastapi.responses import FileResponse, RedirectResponse
-from pygments.formatters import HtmlFormatter
 from starlette.middleware.sessions import SessionMiddleware
 
 import prometheus
@@ -59,7 +58,6 @@ if fly_instance_id:
 
 def add_head_html() -> None:
     ui.add_head_html((Path(__file__).parent / 'website' / 'static' / 'header.html').read_text())
-    ui.add_head_html(f'<style>{HtmlFormatter(nobackground=True).get_style_defs(".codehilite")}</style>')
     ui.add_head_html(f"<style>{(Path(__file__).parent / 'website' / 'static' / 'style.css').read_text()}</style>")
 
 

+ 13 - 0
nicegui/elements/markdown.js

@@ -1,6 +1,7 @@
 export default {
   template: `<div></div>`,
   mounted() {
+    this.ensure_codehilite_css();
     this.update(this.$el.innerHTML);
   },
   methods: {
@@ -11,6 +12,18 @@ export default {
         mermaid.render(`mermaid_${this.$el.id}_${i}`, code, (svg) => (pre.innerHTML = svg));
       });
     },
+    ensure_codehilite_css() {
+      if (!document.querySelector(`style[data-codehilite-css]`)) {
+        const style = document.createElement("style");
+        style.setAttribute("data-codehilite-css", "");
+        style.innerHTML = this.codehilite_css;
+        console.log(style);
+        document.head.appendChild(style);
+      }
+    },
+  },
+  props: {
+    codehilite_css: String,
   },
 };
 

+ 2 - 0
nicegui/elements/markdown.py

@@ -4,6 +4,7 @@ from functools import lru_cache
 from typing import List
 
 import markdown2
+from pygments.formatters import HtmlFormatter
 
 from ..dependencies import register_component
 from .mixins.content_element import ContentElement
@@ -23,6 +24,7 @@ class Markdown(ContentElement):
         """
         self.extras = extras
         super().__init__(tag='markdown', content=content)
+        self._props['codehilite_css'] = HtmlFormatter(nobackground=True).get_style_defs('.codehilite')
 
     def on_content_change(self, content: str) -> None:
         html = prepare_content(content, extras=' '.join(self.extras))

+ 1 - 1
website/demo.py

@@ -42,7 +42,7 @@ class demo:
                 async def copy_code():
                     await ui.run_javascript('navigator.clipboard.writeText(`' + code + '`)', respond=False)
                     ui.notify('Copied to clipboard', type='positive', color='primary')
-                ui.markdown(f'```python\n{code}\n```')
+                ui.markdown(f'````python\n{code}\n````')
                 ui.icon('content_copy', size='xs') \
                     .classes('absolute right-2 top-10 opacity-10 hover:opacity-80 cursor-pointer') \
                     .on('click', copy_code)

+ 1 - 1
website/documentation_tools.py

@@ -72,7 +72,7 @@ class text_demo:
 
     def __call__(self, f: Callable) -> Callable:
         subheading(self.title, make_menu_entry=self.make_menu_entry)
-        ui.markdown(self.explanation)
+        ui.markdown(self.explanation).classes('bold-links arrow-links')
         return demo()(f)
 
 

+ 16 - 0
website/more_documentation/markdown_documentation.py

@@ -23,3 +23,19 @@ def more() -> None:
             
             This is normal text again.
         ''')
+
+    @text_demo('Markdown with code blocks', '''
+        You can use code blocks to show code examples.
+        If you specify the language after the opening triple backticks, the code will be syntax highlighted.
+        See [the Pygments website](https://pygments.org/languages/) for a list of supported languages.
+    ''')
+    def markdown_with_code_blocks():
+        ui.markdown('''
+            ```python
+            from nicegui import ui
+
+            ui.label('Hello World!')
+
+            ui.run(dark=True)
+            ```
+        ''')