Skip to content

Commit

Permalink
Added: github-style admonition support (#295)
Browse files Browse the repository at this point in the history
  • Loading branch information
signebedi committed Jun 26, 2024
1 parent da9c9ba commit defc0a7
Show file tree
Hide file tree
Showing 4 changed files with 137 additions and 8 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ pip install libreforms_fastapi[data]
If you plan to use Postgres or MariaDB, then there are additional extras tags for those, too.

```bash
pip install libreforms_fastapi[postres] # for Postgres
pip install libreforms_fastapi[postgres] # for Postgres
pip install libreforms_fastapi[mariadb] # for MariaDB
```

Expand All @@ -51,7 +51,7 @@ libreformsctl nginx production # Optional if you want a reverse proxy

#### Troubleshooting Errors

You may sometimes run into inexplicable runtime errors. These often result from permission issues on the filesystem. When in doubt, try running the following command as root.
You may sometimes run into inexplicable runtime errors. These often result from permission issues on the filesystem. When in doubt, try running the following command as root on your project root directory (below, we've selected `/opt/libreforms_fastapi`).

```bash
chown -R fastapi:fastapi /opt/libreforms_fastapi
Expand Down
64 changes: 64 additions & 0 deletions libreforms_fastapi/app/static/css/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,67 @@ body {
background-color:#555;
color: white;
}


.admonition {
border: 1px solid #ccc;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
background-color: #f9f9f9;
}

.admonition-title {
font-weight: bold;
margin-bottom: 5px;
}

/* Note Admonition */
.admonition.note {
border-color: #007bff;
background-color: #e7f1ff;
}

.admonition.note .admonition-title {
color: #007bff;
}

/* Tip Admonition */
.admonition.tip {
border-color: #28a745;
background-color: #e6f4ea;
}

.admonition.tip .admonition-title {
color: #28a745;
}

/* Important Admonition */
.admonition.important {
border-color: #dc3545;
background-color: #f8d7da;
}

.admonition.important .admonition-title {
color: #dc3545;
}

/* Warning Admonition */
.admonition.warning {
border-color: #ffc107;
background-color: #fff8e1;
}

.admonition.warning .admonition-title {
color: #ffc107;
}

/* Caution Admonition */
.admonition.caution {
border-color: #ff5733;
background-color: #ffe5d5;
}

.admonition.caution .admonition-title {
color: #ff5733;
}
57 changes: 57 additions & 0 deletions libreforms_fastapi/utils/admonitions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# This is borrowed from https://github.com/dahlia/markdown-gfm-admonition
import re
from typing import List, Optional

from markdown.core import Markdown
from markdown.extensions import Extension
from markdown.blockprocessors import BlockProcessor
from markdown.blockparser import BlockParser
from xml.etree.ElementTree import Element, SubElement

__all__ = ["GfmAdmonitionExtension", "GfmAdmonitionProcessor", "makeExtension"]


class GfmAdmonitionExtension(Extension):
def extendMarkdown(self, md: Markdown) -> None:
md.registerExtension(self)
md.parser.blockprocessors.register(
GfmAdmonitionProcessor(md.parser),
"gfm_admonition",
105
)


class GfmAdmonitionProcessor(BlockProcessor):
PATTERN = re.compile(r"""
^ \s*
\[ ! ( NOTE | TIP | IMPORTANT | WARNING | CAUTION ) \]
(?: $ | (?: [ ] [ ] )? \n )
""", re.VERBOSE)

def __init__(self, parser: BlockParser):
super().__init__(parser)

def test(self, parent: Element, block: str) -> bool:
if parent.tag != "blockquote":
return False
match = self.PATTERN.match(block)
return match is not None

def run(self, parent: Element, blocks: List[str]) -> Optional[bool]:
if not blocks:
return False
match = self.PATTERN.match(blocks[0])
blocks[0] = blocks[0][match.end():]
type_ = match.group(1).lower()
parent.tag = "div"
parent.set("class", "admonition " + type_)
title = SubElement(parent, "p")
title.set("class", "admonition-title")
title.text = type_.capitalize()
self.parser.parseBlocks(parent, blocks)
blocks.clear()
return True


def makeExtension(**kwargs):
return GfmAdmonitionExtension(**kwargs)
20 changes: 14 additions & 6 deletions libreforms_fastapi/utils/docs.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,29 @@
import markdown, os
import os
from pathlib import Path
from datetime import datetime

import markdown
from markdown.extensions.admonition import AdmonitionExtension
from libreforms_fastapi.utils.admonitions import GfmAdmonitionExtension


from html_sanitizer import Sanitizer

sanitizer_config = {
'tags': {'a', 'br', 'p', 'strong', 'em', 'ul', 'ol', 'li', 'b', 'i', 'u', 'span', 'div', 'img', 'h1', 'h2', 'h3', 'h4', 'h5'},
'attributes': {
'a': ['href', 'title'],
'img': ['src', 'alt'],
'div': ['style'], # Might mkae sense to sanitize style content separately
'div': ['style', 'class'], # Might make sense to sanitize style content separately
'p': ['style', 'class'], # Might make sense to sanitize style content separately
},
'empty': {'br', 'h1', 'h2', 'h3', 'h4', 'h5'},
'separate': {'a', 'p', 'ul', 'ol', 'li', 'br', 'img'},
'protocols': {'a': ['http', 'https', 'mailto'], 'img': ['http', 'https']},
'unescape_special_chars': True
}

sanitizer = Sanitizer()
sanitizer = Sanitizer(sanitizer_config)


class UnsafeHtmlContentError(Exception):
Expand Down Expand Up @@ -120,7 +127,8 @@ def get_docs(
if scrub_unsafe:
content = escape_unsafe_html(content)
if render_markdown:
content = markdown.markdown(content, extensions=['toc'])
extensions=['toc', AdmonitionExtension(), GfmAdmonitionExtension()]
content = markdown.markdown(content, extensions=extensions)
return content
except FileNotFoundError:
# Create the parent directories and the file if it doesn't exist
Expand Down Expand Up @@ -183,8 +191,8 @@ def render_markdown_content(
"""
try:
markdown_str = markdown.markdown(markdown_str, extensions=['toc'])

extensions=['toc', AdmonitionExtension(), GfmAdmonitionExtension()]
markdown_str = markdown.markdown(markdown_str, extensions=extensions)

if scrub_unsafe:
markdown_str = sanitizer.sanitize(markdown_str)
Expand Down

0 comments on commit defc0a7

Please sign in to comment.