1
0
mirror of https://github.com/squidfunk/mkdocs-material.git synced 2024-11-27 17:00:54 +01:00

Merged features tied to Scotch Bonnet funding goal

This commit is contained in:
squidfunk 2022-09-13 12:35:14 +02:00
parent 6b001c8fa2
commit 419740831d
66 changed files with 1619 additions and 363 deletions

View File

@ -43,12 +43,17 @@ RUN \
apk upgrade --update-cache -a \
&& \
apk add --no-cache \
cairo \
freetype-dev \
git \
git-fast-import \
jpeg-dev \
openssh \
zlib-dev \
&& \
apk add --no-cache --virtual .build \
gcc \
libffi-dev \
musl-dev \
&& \
pip install --no-cache-dir . \

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -34,7 +34,7 @@
{% endif %}
{% endblock %}
{% block styles %}
<link rel="stylesheet" href="{{ 'assets/stylesheets/main.6b80c2a2.min.css' | url }}">
<link rel="stylesheet" href="{{ 'assets/stylesheets/main.bd774711.min.css' | url }}">
{% if config.theme.palette %}
{% set palette = config.theme.palette %}
<link rel="stylesheet" href="{{ 'assets/stylesheets/palette.cbb835fc.min.css' | url }}">
@ -61,13 +61,18 @@
<style>:root{--md-text-font:"{{ text }}";--md-code-font:"{{ code }}"}</style>
{% endif %}
{% endblock %}
{% for path in config["extra_css"] %}
{% for path in config.extra_css %}
<link rel="stylesheet" href="{{ path | url }}">
{% endfor %}
{% include "partials/javascripts/base.html" %}
{% block analytics %}
{% include "partials/integrations/analytics.html" %}
{% endblock %}
{% if page.meta and page.meta.meta %}
{% for tag in page.meta.meta %}
<meta {% for key, value in tag.items() %} {{ key }}="{{value}}" {% endfor %}>
{% endfor %}
{% endif %}
{% block extrahead %}{% endblock %}
</head>
{% set direction = config.theme.direction or lang.t('direction') %}
@ -167,14 +172,16 @@
</div>
{% endif %}
{% endblock %}
<div class="md-content" data-md-component="content">
<article class="md-content__inner md-typeset">
{% block content %}
{% include "partials/content.html" %}
{% endblock %}
</article>
{% include "partials/javascripts/content.html" %}
</div>
{% block container %}
<div class="md-content" data-md-component="content">
<article class="md-content__inner md-typeset">
{% block content %}
{% include "partials/content.html" %}
{% endblock %}
</article>
</div>
{% endblock %}
{% include "partials/javascripts/content.html" %}
</div>
{% if "navigation.top" in features %}
<a href="#" class="md-top md-icon" data-md-component="top" hidden>
@ -211,6 +218,9 @@
{%- if config.extra.version -%}
{%- set _ = app.update({ "version": config.extra.version }) -%}
{%- endif -%}
{%- if config.extra.tags -%}
{%- set _ = app.update({ "tags": config.extra.tags }) -%}
{%- endif -%}
{%- set translations = app.translations -%}
{%- for key in [
"clipboard.copy",
@ -235,8 +245,8 @@
</script>
{% endblock %}
{% block scripts %}
<script src="{{ 'assets/javascripts/bundle.2ab50757.min.js' | url }}"></script>
{% for path in config["extra_javascript"] %}
<script src="{{ 'assets/javascripts/bundle.e93b4713.min.js' | url }}"></script>
{% for path in config.extra_javascript %}
<script src="{{ path | url }}"></script>
{% endfor %}
{% endblock %}

View File

@ -19,5 +19,5 @@
{% endblock %}
{% block scripts %}
{{ super() }}
<script src="{{ 'overrides/assets/javascripts/bundle.a163e2c4.min.js' | url }}"></script>
<script src="{{ 'overrides/assets/javascripts/bundle.a3d871f9.min.js' | url }}"></script>
{% endblock %}

View File

@ -1,7 +1,6 @@
{#-
This file was automatically generated - do not edit
-#}
{% import "partials/language.html" as lang with context %}
{% set cookies = config.extra.consent.cookies %}
{% if config.extra.analytics and not cookies %}
{% set cookies = { "analytics": "Google Analytics" } %}

View File

@ -4,7 +4,7 @@
{% if config.extra.analytics %}
{% set feedback = config.extra.analytics.feedback %}
{% endif %}
{% if page and page.meta and page.meta.hide %}
{% if page.meta and page.meta.hide %}
{% if "feedback" in page.meta.hide %}
{% set feedback = None %}
{% endif %}
@ -27,7 +27,7 @@
{% for rating in feedback.ratings %}
<div data-md-value="{{ rating.data }}" hidden>
{% set url = "/" ~ page.url %}
{% if page and page.meta and page.meta.title %}
{% if page.meta and page.meta.title %}
{% set title = page.meta.title | urlencode %}
{% else %}
{% set title = page.title | urlencode %}

View File

@ -66,7 +66,7 @@
</div>
</div>
{% endif %}
{% if "search" in config["plugins"] %}
{% if "search" in config.plugins %}
<label class="md-header__button md-icon" for="__search">
{% include ".icons/material/magnify.svg" %}
</label>

View File

@ -15,3 +15,22 @@
{% set _ = style.append("}\x3c/style\x3e") %}
{{ style | join }}
{% endif %}
{% if config.theme.icon.tag %}
{% set style = ["\x3cstyle\x3e"] %}
{% for type, icon in config.theme.icon.tag.items() %}
{% import ".icons/" ~ icon ~ ".svg" as icon %}
{% if type != "default" %}
{% set modifier = "--" ~ type %}
{% endif %}
{% set _ = style.append(
".md-tag-icon" ~ modifier ~ "{" ~
"--md-tag-icon:" ~
"url('data:image/svg+xml;charset=utf-8," ~
icon | replace("\n", "") ~
"');" ~
"}"
) %}
{% endfor %}
{% set _ = style.append("\x3c/style\x3e") %}
{{ style | join }}
{% endif %}

View File

@ -12,8 +12,11 @@
"edit.link.title": "Seite editieren",
"footer.previous": "Zurück",
"footer.next": "Weiter",
"footer.title": "Fußzeile",
"header.title": "Kopfzeile",
"meta.comments": "Kommentare",
"meta.source": "Quellcode",
"nav.title": "Navigation",
"search.config.lang": "de",
"search.placeholder": "Suche",
"search.share": "Teilen",
@ -30,9 +33,10 @@
"select.language.title": "Sprache wechseln",
"select.version.title": "Version auswählen",
"skip.link.title": "Zum Inhalt",
"source.link.title": "Quellcode",
"source.link.title": "Zum Repository",
"source.file.date.updated": "Letztes Update",
"source.file.date.created": "Erstellt",
"tabs.title": "Hauptnavigation",
"toc.title": "Inhaltsverzeichnis",
"top.title": "Zurück zum Seitenanfang"
}[key] }}{% endmacro %}

View File

@ -12,11 +12,11 @@
</label>
<nav class="md-search__options" aria-label="{{ lang.t('search.title') }}">
{% if "search.share" in features %}
<a href="javascript:void(0)" class="md-search__icon md-icon" aria-label="{{ lang.t('search.share') }}" data-clipboard data-clipboard-text="" data-md-component="search-share" tabindex="-1">
<a href="javascript:void(0)" class="md-search__icon md-icon" title="{{ lang.t('search.share') }}" aria-label="{{ lang.t('search.share') }}" data-clipboard data-clipboard-text="" data-md-component="search-share" tabindex="-1">
{% include ".icons/material/share-variant.svg" %}
</a>
{% endif %}
<button type="reset" class="md-search__icon md-icon" aria-label="{{ lang.t('search.reset') }}" tabindex="-1">
<button type="reset" class="md-search__icon md-icon" title="{{ lang.t('search.reset') }}" aria-label="{{ lang.t('search.reset') }}" tabindex="-1">
{% include ".icons/material/close.svg" %}
</button>
</nav>

View File

@ -7,12 +7,20 @@
{% if tags %}
<nav class="md-tags" {{ hidden }}>
{% for tag in tags %}
{% if config.extra.tags %}
{% set icon = " md-tag-icon" %}
{% if tag.type %}
{% set icon = icon ~ " md-tag-icon--" ~ tag.type %}
{% endif %}
{% endif %}
{% if tag.url %}
<a href="{{ tag.url | url }}" class="md-tag">
{{ tag.name }}
<a href="{{ tag.url | url }}" class="md-tag{{ icon }}">
{{- tag.name -}}
</a>
{% else %}
<span class="md-tag">{{ tag.name }}</span>
<span class="md-tag{{ icon }}">
{{- tag.name -}}
</span>
{% endif %}
{% endfor %}
</nav>

View File

View File

@ -0,0 +1,398 @@
# Copyright (c) 2016-2022 Martin Donath <martin.donath@squidfunk.com>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import os
import re
import requests
from cairosvg import svg2png
from collections import defaultdict
from hashlib import md5
from io import BytesIO
from mkdocs.config.config_options import Deprecated, Type
from mkdocs.plugins import BasePlugin
from PIL import Image, ImageDraw, ImageFont
from shutil import copyfile
from tempfile import TemporaryFile
from zipfile import ZipFile
# -----------------------------------------------------------------------------
# Class
# -----------------------------------------------------------------------------
# Social plugin
class SocialPlugin(BasePlugin):
# Configuration scheme
config_scheme = (
("enabled", Type(bool, default = True)),
("cache_dir", Type(str, default = ".cache/plugin/social")),
# Options for social cards
("cards", Type(bool, default = True)),
("cards_dir", Type(str, default = "assets/images/social")),
("cards_color", Type(dict, default = {})),
("cards_font", Type(str, default = None)),
# Deprecated options
("cards_directory", Deprecated(moved_to = "cards_dir")),
)
# Retrieve configuration
def on_config(self, config):
self.color = colors.get("indigo")
if not self.config["cards"]:
return
# Ensure presence of cache directory
self.cache = self.config["cache_dir"]
if not os.path.isdir(self.cache):
os.makedirs(self.cache)
# Retrieve palette from theme configuration
theme = config["theme"]
if "palette" in theme:
palette = theme["palette"]
# Use first palette, if multiple are defined
if isinstance(palette, list):
palette = palette[0]
# Set colors according to palette
if "primary" in palette and palette["primary"]:
primary = palette["primary"].replace(" ", "-")
self.color = colors.get(primary, self.color)
# Retrieve color overrides
self.color = { **self.color, **self.config["cards_color"] }
# Retrieve logo and font
self.logo = self._load_logo(config)
self.font = self._load_font(config)
# Create social cards
def on_page_markdown(self, markdown, page, config, files):
if not self.config["cards"]:
return
# Resolve image directory
directory = self.config["cards_dir"]
file, _ = os.path.splitext(page.file.src_path)
# Resolve path of image
path = "{}.png".format(os.path.join(
config["site_dir"],
directory,
file
))
# Resolve path of image directory
directory = os.path.dirname(path)
if not os.path.isdir(directory):
os.makedirs(directory)
# Compute site name
site_name = config.get("site_name")
# Compute page title and description
title = page.meta.get("title", page.title)
description = config.get("site_description") or ""
if "description" in page.meta:
description = page.meta["description"]
# Generate social card if not in cache - TODO: values from mkdocs.yml
hash = md5("".join([
site_name,
str(title),
description
]).encode("utf-8"))
file = os.path.join(self.cache, f"{hash.hexdigest()}.png")
if not os.path.isfile(file):
image = self._render_card(site_name, title, description)
image.save(file)
# Copy file from cache
copyfile(file, path)
# Inject meta tags into page
meta = page.meta.get("meta", [])
page.meta["meta"] = meta + self._generate_meta(page, config)
# -------------------------------------------------------------------------
# Render social card
def _render_card(self, site_name, title, description):
logo = self.logo
# Render background and logo
image = self._render_card_background((1200, 630), self.color["fill"])
image.alpha_composite(
logo.resize((144, int(144 * logo.height / logo.width))),
(1200 - 228, 64 - 4)
)
# Render site name
font = ImageFont.truetype(self.font["Bold"], 36)
image.alpha_composite(
self._render_text((826, 48), font, site_name, 1, 20),
(64 + 4, 64)
)
# Render page title
font = ImageFont.truetype(self.font["Bold"], 92)
image.alpha_composite(
self._render_text((826, 328), font, title, 3, 30),
(64, 160)
)
# Render page description
font = ImageFont.truetype(self.font["Regular"], 28)
image.alpha_composite(
self._render_text((826, 80), font, description, 2, 14),
(64 + 4, 512)
)
# Return social card image
return image
# Render social card background
def _render_card_background(self, size, fill):
return Image.new(mode = "RGBA", size = size, color = fill)
# Render social card text
def _render_text(self, size, font, text, lmax, spacing = 0):
lines, words = [], []
# Remove remnant HTML tags
text = re.sub(r"(<[^>]+>)", "", text)
# Create temporary image
image = Image.new(mode = "RGBA", size = size)
# Retrieve y-offset of textbox to correct for spacing
yoffset = 0
# Create drawing context and split text into lines
context = ImageDraw.Draw(image)
for word in text.split(" "):
combine = " ".join(words + [word])
textbox = context.textbbox((0, 0), combine, font = font)
yoffset = textbox[1]
if not words or textbox[2] <= image.width:
words.append(word)
else:
lines.append(words)
words = [word]
# # Balance words on last line - TODO: overflows when broken word is too long
# if len(lines) > 0:
# prev = len(" ".join(lines[-1]))
# last = len(" ".join(words))#
# print(last, prev)
# # Heuristic: try to find a good ratio
# if last / prev < 0.6:
# words.insert(0, lines[-1].pop())
# Join words for each line and create image
lines.append(words)
lines = [" ".join(line) for line in lines]
image = Image.new(mode = "RGBA", size = size)
# Create drawing context and split text into lines
context = ImageDraw.Draw(image)
context.text(
(0, spacing / 2 - yoffset), "\n".join(lines[:lmax]),
font = font, fill = self.color["text"], spacing = spacing - yoffset
)
# Return text image
return image
# -------------------------------------------------------------------------
# Generate meta tags
def _generate_meta(self, page, config):
directory = self.config["cards_dir"]
file, _ = os.path.splitext(page.file.src_path)
# Compute page title
title = page.meta.get("title", page.title)
if not page.is_homepage:
title = f"{title} - {config.get('site_name')}"
# Compute page description
description = config.get("site_description")
if "description" in page.meta:
description = page.meta["description"]
# Resolve image URL
url = "{}.png".format(os.path.join(
config.get("site_url"),
directory,
file
))
# Ensure forward slashes
url = url.replace(os.path.sep, "/")
# Return meta tags
return [
# Meta tags for Open Graph
{ "property": "og:type", "content": "website" },
{ "property": "og:title", "content": title },
{ "property": "og:description", "content": description },
{ "property": "og:image", "content": url },
{ "property": "og:image:type", "content": "image/png" },
{ "property": "og:image:width", "content": "1200" },
{ "property": "og:image:height", "content": "630" },
{ "property": "og:url", "content": page.canonical_url },
# Meta tags for Twitter
{ "name": "twitter:card", "content": "summary_large_image" },
# { "name": "twitter:site", "content": user },
# { "name": "twitter:creator", "content": user },
{ "name": "twitter:title", "content": title },
{ "name": "twitter:description", "content": description },
{ "name": "twitter:image", "content": url }
]
# Retrieve logo image or icon
def _load_logo(self, config):
theme = config.get("theme")
# Handle images (precedence over icons)
if "logo" in theme:
_, extension = os.path.splitext(theme["logo"])
# Load SVG and convert to PNG
path = os.path.join(config["docs_dir"], theme["logo"])
if extension == ".svg":
return self._load_logo_svg(path)
# Load PNG, JPEG, etc.
return Image.open(path).convert("RGBA")
# Handle icons
logo = "material/library"
icon = theme["icon"] or {}
if "logo" in icon and icon["logo"]:
logo = icon["logo"]
# Resolve path of package
base = os.path.abspath(os.path.join(
os.path.dirname(__file__),
"../.."
))
# Load icon data and fill with color
path = f"{base}/.icons/{logo}.svg"
return self._load_logo_svg(path, self.color["text"])
# Load SVG file and convert to PNG
def _load_logo_svg(self, path, fill = None):
file = BytesIO()
data = open(path).read()
# Fill with color, if given
if fill:
data = data.replace("<svg", f"<svg fill=\"{fill}\"")
# Convert to PNG and return image
svg2png(bytestring = data, write_to = file, scale = 10)
return Image.open(file)
# Retrieve font
def _load_font(self, config):
name = self.config.get("cards_font")
if not name:
# Retrieve from theme (default: Roboto)
theme = config["theme"]
if theme["font"]:
name = theme["font"]["text"]
else:
name = "Roboto"
# Retrieve font files, if not already done
files = os.listdir(self.cache)
files = [file for file in files if file.endswith(".ttf") or file.endswith(".otf")] or (
self._load_font_from_google(name)
)
# Map available font weights to file paths
font = dict()
for file in files:
match = re.search("-(\w+)\.[ot]tf$", file)
if match:
font[match.group(1)] = os.path.join(self.cache, file)
# Return available font weights with fallback
return defaultdict(lambda: font["Regular"], font)
# Retrieve font from Google Fonts
def _load_font_from_google(self, name):
url = "https://fonts.google.com/download?family={}"
res = requests.get(url.format(name.replace(" ", "+")), stream = True)
# Write archive to temporary file
tmp = TemporaryFile()
for chunk in res.iter_content(chunk_size = 128):
tmp.write(chunk)
# Unzip fonts from temporary file
zip = ZipFile(tmp)
files = [file for file in zip.namelist() if file.endswith(".ttf") or file.endswith(".otf")]
zip.extractall(self.cache, files)
# Close and delete temporary file
tmp.close()
return files
# -----------------------------------------------------------------------------
# Data
# -----------------------------------------------------------------------------
# Color palette
colors = dict({
"red": { "fill": "#ef5552", "text": "#ffffff" },
"pink": { "fill": "#e92063", "text": "#ffffff" },
"purple": { "fill": "#ab47bd", "text": "#ffffff" },
"deep-purple": { "fill": "#7e56c2", "text": "#ffffff" },
"indigo": { "fill": "#4051b5", "text": "#ffffff" },
"blue": { "fill": "#2094f3", "text": "#ffffff" },
"light-blue": { "fill": "#02a6f2", "text": "#ffffff" },
"cyan": { "fill": "#00bdd6", "text": "#ffffff" },
"teal": { "fill": "#009485", "text": "#ffffff" },
"green": { "fill": "#4cae4f", "text": "#ffffff" },
"light-green": { "fill": "#8bc34b", "text": "#ffffff" },
"lime": { "fill": "#cbdc38", "text": "#000000" },
"yellow": { "fill": "#ffec3d", "text": "#000000" },
"amber": { "fill": "#ffc105", "text": "#000000" },
"orange": { "fill": "#ffa724", "text": "#000000" },
"deep-orange": { "fill": "#ff6e42", "text": "#ffffff" },
"brown": { "fill": "#795649", "text": "#ffffff" },
"grey": { "fill": "#757575", "text": "#ffffff" },
"blue-grey": { "fill": "#546d78", "text": "#ffffff" },
"black": { "fill": "#000000", "text": "#ffffff" },
"white": { "fill": "#ffffff", "text": "#000000" }
})

View File

@ -42,92 +42,106 @@ class TagsPlugin(BasePlugin):
)
# Initialize plugin
def __init__(self):
def on_config(self, config):
self.tags = defaultdict(list)
self.tags_file = None
self.slugify = None
# Retrieve configuration for anchor generation
def on_config(self, config):
if "toc" in config["markdown_extensions"]:
toc = { "slugify": slugify, "separator": "-" }
if "toc" in config["mdx_configs"]:
toc = { **toc, **config["mdx_configs"]["toc"] }
# Retrieve tags mapping from configuration
self.tags_map = config["extra"].get("tags")
# Partially apply slugify function
self.slugify = lambda value: (
toc["slugify"](str(value), toc["separator"])
)
# Use override of slugify function
toc = { "slugify": slugify, "separator": "-" }
if "toc" in config["mdx_configs"]:
toc = { **toc, **config["mdx_configs"]["toc"] }
# Hack: 2nd pass for tags index page
def on_nav(self, nav, files, **kwargs):
# Partially apply slugify function
self.slugify = lambda value: (
toc["slugify"](str(value), toc["separator"])
)
# Hack: 2nd pass for tags index page(s)
def on_nav(self, nav, config, files):
file = self.config.get("tags_file")
if file:
self.tags_file = files.get_file_from_path(file)
if not self.tags_file:
log.error(f"Configuration error: {file} doesn't exist.")
sys.exit()
# Add tags file to files
files.append(self.tags_file)
self.tags_file = self._get_tags_file(files, file)
# Build and render tags index page
def on_page_markdown(self, markdown, page, **kwargs):
def on_page_markdown(self, markdown, page, config, files):
if page.file == self.tags_file:
return self.__render_tag_index(markdown)
return self._render_tag_index(markdown)
# Add page to tags index
for tag in page.meta.get("tags", []):
self.tags[tag].append(page)
# Inject tags into page (after search and before minification)
def on_page_context(self, context, page, **kwargs):
def on_page_context(self, context, page, config, nav):
if "tags" in page.meta:
context["tags"] = [
self.__render_tag(tag)
self._render_tag(tag)
for tag in page.meta["tags"]
]
# -------------------------------------------------------------------------
# Obtain tags file
def _get_tags_file(self, files, path):
file = files.get_file_from_path(path)
if not file:
log.error(f"Tags file '{path}' does not exist.")
sys.exit()
# Add tags file to files
files.append(file)
return file
# Render tags index
def __render_tag_index(self, markdown):
def _render_tag_index(self, markdown):
if not "[TAGS]" in markdown:
markdown += "\n[TAGS]"
# Replace placeholder in Markdown with rendered tags index
return markdown.replace("[TAGS]", "\n".join([
self.__render_tag_links(*args)
self._render_tag_links(*args)
for args in sorted(self.tags.items())
]))
# Render the given tag and links to all pages with occurrences
def __render_tag_links(self, tag, pages):
content = [f"## <span class=\"md-tag\">{tag}</span>", ""]
def _render_tag_links(self, tag, pages):
classes = ["md-tag"]
if isinstance(self.tags_map, dict):
classes.append("md-tag-icon")
type = self.tags_map.get(tag)
if type:
classes.append(f"md-tag-icon--{type}")
# Render section for tag and a link to each page
classes = " ".join(classes)
content = [f"## <span class=\"{classes}\">{tag}</span>", ""]
for page in pages:
# Ensure forward slashes, as we have to use the path of the source
# file which contains the operating system's path separator.
url = utils.get_relative_url(
page.file.src_path.replace(os.path.sep, "/"),
self.tags_file.src_path.replace(os.path.sep, "/")
)
# Ensure forward slashes, as we have to use the path of the source
# file which contains the operating system's path separator.
content.append("- [{}]({})".format(
page.meta.get("title", page.title),
url
))
# Render link to page
title = page.meta.get("title", page.title)
content.append(f"- [{title}]({url})")
# Return rendered tag links
return "\n".join(content)
# Render the given tag, linking to the tags index (if enabled)
def __render_tag(self, tag):
def _render_tag(self, tag):
type = self.tags_map.get(tag) if self.tags_map else None
if not self.tags_file or not self.slugify:
return dict(name = tag)
return dict(name = tag, type = type)
else:
url = self.tags_file.url
url += f"#{self.slugify(tag)}"
return dict(name = tag, url = url)
url = f"{self.tags_file.url}#{self.slugify(tag)}"
return dict(name = tag, type = type, url = url)
# -----------------------------------------------------------------------------
# Data

View File

@ -102,6 +102,7 @@ plugins:
upgrading.md: upgrade.md
- minify:
minify_html: true
- social
# Customization
extra:

View File

@ -18,10 +18,15 @@
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
# Direct dependencies
# Requirements for core
jinja2>=3.0.2
markdown>=3.2
mkdocs>=1.3.0
mkdocs-material-extensions>=1.0.3
pygments>=2.12
pymdown-extensions>=9.4
# Requirements for social plugin
cairosvg>=2.5
pillow>=8.0
requests>=2.26

View File

@ -71,6 +71,7 @@ setup(
],
"mkdocs.plugins": [
"search = material.plugins.search.plugin:SearchPlugin",
"social = material.plugins.social.plugin:SocialPlugin",
"tags = material.plugins.tags.plugin:TagsPlugin"
]
},

View File

@ -32,6 +32,7 @@ import { getElement, getLocation } from "~/browser"
export type Flag =
| "announce.dismiss" /* Dismissable announcement bar */
| "content.code.annotate" /* Code annotations */
| "content.lazy" /* Lazy content elements */
| "content.tabs.link" /* Link content tabs */
| "header.autohide" /* Hide header */
| "navigation.expand" /* Automatic expansion */
@ -45,6 +46,7 @@ export type Flag =
| "search.highlight" /* Search highlighting */
| "search.share" /* Search sharing */
| "search.suggest" /* Search suggestions */
| "toc.follow" /* Following table of contents */
| "toc.integrate" /* Integrated table of contents */
/* ------------------------------------------------------------------------- */
@ -91,6 +93,7 @@ export interface Config {
features: Flag[] /* Feature flags */
translations: Translations /* Translations */
search: string /* Search worker URL */
tags?: Record<string, string> /* Tags mapping */
version?: Versioning /* Versioning */
}

View File

@ -1,5 +1,6 @@
{
"rules": {
"jsdoc/require-jsdoc": "off"
"jsdoc/require-jsdoc": "off",
"jsdoc/require-returns-check": "off"
}
}

View File

@ -41,3 +41,27 @@ export function getElementContentSize(
height: el.scrollHeight
}
}
/**
* Retrieve the overflowing container of an element, if any
*
* @param el - Element
*
* @returns Overflowing container or nothing
*/
export function getElementContainer(
el: HTMLElement
): HTMLElement | undefined {
let parent = el.parentElement
while (parent)
if (
el.scrollWidth <= parent.scrollWidth &&
el.scrollHeight <= parent.scrollHeight
)
parent = (el = parent).parentElement
else
break
/* Return overflowing container */
return parent ? el : undefined
}

View File

@ -94,7 +94,7 @@ export function mountContent(
/* Code blocks */
...getElements("pre:not(.mermaid) > code", el)
.map(child => mountCodeBlock(child, { print$ })),
.map(child => mountCodeBlock(child, { target$, print$ })),
/* Mermaid diagrams */
...getElements("pre.mermaid", el)

View File

@ -21,26 +21,31 @@
*/
import {
EMPTY,
Observable,
Subject,
animationFrameScheduler,
auditTime,
combineLatest,
debounceTime,
defer,
delay,
filter,
finalize,
fromEvent,
map,
merge,
switchMap,
take,
takeLast,
takeUntil,
tap,
throttleTime
throttleTime,
withLatestFrom
} from "rxjs"
import {
ElementOffset,
getElement,
getActiveElement,
getElementSize,
watchElementContentOffset,
watchElementFocus,
@ -62,6 +67,17 @@ export interface Annotation {
offset: ElementOffset /* Annotation offset */
}
/* ----------------------------------------------------------------------------
* Helper types
* ------------------------------------------------------------------------- */
/**
* Mount options
*/
interface MountOptions {
target$: Observable<HTMLElement> /* Location target observable */
}
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
@ -82,11 +98,11 @@ export function watchAnnotation(
watchElementContentOffset(container)
]))
.pipe(
map(([{ x, y }, scroll]) => {
const { width } = getElementSize(el)
map(([{ x, y }, scroll]): ElementOffset => {
const { width, height } = getElementSize(el)
return ({
x: x - scroll.x + width / 2,
y: y - scroll.y
y: y - scroll.y + height / 2
})
})
)
@ -108,14 +124,19 @@ export function watchAnnotation(
*
* @param el - Annotation element
* @param container - Containing element
* @param options - Options
*
* @returns Annotation component observable
*/
export function mountAnnotation(
el: HTMLElement, container: HTMLElement
el: HTMLElement, container: HTMLElement, { target$ }: MountOptions
): Observable<Component<Annotation>> {
const [tooltip, index] = Array.from(el.children)
/* Mount component on subscription */
return defer(() => {
const push$ = new Subject<Annotation>()
const done$ = push$.pipe(takeLast(1))
push$.subscribe({
/* Handle emission */
@ -132,7 +153,6 @@ export function mountAnnotation(
})
/* Start animation only when annotation is visible */
const done$ = push$.pipe(takeLast(1))
watchElementVisibility(el)
.pipe(
takeUntil(done$)
@ -141,11 +161,42 @@ export function mountAnnotation(
el.toggleAttribute("data-md-visible", visible)
})
/* Toggle tooltip presence to mitigate empty lines when copying */
merge(
push$.pipe(filter(({ active }) => active)),
push$.pipe(debounceTime(250), filter(({ active }) => !active))
)
.subscribe({
/* Handle emission */
next({ active }) {
if (active)
el.prepend(tooltip)
else
tooltip.remove()
},
/* Handle complete */
complete() {
el.prepend(tooltip)
}
})
/* Toggle tooltip visibility */
push$
.pipe(
auditTime(16, animationFrameScheduler)
)
.subscribe(({ active }) => {
tooltip.classList.toggle("md-tooltip--active", active)
})
/* Track relative origin of tooltip */
push$
.pipe(
throttleTime(500, animationFrameScheduler),
map(() => container.getBoundingClientRect()),
throttleTime(125, animationFrameScheduler),
filter(() => !!el.offsetParent),
map(() => el.offsetParent!.getBoundingClientRect()),
map(({ x }) => x)
)
.subscribe({
@ -164,15 +215,47 @@ export function mountAnnotation(
}
})
/* Close open annotation on click */
const index = getElement(":scope > :last-child", el)
const blur$ = fromEvent(index, "mousedown", { once: true })
push$
/* Allow to copy link without scrolling to anchor */
fromEvent<MouseEvent>(index, "click")
.pipe(
switchMap(({ active }) => active ? blur$ : EMPTY),
tap(ev => ev.preventDefault())
takeUntil(done$),
filter(ev => !(ev.metaKey || ev.ctrlKey))
)
.subscribe(() => el.blur())
.subscribe(ev => ev.preventDefault())
/* Allow to open link in new tab or blur on close */
fromEvent<MouseEvent>(index, "mousedown")
.pipe(
takeUntil(done$),
withLatestFrom(push$)
)
.subscribe(([ev, { active }]) => {
/* Open in new tab */
if (ev.button !== 0 || ev.metaKey || ev.ctrlKey) {
ev.preventDefault()
/* Close annotation */
} else if (active) {
ev.preventDefault()
/* Focus parent annotation, if any */
const parent = el.parentElement!.closest(".md-annotation")
if (parent instanceof HTMLElement)
parent.focus()
else
getActiveElement()?.blur()
}
})
/* Open and focus annotation on location target */
target$
.pipe(
takeUntil(done$),
filter(target => target === tooltip),
delay(125)
)
.subscribe(() => el.focus())
/* Create and return component */
return watchAnnotation(el, container)

View File

@ -53,6 +53,7 @@ import {
* Mount options
*/
interface MountOptions {
target$: Observable<HTMLElement> /* Location target observable */
print$: Observable<boolean> /* Media print observable */
}
@ -69,17 +70,34 @@ interface MountOptions {
*/
function findAnnotationMarkers(container: HTMLElement): Text[] {
const markers: Text[] = []
for (const comment of getElements(".c, .c1, .cm", container)) {
let match: RegExpExecArray | null
for (const el of getElements(".c, .c1, .cm", container)) {
const nodes: Text[] = []
/* Split text at marker and add to list */
let text = comment.firstChild as Text
if (text instanceof Text)
while ((match = /\((\d+)\)/.exec(text.textContent!))) {
const marker = text.splitText(match.index)
text = marker.splitText(match[0].length)
markers.push(marker)
/* Find all text nodes in current element */
const it = document.createNodeIterator(el, NodeFilter.SHOW_TEXT)
for (let node = it.nextNode(); node; node = it.nextNode())
nodes.push(node as Text)
/* Find all markers in each text node */
for (let text of nodes) {
let match: RegExpExecArray | null
/* Split text at marker and add to list */
while ((match = /(\(\d+\))(!)?/.exec(text.textContent!))) {
const [, id, force] = match
if (typeof force === "undefined") {
const marker = text.splitText(match.index)
text = marker.splitText(id.length)
markers.push(marker)
/* Replace entire text with marker */
} else {
text.textContent = id
markers.push(text)
break
}
}
}
}
return markers
}
@ -113,16 +131,20 @@ function swap(source: HTMLElement, target: HTMLElement): void {
* @returns Annotation component observable
*/
export function mountAnnotationList(
el: HTMLElement, container: HTMLElement, { print$ }: MountOptions
el: HTMLElement, container: HTMLElement, { target$, print$ }: MountOptions
): Observable<Component<Annotation>> {
/* Compute prefix for tooltip anchors */
const parent = container.closest("[id]")
const prefix = parent?.id
/* Find and replace all markers with empty annotations */
const annotations = new Map<number, HTMLElement>()
const annotations = new Map<string, HTMLElement>()
for (const marker of findAnnotationMarkers(container)) {
const [, id] = marker.textContent!.match(/\((\d+)\)/)!
if (getOptionalElement(`li:nth-child(${id})`, el)) {
annotations.set(+id, renderAnnotation(+id))
marker.replaceWith(annotations.get(+id)!)
annotations.set(id, renderAnnotation(id, prefix))
marker.replaceWith(annotations.get(id)!)
}
}
@ -130,33 +152,38 @@ export function mountAnnotationList(
if (annotations.size === 0)
return EMPTY
/* Create and return component */
/* Mount component on subscription */
return defer(() => {
const done$ = new Subject<void>()
const done$ = new Subject()
/* Retrieve container pairs for swapping */
const pairs: [HTMLElement, HTMLElement][] = []
for (const [id, annotation] of annotations)
pairs.push([
getElement(".md-typeset", annotation),
getElement(`li:nth-child(${id})`, el)
])
/* Handle print mode - see https://bit.ly/3rgPdpt */
print$
.pipe(
takeUntil(done$.pipe(takeLast(1)))
)
.subscribe(active => {
el.hidden = !active
.subscribe(active => {
el.hidden = !active
/* Show annotations in code block or list (print) */
for (const [id, annotation] of annotations) {
const inner = getElement(".md-typeset", annotation)
const child = getElement(`li:nth-child(${id})`, el)
if (!active)
swap(child, inner)
else
swap(inner, child)
}
})
/* Show annotations in code block or list (print) */
for (const [inner, child] of pairs)
if (!active)
swap(child, inner)
else
swap(inner, child)
})
/* Create and return component */
return merge(...[...annotations]
.map(([, annotation]) => (
mountAnnotation(annotation, container)
mountAnnotation(annotation, container, { target$ })
))
)
.pipe(

View File

@ -34,8 +34,6 @@ import {
mergeWith,
switchMap,
take,
takeLast,
takeUntil,
tap
} from "rxjs"
@ -72,6 +70,7 @@ export interface CodeBlock {
* Mount options
*/
interface MountOptions {
target$: Observable<HTMLElement> /* Location target observable */
print$: Observable<boolean> /* Media print observable */
}
@ -80,7 +79,7 @@ interface MountOptions {
* ------------------------------------------------------------------------- */
/**
* Global sequence number for Clipboard.js integration
* Global sequence number for code blocks
*/
let sequence = 0
@ -147,6 +146,11 @@ export function watchCodeBlock(
* Furthermore, if code annotations are enabled, they are mounted if and only
* if the code block is currently visible, e.g., not in a hidden content tab.
*
* Note that code blocks may be mounted eagerly or lazily. If they're mounted
* lazily (on first visibility), code annotation anchor links will not work,
* as they are evaluated on initial page load, and code annotations in general
* might feel a little bumpier.
*
* @param el - Code block element
* @param options - Options
*
@ -198,7 +202,6 @@ export function mountCodeBlock(
mergeWith(
watchElementSize(container)
.pipe(
takeUntil(push$.pipe(takeLast(1))),
map(({ width, height }) => width && height),
distinctUntilChanged(),
switchMap(active => active ? annotations$ : EMPTY)
@ -217,11 +220,15 @@ export function mountCodeBlock(
)
})
/* Mount code block on first sight */
return watchElementVisibility(el)
.pipe(
filter(visible => visible),
take(1),
switchMap(() => factory$)
)
/* Mount code block lazily */
if (feature("content.lazy"))
return watchElementVisibility(el)
.pipe(
filter(visible => visible),
take(1),
switchMap(() => factory$)
)
/* Mount code block */
return factory$
}

View File

@ -122,10 +122,7 @@ export function mountDetails(
return defer(() => {
const push$ = new Subject<Details>()
push$.subscribe(({ action, reveal }) => {
if (action === "open")
el.setAttribute("open", "")
else
el.removeAttribute("open")
el.toggleAttribute("open", action === "open")
if (reveal)
el.scrollIntoView()
})

View File

@ -30,6 +30,8 @@ import {
distinctUntilChanged,
finalize,
map,
observeOn,
take,
tap,
withLatestFrom
} from "rxjs"
@ -37,7 +39,10 @@ import {
import {
Viewport,
getElement,
getElementOffset
getElementContainer,
getElementOffset,
getElementSize,
getElements
} from "~/browser"
import { Component } from "../_"
@ -169,6 +174,25 @@ export function mountSidebar(
}
})
/* Bring active item into view on initial load */
push$
.pipe(
observeOn(animationFrameScheduler),
take(1)
)
.subscribe(() => {
for (const item of getElements(".md-nav__link--active[href]", el)) {
const container = getElementContainer(item)
if (typeof container !== "undefined") {
const offset = item.offsetTop - container.offsetTop
const { height } = getElementSize(container)
container.scrollTo({
top: offset - height / 2
})
}
}
})
/* Create and return component */
return watchSidebar(el, options)
.pipe(

View File

@ -29,8 +29,10 @@ import {
defer,
distinctUntilChanged,
distinctUntilKeyChanged,
filter,
finalize,
map,
merge,
of,
repeat,
scan,
@ -48,6 +50,8 @@ import { feature } from "~/_"
import {
Viewport,
getElement,
getElementContainer,
getElementSize,
getElements,
getLocation,
getOptionalElement,
@ -288,6 +292,39 @@ export function mountTableOfContents(
}
})
/* Set up following, if enabled */
if (feature("toc.follow")) {
/* Toggle smooth scrolling only for anchor clicks */
const smooth$ = merge(
viewport$.pipe(debounceTime(1), map(() => undefined)),
viewport$.pipe(debounceTime(250), map(() => "smooth" as const))
)
/* Bring active anchor into view */
push$
.pipe(
filter(({ prev }) => prev.length > 0),
withLatestFrom(smooth$)
)
.subscribe(([{ prev }, behavior]) => {
const [anchor] = prev[prev.length - 1]
if (anchor.offsetHeight) {
/* Retrieve overflowing container and scroll */
const container = getElementContainer(anchor)
if (typeof container !== "undefined") {
const offset = anchor.offsetTop - container.offsetTop
const { height } = getElementSize(container)
container.scrollTo({
top: offset - height / 2,
behavior
})
}
}
})
}
/* Set up anchor tracking, if enabled */
if (feature("navigation.tracking"))
viewport$

View File

@ -22,26 +22,44 @@
import { h } from "~/utilities"
import { renderTooltip } from "../tooltip"
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Render an empty annotation
* Render an annotation
*
* @param id - Annotation identifier
* @param prefix - Tooltip identifier prefix
*
* @returns Element
*/
export function renderAnnotation(id: number): HTMLElement {
return (
<aside class="md-annotation" tabIndex={0}>
<div class="md-annotation__inner md-tooltip">
<div class="md-tooltip__inner md-typeset"></div>
</div>
<span class="md-annotation__index">
<span data-md-annotation-id={id}></span>
</span>
</aside>
)
export function renderAnnotation(
id: string | number, prefix?: string
): HTMLElement {
prefix = prefix ? `${prefix}_annotation_${id}` : undefined
/* Render tooltip with anchor, if given */
if (prefix) {
const anchor = prefix ? `#${prefix}` : undefined
return (
<aside class="md-annotation" tabIndex={0}>
{renderTooltip(prefix)}
<a href={anchor} class="md-annotation__index" tabIndex={-1}>
<span data-md-annotation-id={id}></span>
</a>
</aside>
)
} else {
return (
<aside class="md-annotation" tabIndex={0}>
{renderTooltip(prefix)}
<span class="md-annotation__index" tabIndex={-1}>
<span data-md-annotation-id={id}></span>
</span>
</aside>
)
}
}

View File

@ -22,7 +22,7 @@
import { ComponentChild } from "preact"
import { feature, translation } from "~/_"
import { configuration, feature, translation } from "~/_"
import {
SearchDocument,
SearchMetadata,
@ -77,10 +77,11 @@ function renderSearchDocument(
)
/* Render article or section, depending on flags */
const { tags } = configuration()
return (
<a href={`${url}`} class="md-search-result__link" tabIndex={-1}>
<article
class={["md-search-result__article", ...parent
class={["md-search-result__article", "md-typeset", ...parent
? ["md-search-result__article--document"]
: []
].join(" ")}
@ -93,9 +94,17 @@ function renderSearchDocument(
{truncate(document.text, 320)}
</p>
}
{document.tags && document.tags.map(tag => (
<span class="md-tag">{tag}</span>
))}
{document.tags && document.tags.map(tag => {
const id = tag.replace(/<[^>]+>/g, "")
const type = tags
? id in tags
? `md-tag-icon md-tag-icon--${tags[id]}`
: "md-tag-icon"
: ""
return (
<span class={`md-tag ${type}`}>{tag}</span>
)
})}
{teaser > 0 && missing.length > 0 &&
<p class="md-search-result__terms">
{translation("search.result.term.missing")}: {...missing}

View File

@ -0,0 +1,42 @@
/*
* Copyright (c) 2016-2021 Martin Donath <martin.donath@squidfunk.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
import { h } from "~/utilities"
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Render a tooltip
*
* @param id - Tooltip identifier
*
* @returns Element
*/
export function renderTooltip(id?: string): HTMLElement {
return (
<div class="md-tooltip" id={id}>
<div class="md-tooltip__inner md-typeset"></div>
</div>
)
}

View File

@ -50,7 +50,7 @@ export interface Version {
function renderVersion(version: Version): HTMLElement {
const config = configuration()
/* Ensure trailing slash, see https://bit.ly/3rL5u3f */
/* Ensure trailing slash - see https://bit.ly/3rL5u3f */
const url = new URL(`../${version.version}/`, config.base)
return (
<li class="md-version__item">

View File

@ -32,26 +32,16 @@
// Modifier to float block elements
.inline {
float: left;
float: inline-start;
width: px2rem(234px);
margin-top: 0;
margin-inline-end: px2rem(16px);
margin-bottom: px2rem(16px);
// Adjust for right-to-left languages
[dir="rtl"] & {
float: right;
}
// Modifier to move to end (ltr: right, rtl: left)
&.end {
float: right;
float: inline-end;
margin-inline: px2rem(16px) 0;
// Adjust for right-to-left languages
[dir="rtl"] & {
float: left;
}
}
}
}

View File

@ -141,6 +141,7 @@ $admonitions: (
height: px2rem(20px);
background-color: $clr-blue-a200;
mask-image: var(--md-admonition-icon--note);
mask-position: center;
mask-repeat: no-repeat;
mask-size: contain;
content: "";
@ -176,8 +177,6 @@ $admonitions: (
&::before {
background-color: $tint;
mask-image: var(--md-admonition-icon--#{$name});
mask-repeat: no-repeat;
mask-size: contain;
}
}
}

View File

@ -128,6 +128,7 @@
height: px2rem(16px);
background-color: currentcolor;
mask-image: var(--md-footnotes-icon);
mask-position: center;
mask-repeat: no-repeat;
mask-size: contain;
content: "";

View File

@ -90,6 +90,7 @@
height: px2rem(20px);
background-color: currentcolor;
mask-image: var(--md-details-icon);
mask-position: center;
mask-repeat: no-repeat;
mask-size: contain;
transform: rotate(0deg);

View File

@ -276,6 +276,7 @@
background-color 250ms,
transform 250ms;
mask-image: var(--md-tabbed-icon--prev);
mask-position: center;
mask-repeat: no-repeat;
mask-size: contain;
content: "";

View File

@ -66,6 +66,7 @@
height: px2em(20px);
background-color: var(--md-default-fg-color--lightest);
mask-image: var(--md-tasklist-icon);
mask-position: center;
mask-repeat: no-repeat;
mask-size: contain;
content: "";

View File

@ -76,6 +76,7 @@
margin: 0 auto;
background-color: currentcolor;
mask-image: var(--md-clipboard-icon);
mask-position: center;
mask-repeat: no-repeat;
mask-size: contain;
content: "";

View File

@ -68,7 +68,7 @@
// Button inside of the content area - these buttons are meant for actions on
// a document-level, i.e. linking to related source code files, printing etc.
&__button {
float: right;
float: inline-end;
margin: px2rem(8px) 0;
margin-inline-start: px2rem(8px);
padding: 0;
@ -78,11 +78,6 @@
display: none;
}
// Adjust for right-to-left languages
[dir="rtl"] & {
float: left;
}
// Adjust default link color for icons
.md-typeset & {
color: var(--md-default-fg-color--lighter);

View File

@ -216,6 +216,7 @@
height: 100%;
background-color: currentcolor;
mask-image: var(--md-nav-icon--prev);
mask-position: center;
mask-repeat: no-repeat;
mask-size: contain;
content: "";
@ -295,6 +296,7 @@
height: 100%;
background-color: currentcolor;
mask-image: var(--md-nav-icon--next);
mask-position: center;
mask-repeat: no-repeat;
mask-size: contain;
content: "";
@ -439,6 +441,13 @@
// Navigation title
&--secondary &__title {
position: sticky;
top: 0;
// Hack: because of the hack that we need to make .md-ellipsis work in
// Safari, we need to set `z-index` here as - see https://bit.ly/3s5M2jm
z-index: 1;
background: var(--md-default-bg-color);
box-shadow: 0 0 px2rem(8px) px2rem(8px) var(--md-default-bg-color);
// Adjust snapping behavior
&[for="__toc"] {
@ -458,6 +467,13 @@
// Navigation title
&--primary &__title {
position: sticky;
top: 0;
// Hack: because of the hack that we need to make .md-ellipsis work in
// Safari, we need to set `z-index` here as - see https://bit.ly/3s5M2jm
z-index: 1;
background: var(--md-default-bg-color);
box-shadow: 0 0 px2rem(8px) px2rem(8px) var(--md-default-bg-color);
// Adjust snapping behavior
&[for="__drawer"] {
@ -524,7 +540,6 @@
// Navigation icon
&__icon {
float: right;
width: px2rem(18px);
height: px2rem(18px);
border-radius: 100%;
@ -534,7 +549,6 @@
// Adjust for right-to-left languages
[dir="rtl"] & {
float: left;
transform: rotate(180deg);
}
@ -551,6 +565,7 @@
vertical-align: px2rem(-2px);
background-color: currentcolor;
mask-image: var(--md-nav-icon--next);
mask-position: center;
mask-repeat: no-repeat;
mask-size: contain;
content: "";
@ -583,10 +598,14 @@
// Show navigation link as title
> .md-nav__link {
position: sticky;
top: 0;
z-index: 1;
margin-top: 0;
padding: 0 px2rem(12px);
font-weight: 700;
pointer-events: none;
background: var(--md-default-bg-color);
box-shadow: 0 0 px2rem(8px) px2rem(8px) var(--md-default-bg-color);
// Make navigation link clickable
&--index [href] {

View File

@ -169,15 +169,10 @@
// [tablet landscape +]: Header-embedded search
@include break-from-device(tablet landscape) {
position: relative;
float: right;
float: inline-end;
width: px2rem(234px);
padding: px2rem(2px) 0;
transition: width 250ms cubic-bezier(0.1, 0.7, 0.1, 1);
// Adjust for right-to-left languages
[dir="rtl"] & {
float: left;
}
}
// Adjust appearance when search is active
@ -647,6 +642,7 @@
height: 100%;
background-color: currentcolor;
mask-image: var(--md-search-result-icon);
mask-position: center;
mask-repeat: no-repeat;
mask-size: contain;
content: "";

View File

@ -38,11 +38,11 @@
display: none;
}
// [tablet -]: Show navigation as drawer
@include break-to-device(tablet) {
// Primary sidebar with navigation
&--primary {
// Primary sidebar with navigation
&--primary {
// [tablet -]: Show navigation as drawer
@include break-to-device(tablet) {
position: fixed;
top: 0;
inset-inline-start: px2rem(-242px);
@ -86,6 +86,11 @@
.no-js & {
height: auto;
}
// Adjust spacing for sticky navigation tabs
.md-header--lifted ~ .md-container & {
top: px2rem(96px);
}
}
// Secondary sidebar with table of contents

View File

@ -148,6 +148,7 @@
margin-inline-end: px2rem(2px);
vertical-align: text-top;
background-color: currentcolor;
mask-position: center;
mask-repeat: no-repeat;
mask-size: contain;
content: "";

View File

@ -24,42 +24,81 @@
// Rules
// ----------------------------------------------------------------------------
// Tag list
.md-tags {
margin-bottom: px2em(12px);
// Tag variables
:root {
--md-tag-icon: svg-load("material/pound.svg");
}
// Tag
.md-tag {
display: inline-block;
margin-inline-end: 0.5em;
margin-bottom: 0.5em;
padding: px2em(4px, 12.8px) px2em(12px, 12.8px);
font-weight: 700;
font-size: px2rem(12.8px);
line-height: 1.6;
background: var(--md-default-fg-color--lightest);
border-radius: px2rem(8px);
// ----------------------------------------------------------------------------
// Linked tag
&[href] {
color: inherit;
outline: none;
-webkit-tap-highlight-color: transparent;
transition:
color 125ms,
background-color 125ms;
// Scoped in typesetted content to match specificity of regular content
.md-typeset {
// Linked tag on focus/hover
&:focus,
&:hover {
color: var(--md-accent-bg-color);
background-color: var(--md-accent-fg-color);
// Tag list
.md-tags {
margin-top: px2em(-2px);
margin-bottom: px2em(12px);
}
// Tag
.md-tag {
display: inline-block;
margin-inline-end: 0.5em;
margin-bottom: 0.5em;
padding: px2em(4px, 12.8px) px2em(12px, 12.8px);
font-weight: 700;
font-size: px2rem(12.8px);
line-height: 1.6;
letter-spacing: initial;
vertical-align: middle;
background: var(--md-default-fg-color--lightest);
border-radius: px2rem(48px);
// Linked tag
&[href] {
color: inherit;
outline: none;
-webkit-tap-highlight-color: transparent;
transition:
color 125ms,
background-color 125ms;
// Linked tag on focus/hover
&:focus,
&:hover {
color: var(--md-accent-bg-color);
background-color: var(--md-accent-fg-color);
}
}
// Tag inside headline
[id] > & {
vertical-align: text-top;
}
}
// Tag inside headline
[id] > & {
vertical-align: text-top;
// Tag icon
.md-tag-icon {
// Tag icon content
&::before {
display: inline-block;
width: 1.2em;
height: 1.2em;
margin-right: 0.4em;
vertical-align: text-bottom;
background-color: var(--md-default-fg-color--lighter);
mask-image: var(--md-tag-icon);
mask-position: center;
mask-repeat: no-repeat;
mask-size: contain;
transition: background-color 125ms;
content: "";
}
// Linked tag on focus/hover
&:is(a:focus, a:hover)::before {
background-color: var(--md-accent-bg-color);
}
}
}

View File

@ -71,8 +71,8 @@
z-index: 0;
width: var(--md-tooltip-width);
max-width: calc(100vw - 2 * #{px2rem(16px)});
max-height: 0;
color: var(--md-default-fg-color);
font-family: var(--md-text-font-family);
background-color: var(--md-default-bg-color);
border-radius: px2rem(2px);
box-shadow: var(--md-shadow-z2);
@ -81,25 +81,23 @@
backface-visibility: hidden;
opacity: 0;
transition:
transform 0ms 250ms,
opacity 250ms,
max-height 0ms 250ms,
z-index 250ms;
transform 0ms 250ms,
opacity 250ms,
z-index 250ms;
// Tooltip on parent focus
:focus-within > & {
max-height: 1000%;
// Active tooltip
&--active {
z-index: 2;
transform: translateY(0);
opacity: 1;
transition:
transform 250ms cubic-bezier(0.1, 0.7, 0.1, 1),
opacity 250ms,
max-height 250ms,
z-index 0ms;
transform 250ms cubic-bezier(0.1, 0.7, 0.1, 1),
opacity 250ms,
z-index 0ms;
}
// Show outline for keyboard devices
.focus-visible > & {
// Show outline on target and for keyboard devices
:is(.focus-visible > &, &:target) {
outline: var(--md-accent-fg-color) auto;
}
@ -124,6 +122,7 @@
// Annotation
.md-annotation {
font-weight: 400;
white-space: normal;
outline: none;
@ -140,40 +139,36 @@
line-height: 1.325;
}
// Promote children to top on focus
&:focus-within > * {
z-index: 2;
}
// Annotation wrapper (= tooltip)
&__inner {
top: calc(var(--md-tooltip-y) + 1.2ch);
font-family: var(--md-text-font-family);
// Annotation tooltip when not focused
:not(:focus-within) > & {
user-select: none;
pointer-events: none;
}
}
// Annotation index
&__index {
position: relative;
z-index: 0;
margin: 0 1ch;
color: hsla(0, 0%, 100%, 1);
font-size: px2em(13.6px, 16px);
font-family: var(--md-code-font-family);
outline: none;
cursor: pointer;
transition: z-index 250ms;
user-select: none;
// Hack: increase specificity to override default for anchors
.md-annotation & {
color: hsla(0, 0%, 100%, 1);
transition: z-index 250ms;
// Text link on focus/hover
&:is(:focus, :hover) {
color: hsla(0, 0%, 100%, 1);
}
}
// Annotation marker the marker must be positioned absolutely behind
// the index, because it shouldn't impact the rendering of a code block.
// Otherwise, small rounding differences in browsers can sometimes mess up
// alignment of text following an annotation.
&::after {
position: absolute;
left: -0.126em;
top: 0;
left: px2em(-2px);
z-index: -1;
// Hack: the first property is used as a fallback for older browsers
// which don't support the min/max/clamp math functions.
@ -198,13 +193,8 @@
}
}
// Annotation marker on focus/hover
:is(:focus-within, :hover) > & {
background-color: var(--md-accent-fg-color);
}
// Annotation marker on focus
:focus-within > & {
// Annotation marker for active tooltip
.md-tooltip--active + & {
transition:
color 250ms,
background-color 250ms;
@ -212,6 +202,29 @@
}
}
// Annotation index in code block
code & {
font-size: inherit;
font-family: var(--md-code-font-family);
}
// Annotation index for active tooltip or on hover
:is(.md-tooltip--active + &, :hover > &) {
color: var(--md-accent-bg-color);
// Annotation marker
&::after {
background-color: var(--md-accent-fg-color);
}
}
// Annotation index for active tooltip
.md-tooltip--active + & {
z-index: 2;
transition: none;
animation: none;
}
// Annotation marker
[data-md-annotation-id] {
display: inline-block;
@ -238,16 +251,5 @@
}
}
}
// Annotation index on focus/hover
:is(:focus-within, :hover) > & {
color: var(--md-accent-bg-color);
}
// Annotation index on focus
:focus-within > & {
transition: none;
animation: none;
}
}
}

View File

@ -69,7 +69,9 @@
margin-inline-start: px2rem(8px);
background-color: currentcolor;
mask-image: var(--md-version-icon);
mask-position: center;
mask-repeat: no-repeat;
mask-size: contain;
content: "";
}
}

View File

@ -125,7 +125,7 @@
{% endblock %}
<!-- Custom style sheets -->
{% for path in config["extra_css"] %}
{% for path in config.extra_css %}
<link rel="stylesheet" href="{{ path | url }}" />
{% endfor %}
@ -137,6 +137,17 @@
{% include "partials/integrations/analytics.html" %}
{% endblock %}
<!-- Meta tags from front matter or plugins -->
{% if page.meta and page.meta.meta %}
{% for tag in page.meta.meta %}
<meta
{% for key, value in tag.items() %}
{{ key }}="{{value}}"
{% endfor %}
/>
{% endfor %}
{% endif %}
<!-- Custom front matter -->
{% block extrahead %}{% endblock %}
</head>
@ -306,16 +317,18 @@
{% endblock %}
<!-- Page content -->
<div class="md-content" data-md-component="content">
<article class="md-content__inner md-typeset">
{% block content %}
{% include "partials/content.html" %}
{% endblock %}
</article>
{% block container %}
<div class="md-content" data-md-component="content">
<article class="md-content__inner md-typeset">
{% block content %}
{% include "partials/content.html" %}
{% endblock %}
</article>
</div>
{% endblock %}
<!-- User preference: content -->
{% include "partials/javascripts/content.html" %}
</div>
<!-- User preference: content -->
{% include "partials/javascripts/content.html" %}
</div>
<!-- Back-to-top button -->
@ -372,6 +385,11 @@
{%- set _ = app.update({ "version": config.extra.version }) -%}
{%- endif -%}
<!-- Tags -->
{%- if config.extra.tags -%}
{%- set _ = app.update({ "tags": config.extra.tags }) -%}
{%- endif -%}
<!-- Translations -->
{%- set translations = app.translations -%}
{%- for key in [
@ -404,7 +422,7 @@
<script src="{{ 'assets/javascripts/bundle.js' | url }}"></script>
<!-- Custom JavaScript -->
{% for path in config["extra_javascript"] %}
{% for path in config.extra_javascript %}
<script src="{{ path | url }}"></script>
{% endfor %}
{% endblock %}

View File

@ -20,8 +20,6 @@
IN THE SOFTWARE.
-->
{% import "partials/language.html" as lang with context %}
<!-- Determine cookies (default to analytics, if present) -->
{% set cookies = config.extra.consent.cookies %}
{% if config.extra.analytics and not cookies %}

View File

@ -26,7 +26,7 @@
{% endif %}
<!-- Determine whether to show feedback -->
{% if page and page.meta and page.meta.hide %}
{% if page.meta and page.meta.hide %}
{% if "feedback" in page.meta.hide %}
{% set feedback = None %}
{% endif %}
@ -62,7 +62,7 @@
{% set url = "/" ~ page.url %}
<!-- Determine title -->
{% if page and page.meta and page.meta.title %}
{% if page.meta and page.meta.title %}
{% set title = page.meta.title | urlencode %}
{% else %}
{% set title = page.title | urlencode %}

View File

@ -135,7 +135,7 @@
{% endif %}
<!-- Button to open search modal -->
{% if "search" in config["plugins"] %}
{% if "search" in config.plugins %}
<label class="md-header__button md-icon" for="__search">
{% include ".icons/material/magnify.svg" %}
</label>

View File

@ -35,3 +35,24 @@
{% set _ = style.append("}\x3c/style\x3e") %}
{{ style | join }}
{% endif %}
<!-- Custom tag icons -->
{% if config.theme.icon.tag %}
{% set style = ["\x3cstyle\x3e"] %}
{% for type, icon in config.theme.icon.tag.items() %}
{% import ".icons/" ~ icon ~ ".svg" as icon %}
{% if type != "default" %}
{% set modifier = "--" ~ type %}
{% endif %}
{% set _ = style.append(
".md-tag-icon" ~ modifier ~ "{" ~
"--md-tag-icon:" ~
"url('data:image/svg+xml;charset=utf-8," ~
icon | replace("\n", "") ~
"');" ~
"}"
) %}
{% endfor %}
{% set _ = style.append("\x3c/style\x3e") %}
{{ style | join }}
{% endif %}

View File

@ -32,8 +32,11 @@
"edit.link.title": "Seite editieren",
"footer.previous": "Zurück",
"footer.next": "Weiter",
"footer.title": "Fußzeile",
"header.title": "Kopfzeile",
"meta.comments": "Kommentare",
"meta.source": "Quellcode",
"nav.title": "Navigation",
"search.config.lang": "de",
"search.placeholder": "Suche",
"search.share": "Teilen",
@ -50,9 +53,10 @@
"select.language.title": "Sprache wechseln",
"select.version.title": "Version auswählen",
"skip.link.title": "Zum Inhalt",
"source.link.title": "Quellcode",
"source.link.title": "Zum Repository",
"source.file.date.updated": "Letztes Update",
"source.file.date.created": "Erstellt",
"tabs.title": "Hauptnavigation",
"toc.title": "Inhaltsverzeichnis",
"top.title": "Zurück zum Seitenanfang"
}[key] }}{% endmacro %}

View File

@ -58,6 +58,7 @@
<a
href="javascript:void(0)"
class="md-search__icon md-icon"
title="{{ lang.t('search.share') }}"
aria-label="{{ lang.t('search.share') }}"
data-clipboard
data-clipboard-text=""
@ -72,6 +73,7 @@
<button
type="reset"
class="md-search__icon md-icon"
title="{{ lang.t('search.reset') }}"
aria-label="{{ lang.t('search.reset') }}"
tabindex="-1"
>

View File

@ -29,12 +29,24 @@
{% if tags %}
<nav class="md-tags" {{ hidden }}>
{% for tag in tags %}
{% if config.extra.tags %}
{% set icon = " md-tag-icon" %}
{% if tag.type %}
{% set icon = icon ~ " md-tag-icon--" ~ tag.type %}
{% endif %}
{% endif %}
<!-- Render tag with link -->
{% if tag.url %}
<a href="{{ tag.url | url }}" class="md-tag">
{{ tag.name }}
<a href="{{ tag.url | url }}" class="md-tag{{ icon }}">
{{- tag.name -}}
</a>
<!-- Render tag without link -->
{% else %}
<span class="md-tag">{{ tag.name }}</span>
<span class="md-tag{{ icon }}">
{{- tag.name -}}
</span>
{% endif %}
{% endfor %}
</nav>

View File

View File

@ -0,0 +1,398 @@
# Copyright (c) 2016-2022 Martin Donath <martin.donath@squidfunk.com>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import os
import re
import requests
from cairosvg import svg2png
from collections import defaultdict
from hashlib import md5
from io import BytesIO
from mkdocs.config.config_options import Deprecated, Type
from mkdocs.plugins import BasePlugin
from PIL import Image, ImageDraw, ImageFont
from shutil import copyfile
from tempfile import TemporaryFile
from zipfile import ZipFile
# -----------------------------------------------------------------------------
# Class
# -----------------------------------------------------------------------------
# Social plugin
class SocialPlugin(BasePlugin):
# Configuration scheme
config_scheme = (
("enabled", Type(bool, default = True)),
("cache_dir", Type(str, default = ".cache/plugin/social")),
# Options for social cards
("cards", Type(bool, default = True)),
("cards_dir", Type(str, default = "assets/images/social")),
("cards_color", Type(dict, default = {})),
("cards_font", Type(str, default = None)),
# Deprecated options
("cards_directory", Deprecated(moved_to = "cards_dir")),
)
# Retrieve configuration
def on_config(self, config):
self.color = colors.get("indigo")
if not self.config["cards"]:
return
# Ensure presence of cache directory
self.cache = self.config["cache_dir"]
if not os.path.isdir(self.cache):
os.makedirs(self.cache)
# Retrieve palette from theme configuration
theme = config["theme"]
if "palette" in theme:
palette = theme["palette"]
# Use first palette, if multiple are defined
if isinstance(palette, list):
palette = palette[0]
# Set colors according to palette
if "primary" in palette and palette["primary"]:
primary = palette["primary"].replace(" ", "-")
self.color = colors.get(primary, self.color)
# Retrieve color overrides
self.color = { **self.color, **self.config["cards_color"] }
# Retrieve logo and font
self.logo = self._load_logo(config)
self.font = self._load_font(config)
# Create social cards
def on_page_markdown(self, markdown, page, config, files):
if not self.config["cards"]:
return
# Resolve image directory
directory = self.config["cards_dir"]
file, _ = os.path.splitext(page.file.src_path)
# Resolve path of image
path = "{}.png".format(os.path.join(
config["site_dir"],
directory,
file
))
# Resolve path of image directory
directory = os.path.dirname(path)
if not os.path.isdir(directory):
os.makedirs(directory)
# Compute site name
site_name = config.get("site_name")
# Compute page title and description
title = page.meta.get("title", page.title)
description = config.get("site_description") or ""
if "description" in page.meta:
description = page.meta["description"]
# Generate social card if not in cache - TODO: values from mkdocs.yml
hash = md5("".join([
site_name,
str(title),
description
]).encode("utf-8"))
file = os.path.join(self.cache, f"{hash.hexdigest()}.png")
if not os.path.isfile(file):
image = self._render_card(site_name, title, description)
image.save(file)
# Copy file from cache
copyfile(file, path)
# Inject meta tags into page
meta = page.meta.get("meta", [])
page.meta["meta"] = meta + self._generate_meta(page, config)
# -------------------------------------------------------------------------
# Render social card
def _render_card(self, site_name, title, description):
logo = self.logo
# Render background and logo
image = self._render_card_background((1200, 630), self.color["fill"])
image.alpha_composite(
logo.resize((144, int(144 * logo.height / logo.width))),
(1200 - 228, 64 - 4)
)
# Render site name
font = ImageFont.truetype(self.font["Bold"], 36)
image.alpha_composite(
self._render_text((826, 48), font, site_name, 1, 20),
(64 + 4, 64)
)
# Render page title
font = ImageFont.truetype(self.font["Bold"], 92)
image.alpha_composite(
self._render_text((826, 328), font, title, 3, 30),
(64, 160)
)
# Render page description
font = ImageFont.truetype(self.font["Regular"], 28)
image.alpha_composite(
self._render_text((826, 80), font, description, 2, 14),
(64 + 4, 512)
)
# Return social card image
return image
# Render social card background
def _render_card_background(self, size, fill):
return Image.new(mode = "RGBA", size = size, color = fill)
# Render social card text
def _render_text(self, size, font, text, lmax, spacing = 0):
lines, words = [], []
# Remove remnant HTML tags
text = re.sub(r"(<[^>]+>)", "", text)
# Create temporary image
image = Image.new(mode = "RGBA", size = size)
# Retrieve y-offset of textbox to correct for spacing
yoffset = 0
# Create drawing context and split text into lines
context = ImageDraw.Draw(image)
for word in text.split(" "):
combine = " ".join(words + [word])
textbox = context.textbbox((0, 0), combine, font = font)
yoffset = textbox[1]
if not words or textbox[2] <= image.width:
words.append(word)
else:
lines.append(words)
words = [word]
# # Balance words on last line - TODO: overflows when broken word is too long
# if len(lines) > 0:
# prev = len(" ".join(lines[-1]))
# last = len(" ".join(words))#
# print(last, prev)
# # Heuristic: try to find a good ratio
# if last / prev < 0.6:
# words.insert(0, lines[-1].pop())
# Join words for each line and create image
lines.append(words)
lines = [" ".join(line) for line in lines]
image = Image.new(mode = "RGBA", size = size)
# Create drawing context and split text into lines
context = ImageDraw.Draw(image)
context.text(
(0, spacing / 2 - yoffset), "\n".join(lines[:lmax]),
font = font, fill = self.color["text"], spacing = spacing - yoffset
)
# Return text image
return image
# -------------------------------------------------------------------------
# Generate meta tags
def _generate_meta(self, page, config):
directory = self.config["cards_dir"]
file, _ = os.path.splitext(page.file.src_path)
# Compute page title
title = page.meta.get("title", page.title)
if not page.is_homepage:
title = f"{title} - {config.get('site_name')}"
# Compute page description
description = config.get("site_description")
if "description" in page.meta:
description = page.meta["description"]
# Resolve image URL
url = "{}.png".format(os.path.join(
config.get("site_url"),
directory,
file
))
# Ensure forward slashes
url = url.replace(os.path.sep, "/")
# Return meta tags
return [
# Meta tags for Open Graph
{ "property": "og:type", "content": "website" },
{ "property": "og:title", "content": title },
{ "property": "og:description", "content": description },
{ "property": "og:image", "content": url },
{ "property": "og:image:type", "content": "image/png" },
{ "property": "og:image:width", "content": "1200" },
{ "property": "og:image:height", "content": "630" },
{ "property": "og:url", "content": page.canonical_url },
# Meta tags for Twitter
{ "name": "twitter:card", "content": "summary_large_image" },
# { "name": "twitter:site", "content": user },
# { "name": "twitter:creator", "content": user },
{ "name": "twitter:title", "content": title },
{ "name": "twitter:description", "content": description },
{ "name": "twitter:image", "content": url }
]
# Retrieve logo image or icon
def _load_logo(self, config):
theme = config.get("theme")
# Handle images (precedence over icons)
if "logo" in theme:
_, extension = os.path.splitext(theme["logo"])
# Load SVG and convert to PNG
path = os.path.join(config["docs_dir"], theme["logo"])
if extension == ".svg":
return self._load_logo_svg(path)
# Load PNG, JPEG, etc.
return Image.open(path).convert("RGBA")
# Handle icons
logo = "material/library"
icon = theme["icon"] or {}
if "logo" in icon and icon["logo"]:
logo = icon["logo"]
# Resolve path of package
base = os.path.abspath(os.path.join(
os.path.dirname(__file__),
"../.."
))
# Load icon data and fill with color
path = f"{base}/.icons/{logo}.svg"
return self._load_logo_svg(path, self.color["text"])
# Load SVG file and convert to PNG
def _load_logo_svg(self, path, fill = None):
file = BytesIO()
data = open(path).read()
# Fill with color, if given
if fill:
data = data.replace("<svg", f"<svg fill=\"{fill}\"")
# Convert to PNG and return image
svg2png(bytestring = data, write_to = file, scale = 10)
return Image.open(file)
# Retrieve font
def _load_font(self, config):
name = self.config.get("cards_font")
if not name:
# Retrieve from theme (default: Roboto)
theme = config["theme"]
if theme["font"]:
name = theme["font"]["text"]
else:
name = "Roboto"
# Retrieve font files, if not already done
files = os.listdir(self.cache)
files = [file for file in files if file.endswith(".ttf") or file.endswith(".otf")] or (
self._load_font_from_google(name)
)
# Map available font weights to file paths
font = dict()
for file in files:
match = re.search("-(\w+)\.[ot]tf$", file)
if match:
font[match.group(1)] = os.path.join(self.cache, file)
# Return available font weights with fallback
return defaultdict(lambda: font["Regular"], font)
# Retrieve font from Google Fonts
def _load_font_from_google(self, name):
url = "https://fonts.google.com/download?family={}"
res = requests.get(url.format(name.replace(" ", "+")), stream = True)
# Write archive to temporary file
tmp = TemporaryFile()
for chunk in res.iter_content(chunk_size = 128):
tmp.write(chunk)
# Unzip fonts from temporary file
zip = ZipFile(tmp)
files = [file for file in zip.namelist() if file.endswith(".ttf") or file.endswith(".otf")]
zip.extractall(self.cache, files)
# Close and delete temporary file
tmp.close()
return files
# -----------------------------------------------------------------------------
# Data
# -----------------------------------------------------------------------------
# Color palette
colors = dict({
"red": { "fill": "#ef5552", "text": "#ffffff" },
"pink": { "fill": "#e92063", "text": "#ffffff" },
"purple": { "fill": "#ab47bd", "text": "#ffffff" },
"deep-purple": { "fill": "#7e56c2", "text": "#ffffff" },
"indigo": { "fill": "#4051b5", "text": "#ffffff" },
"blue": { "fill": "#2094f3", "text": "#ffffff" },
"light-blue": { "fill": "#02a6f2", "text": "#ffffff" },
"cyan": { "fill": "#00bdd6", "text": "#ffffff" },
"teal": { "fill": "#009485", "text": "#ffffff" },
"green": { "fill": "#4cae4f", "text": "#ffffff" },
"light-green": { "fill": "#8bc34b", "text": "#ffffff" },
"lime": { "fill": "#cbdc38", "text": "#000000" },
"yellow": { "fill": "#ffec3d", "text": "#000000" },
"amber": { "fill": "#ffc105", "text": "#000000" },
"orange": { "fill": "#ffa724", "text": "#000000" },
"deep-orange": { "fill": "#ff6e42", "text": "#ffffff" },
"brown": { "fill": "#795649", "text": "#ffffff" },
"grey": { "fill": "#757575", "text": "#ffffff" },
"blue-grey": { "fill": "#546d78", "text": "#ffffff" },
"black": { "fill": "#000000", "text": "#ffffff" },
"white": { "fill": "#ffffff", "text": "#000000" }
})

View File

@ -42,92 +42,106 @@ class TagsPlugin(BasePlugin):
)
# Initialize plugin
def __init__(self):
def on_config(self, config):
self.tags = defaultdict(list)
self.tags_file = None
self.slugify = None
# Retrieve configuration for anchor generation
def on_config(self, config):
if "toc" in config["markdown_extensions"]:
toc = { "slugify": slugify, "separator": "-" }
if "toc" in config["mdx_configs"]:
toc = { **toc, **config["mdx_configs"]["toc"] }
# Retrieve tags mapping from configuration
self.tags_map = config["extra"].get("tags")
# Partially apply slugify function
self.slugify = lambda value: (
toc["slugify"](str(value), toc["separator"])
)
# Use override of slugify function
toc = { "slugify": slugify, "separator": "-" }
if "toc" in config["mdx_configs"]:
toc = { **toc, **config["mdx_configs"]["toc"] }
# Hack: 2nd pass for tags index page
def on_nav(self, nav, files, **kwargs):
# Partially apply slugify function
self.slugify = lambda value: (
toc["slugify"](str(value), toc["separator"])
)
# Hack: 2nd pass for tags index page(s)
def on_nav(self, nav, config, files):
file = self.config.get("tags_file")
if file:
self.tags_file = files.get_file_from_path(file)
if not self.tags_file:
log.error(f"Configuration error: {file} doesn't exist.")
sys.exit()
# Add tags file to files
files.append(self.tags_file)
self.tags_file = self._get_tags_file(files, file)
# Build and render tags index page
def on_page_markdown(self, markdown, page, **kwargs):
def on_page_markdown(self, markdown, page, config, files):
if page.file == self.tags_file:
return self.__render_tag_index(markdown)
return self._render_tag_index(markdown)
# Add page to tags index
for tag in page.meta.get("tags", []):
self.tags[tag].append(page)
# Inject tags into page (after search and before minification)
def on_page_context(self, context, page, **kwargs):
def on_page_context(self, context, page, config, nav):
if "tags" in page.meta:
context["tags"] = [
self.__render_tag(tag)
self._render_tag(tag)
for tag in page.meta["tags"]
]
# -------------------------------------------------------------------------
# Obtain tags file
def _get_tags_file(self, files, path):
file = files.get_file_from_path(path)
if not file:
log.error(f"Tags file '{path}' does not exist.")
sys.exit()
# Add tags file to files
files.append(file)
return file
# Render tags index
def __render_tag_index(self, markdown):
def _render_tag_index(self, markdown):
if not "[TAGS]" in markdown:
markdown += "\n[TAGS]"
# Replace placeholder in Markdown with rendered tags index
return markdown.replace("[TAGS]", "\n".join([
self.__render_tag_links(*args)
self._render_tag_links(*args)
for args in sorted(self.tags.items())
]))
# Render the given tag and links to all pages with occurrences
def __render_tag_links(self, tag, pages):
content = [f"## <span class=\"md-tag\">{tag}</span>", ""]
def _render_tag_links(self, tag, pages):
classes = ["md-tag"]
if isinstance(self.tags_map, dict):
classes.append("md-tag-icon")
type = self.tags_map.get(tag)
if type:
classes.append(f"md-tag-icon--{type}")
# Render section for tag and a link to each page
classes = " ".join(classes)
content = [f"## <span class=\"{classes}\">{tag}</span>", ""]
for page in pages:
# Ensure forward slashes, as we have to use the path of the source
# file which contains the operating system's path separator.
url = utils.get_relative_url(
page.file.src_path.replace(os.path.sep, "/"),
self.tags_file.src_path.replace(os.path.sep, "/")
)
# Ensure forward slashes, as we have to use the path of the source
# file which contains the operating system's path separator.
content.append("- [{}]({})".format(
page.meta.get("title", page.title),
url
))
# Render link to page
title = page.meta.get("title", page.title)
content.append(f"- [{title}]({url})")
# Return rendered tag links
return "\n".join(content)
# Render the given tag, linking to the tags index (if enabled)
def __render_tag(self, tag):
def _render_tag(self, tag):
type = self.tags_map.get(tag) if self.tags_map else None
if not self.tags_file or not self.slugify:
return dict(name = tag)
return dict(name = tag, type = type)
else:
url = self.tags_file.url
url += f"#{self.slugify(tag)}"
return dict(name = tag, url = url)
url = f"{self.tags_file.url}#{self.slugify(tag)}"
return dict(name = tag, type = type, url = url)
# -----------------------------------------------------------------------------
# Data

View File

@ -25,10 +25,10 @@ import * as path from "path"
import {
EMPTY,
concat,
concatMap,
defer,
map,
merge,
mergeMap,
of,
reduce,
scan,
@ -162,7 +162,7 @@ const sources$ = copyAll("**/*.py", {
/* Transform styles */
const stylesheets$ = resolve("**/[!_]*.scss", { cwd: "src" })
.pipe(
concatMap(file => zip(
mergeMap(file => zip(
of(ext(file, ".css")),
transformStyle({
from: `src/${file}`,
@ -174,7 +174,7 @@ const stylesheets$ = resolve("**/[!_]*.scss", { cwd: "src" })
/* Transform scripts */
const javascripts$ = resolve("**/{bundle,search}.ts", { cwd: "src" })
.pipe(
concatMap(file => zip(
mergeMap(file => zip(
of(ext(file, ".js")),
transformScript({
from: `src/${file}`,