Explorar o código

tailwind styling in markdown element

Rodja Trappe %!s(int64=4) %!d(string=hai) anos
pai
achega
2a7dbad36d
Modificáronse 3 ficheiros con 21 adicións e 4 borrados
  1. 4 0
      main.py
  2. 17 0
      nicegui/elements/markdown.py
  3. 0 4
      nicegui/nicegui.py

+ 4 - 0
main.py

@@ -3,9 +3,12 @@
 from nicegui import ui, wp
 from contextlib import contextmanager
 import inspect
+from nicegui.elements.markdown import Markdown
 from nicegui.elements.element import Element
 import sys
 import docutils.core
+import icecream
+icecream.install()
 
 # add docutils css to webpage
 wp.head_html += docutils.core.publish_parts('', writer_name='html')['stylesheet']
@@ -22,6 +25,7 @@ def example(element: Element):
             html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
             html = html.replace('<p>', '<h3>', 1)
             html = html.replace('</p>', '</h3>', 1)
+            html = Markdown.apply_tailwind(html)
             ui.html(html, classes='mr-8 w-4/12')
         else:
             ui.label(element.__name__, 'h5')

+ 17 - 0
nicegui/elements/markdown.py

@@ -1,5 +1,6 @@
 import markdown2
 from .html import Html
+import re
 
 class Markdown(Html):
 
@@ -10,4 +11,20 @@ class Markdown(Html):
     def set_content(self, content: str):
 
         html = markdown2.markdown(content, extras=['fenced-code-blocks'])
+        # we need explicit markdown styling because tailwind css removes all default styles
+        html = Markdown.apply_tailwind(html)
         super().set_content(html)
+
+    @staticmethod
+    def apply_tailwind(html: str):
+
+        rep = {
+            '<h1>': '<h1 class="text-5xl mb-4 mt-6">',
+            '<h2>': '<h2 class="text-4xl mb-3 mt-5">',
+            '<h3>': '<h3 class="text-3xl mb-2 mt-4">',
+            '<h4>': '<h4 class="text-2xl mb-1 mt-3">',
+            '<h5>': '<h5 class="text-1xl mb-0.5 mt-2">',
+        }
+        p = dict((re.escape(k), v) for k, v in rep.items())
+        pattern = re.compile("|".join(rep.keys()))
+        return pattern.sub(lambda m: rep[re.escape(m.group(0))], html)

+ 0 - 4
nicegui/nicegui.py

@@ -23,10 +23,6 @@ wp.css = HtmlFormatter().get_style_defs('.codehilite')
 wp.head_html = '<script>confirm = () => true;</script>'  # avoid confirmation dialog for reload
 wp.head_html += '<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">'  # using latest tailwind
 
-markdown_styling = ''.join(
-    [f'h{i} {{ font-size: {80*(5-i)}%; line-height: normal; margin-block-start:1em; margin-block-end: {0.1*(5-1)}em }}' for i in range(1, 5)])
-wp.head_html += '<style>' + markdown_styling + '</style>'
-
 main = jp.Div(a=wp, classes='q-ma-md column items-start', style='row-gap: 1em')
 main.add_page(wp)
 jp.justpy(lambda: wp, start_server=False)