Fix heading anchors and add anchor links

Fixes #460
This commit is contained in:
rubenwardy
2025-06-19 18:37:03 +01:00
parent 2ddcbfb5ab
commit 21ef5f9b84
6 changed files with 25 additions and 3 deletions

View File

@@ -22,6 +22,7 @@ from markdown_it import MarkdownIt
from markdown_it.common.utils import unescapeAll, escapeHtml
from markdown_it.token import Token
from markdown_it.presets import gfm_like
from mdit_py_plugins.anchors import anchors_plugin
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.util import ClassNotFound
@@ -57,6 +58,7 @@ def render_code(self, tokens: Sequence[Token], idx, options, env):
gfm_like.make()
md = MarkdownIt("gfm-like", {"highlight": highlight_code})
md.use(anchors_plugin, permalink=True, permalinkSymbol="#", max_level=6)
md.add_render_rule("fence", render_code)
init_mention(md)
@@ -82,7 +84,8 @@ def get_headings(html: str):
root = []
stack = []
for heading in headings:
this = {"link": heading.get("id") or "", "text": heading.text, "children": []}
text = heading.find(text=True, recursive=False)
this = {"link": heading.get("id") or "", "text": text, "children": []}
this_level = int(heading.name[1:]) - 1
while this_level <= len(stack):

View File

@@ -57,12 +57,16 @@ def allow_class(_tag, name, value):
return name == "class" and value in ALLOWED_CSS
def allow_a(_tag, name, value):
return name in ["href", "title", "data-username"] or (name == "class" and value == "header-anchor")
ALLOWED_ATTRIBUTES = {
"h1": ["id"],
"h2": ["id"],
"h3": ["id"],
"h4": ["id"],
"a": ["href", "title", "data-username"],
"a": allow_a,
"img": ["src", "title", "alt"],
"code": allow_class,
"div": allow_class,

View File

@@ -51,6 +51,19 @@ h3 {
letter-spacing: .05em
}
h1, h2, h3, h4, h5, h6 {
&::after {
display: block;
content: "";
clear: both;
}
}
.header-anchor {
float: right;
opacity: 0.8;
}
.badge-notify {
background:yellow; /* #00bc8c;*/
color: black;

View File

@@ -16,7 +16,7 @@
{%- endif %}
<link rel="stylesheet" type="text/css" href="/static/libs/bootstrap.min.css?v=4">
<link rel="stylesheet" type="text/css" href="/static/custom.css?v=54">
<link rel="stylesheet" type="text/css" href="/static/custom.css?v=55">
<link rel="search" type="application/opensearchdescription+xml" href="/static/opensearch.xml" title="ContentDB" />
{% if noindex -%}

View File

@@ -41,6 +41,7 @@ libsass==0.23.0
lxml==5.2.2
Mako==1.3.5
markdown-it-py==3.0.0
mdit-py-plugins==0.4.2
linkify-it-py==2.0.3
MarkupSafe==2.1.5
packaging==24.0

View File

@@ -12,6 +12,7 @@ SQLAlchemy-Searchable
bcrypt
markdown-it-py
linkify-it-py
mdit-py-plugins
bleach
passlib