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 upgrade --update-cache -a \
&& \ && \
apk add --no-cache \ apk add --no-cache \
cairo \
freetype-dev \
git \ git \
git-fast-import \ git-fast-import \
jpeg-dev \
openssh \ openssh \
zlib-dev \
&& \ && \
apk add --no-cache --virtual .build \ apk add --no-cache --virtual .build \
gcc \ gcc \
libffi-dev \
musl-dev \ musl-dev \
&& \ && \
pip install --no-cache-dir . \ 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 %} {% endif %}
{% endblock %} {% endblock %}
{% block styles %} {% 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 %} {% if config.theme.palette %}
{% set palette = config.theme.palette %} {% set palette = config.theme.palette %}
<link rel="stylesheet" href="{{ 'assets/stylesheets/palette.cbb835fc.min.css' | url }}"> <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> <style>:root{--md-text-font:"{{ text }}";--md-code-font:"{{ code }}"}</style>
{% endif %} {% endif %}
{% endblock %} {% endblock %}
{% for path in config["extra_css"] %} {% for path in config.extra_css %}
<link rel="stylesheet" href="{{ path | url }}"> <link rel="stylesheet" href="{{ path | url }}">
{% endfor %} {% endfor %}
{% include "partials/javascripts/base.html" %} {% include "partials/javascripts/base.html" %}
{% block analytics %} {% block analytics %}
{% include "partials/integrations/analytics.html" %} {% include "partials/integrations/analytics.html" %}
{% endblock %} {% 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 %} {% block extrahead %}{% endblock %}
</head> </head>
{% set direction = config.theme.direction or lang.t('direction') %} {% set direction = config.theme.direction or lang.t('direction') %}
@ -167,14 +172,16 @@
</div> </div>
{% endif %} {% endif %}
{% endblock %} {% endblock %}
<div class="md-content" data-md-component="content"> {% block container %}
<article class="md-content__inner md-typeset"> <div class="md-content" data-md-component="content">
{% block content %} <article class="md-content__inner md-typeset">
{% include "partials/content.html" %} {% block content %}
{% endblock %} {% include "partials/content.html" %}
</article> {% endblock %}
{% include "partials/javascripts/content.html" %} </article>
</div> </div>
{% endblock %}
{% include "partials/javascripts/content.html" %}
</div> </div>
{% if "navigation.top" in features %} {% if "navigation.top" in features %}
<a href="#" class="md-top md-icon" data-md-component="top" hidden> <a href="#" class="md-top md-icon" data-md-component="top" hidden>
@ -211,6 +218,9 @@
{%- if config.extra.version -%} {%- if config.extra.version -%}
{%- set _ = app.update({ "version": config.extra.version }) -%} {%- set _ = app.update({ "version": config.extra.version }) -%}
{%- endif -%} {%- endif -%}
{%- if config.extra.tags -%}
{%- set _ = app.update({ "tags": config.extra.tags }) -%}
{%- endif -%}
{%- set translations = app.translations -%} {%- set translations = app.translations -%}
{%- for key in [ {%- for key in [
"clipboard.copy", "clipboard.copy",
@ -235,8 +245,8 @@
</script> </script>
{% endblock %} {% endblock %}
{% block scripts %} {% block scripts %}
<script src="{{ 'assets/javascripts/bundle.2ab50757.min.js' | url }}"></script> <script src="{{ 'assets/javascripts/bundle.e93b4713.min.js' | url }}"></script>
{% for path in config["extra_javascript"] %} {% for path in config.extra_javascript %}
<script src="{{ path | url }}"></script> <script src="{{ path | url }}"></script>
{% endfor %} {% endfor %}
{% endblock %} {% endblock %}

View File

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

View File

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

View File

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

View File

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

View File

@ -15,3 +15,22 @@
{% set _ = style.append("}\x3c/style\x3e") %} {% set _ = style.append("}\x3c/style\x3e") %}
{{ style | join }} {{ style | join }}
{% endif %} {% 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", "edit.link.title": "Seite editieren",
"footer.previous": "Zurück", "footer.previous": "Zurück",
"footer.next": "Weiter", "footer.next": "Weiter",
"footer.title": "Fußzeile",
"header.title": "Kopfzeile",
"meta.comments": "Kommentare", "meta.comments": "Kommentare",
"meta.source": "Quellcode", "meta.source": "Quellcode",
"nav.title": "Navigation",
"search.config.lang": "de", "search.config.lang": "de",
"search.placeholder": "Suche", "search.placeholder": "Suche",
"search.share": "Teilen", "search.share": "Teilen",
@ -30,9 +33,10 @@
"select.language.title": "Sprache wechseln", "select.language.title": "Sprache wechseln",
"select.version.title": "Version auswählen", "select.version.title": "Version auswählen",
"skip.link.title": "Zum Inhalt", "skip.link.title": "Zum Inhalt",
"source.link.title": "Quellcode", "source.link.title": "Zum Repository",
"source.file.date.updated": "Letztes Update", "source.file.date.updated": "Letztes Update",
"source.file.date.created": "Erstellt", "source.file.date.created": "Erstellt",
"tabs.title": "Hauptnavigation",
"toc.title": "Inhaltsverzeichnis", "toc.title": "Inhaltsverzeichnis",
"top.title": "Zurück zum Seitenanfang" "top.title": "Zurück zum Seitenanfang"
}[key] }}{% endmacro %} }[key] }}{% endmacro %}

View File

@ -12,11 +12,11 @@
</label> </label>
<nav class="md-search__options" aria-label="{{ lang.t('search.title') }}"> <nav class="md-search__options" aria-label="{{ lang.t('search.title') }}">
{% if "search.share" in features %} {% 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" %} {% include ".icons/material/share-variant.svg" %}
</a> </a>
{% endif %} {% 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" %} {% include ".icons/material/close.svg" %}
</button> </button>
</nav> </nav>

View File

@ -7,12 +7,20 @@
{% if tags %} {% if tags %}
<nav class="md-tags" {{ hidden }}> <nav class="md-tags" {{ hidden }}>
{% for tag in tags %} {% 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 %} {% if tag.url %}
<a href="{{ tag.url | url }}" class="md-tag"> <a href="{{ tag.url | url }}" class="md-tag{{ icon }}">
{{ tag.name }} {{- tag.name -}}
</a> </a>
{% else %} {% else %}
<span class="md-tag">{{ tag.name }}</span> <span class="md-tag{{ icon }}">
{{- tag.name -}}
</span>
{% endif %} {% endif %}
{% endfor %} {% endfor %}
</nav> </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 # Initialize plugin
def __init__(self): def on_config(self, config):
self.tags = defaultdict(list) self.tags = defaultdict(list)
self.tags_file = None self.tags_file = None
self.slugify = None
# Retrieve configuration for anchor generation # Retrieve tags mapping from configuration
def on_config(self, config): self.tags_map = config["extra"].get("tags")
if "toc" in config["markdown_extensions"]:
toc = { "slugify": slugify, "separator": "-" }
if "toc" in config["mdx_configs"]:
toc = { **toc, **config["mdx_configs"]["toc"] }
# Partially apply slugify function # Use override of slugify function
self.slugify = lambda value: ( toc = { "slugify": slugify, "separator": "-" }
toc["slugify"](str(value), toc["separator"]) if "toc" in config["mdx_configs"]:
) toc = { **toc, **config["mdx_configs"]["toc"] }
# Hack: 2nd pass for tags index page # Partially apply slugify function
def on_nav(self, nav, files, **kwargs): 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") file = self.config.get("tags_file")
if file: if file:
self.tags_file = files.get_file_from_path(file) self.tags_file = self._get_tags_file(files, 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)
# Build and render tags index page # 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: if page.file == self.tags_file:
return self.__render_tag_index(markdown) return self._render_tag_index(markdown)
# Add page to tags index # Add page to tags index
for tag in page.meta.get("tags", []): for tag in page.meta.get("tags", []):
self.tags[tag].append(page) self.tags[tag].append(page)
# Inject tags into page (after search and before minification) # 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: if "tags" in page.meta:
context["tags"] = [ context["tags"] = [
self.__render_tag(tag) self._render_tag(tag)
for tag in page.meta["tags"] 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 # Render tags index
def __render_tag_index(self, markdown): def _render_tag_index(self, markdown):
if not "[TAGS]" in markdown: if not "[TAGS]" in markdown:
markdown += "\n[TAGS]" markdown += "\n[TAGS]"
# Replace placeholder in Markdown with rendered tags index # Replace placeholder in Markdown with rendered tags index
return markdown.replace("[TAGS]", "\n".join([ return markdown.replace("[TAGS]", "\n".join([
self.__render_tag_links(*args) self._render_tag_links(*args)
for args in sorted(self.tags.items()) for args in sorted(self.tags.items())
])) ]))
# Render the given tag and links to all pages with occurrences # Render the given tag and links to all pages with occurrences
def __render_tag_links(self, tag, pages): def _render_tag_links(self, tag, pages):
content = [f"## <span class=\"md-tag\">{tag}</span>", ""] 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: 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( url = utils.get_relative_url(
page.file.src_path.replace(os.path.sep, "/"), page.file.src_path.replace(os.path.sep, "/"),
self.tags_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 # Render link to page
# file which contains the operating system's path separator. title = page.meta.get("title", page.title)
content.append("- [{}]({})".format( content.append(f"- [{title}]({url})")
page.meta.get("title", page.title),
url
))
# Return rendered tag links # Return rendered tag links
return "\n".join(content) return "\n".join(content)
# Render the given tag, linking to the tags index (if enabled) # 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: if not self.tags_file or not self.slugify:
return dict(name = tag) return dict(name = tag, type = type)
else: else:
url = self.tags_file.url url = f"{self.tags_file.url}#{self.slugify(tag)}"
url += f"#{self.slugify(tag)}" return dict(name = tag, type = type, url = url)
return dict(name = tag, url = url)
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
# Data # Data

View File

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

View File

@ -18,10 +18,15 @@
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE. # IN THE SOFTWARE.
# Direct dependencies # Requirements for core
jinja2>=3.0.2 jinja2>=3.0.2
markdown>=3.2 markdown>=3.2
mkdocs>=1.3.0 mkdocs>=1.3.0
mkdocs-material-extensions>=1.0.3 mkdocs-material-extensions>=1.0.3
pygments>=2.12 pygments>=2.12
pymdown-extensions>=9.4 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": [ "mkdocs.plugins": [
"search = material.plugins.search.plugin:SearchPlugin", "search = material.plugins.search.plugin:SearchPlugin",
"social = material.plugins.social.plugin:SocialPlugin",
"tags = material.plugins.tags.plugin:TagsPlugin" "tags = material.plugins.tags.plugin:TagsPlugin"
] ]
}, },

View File

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

View File

@ -1,5 +1,6 @@
{ {
"rules": { "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 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 */ /* Code blocks */
...getElements("pre:not(.mermaid) > code", el) ...getElements("pre:not(.mermaid) > code", el)
.map(child => mountCodeBlock(child, { print$ })), .map(child => mountCodeBlock(child, { target$, print$ })),
/* Mermaid diagrams */ /* Mermaid diagrams */
...getElements("pre.mermaid", el) ...getElements("pre.mermaid", el)

View File

@ -21,26 +21,31 @@
*/ */
import { import {
EMPTY,
Observable, Observable,
Subject, Subject,
animationFrameScheduler, animationFrameScheduler,
auditTime,
combineLatest, combineLatest,
debounceTime,
defer, defer,
delay,
filter,
finalize, finalize,
fromEvent, fromEvent,
map, map,
merge,
switchMap, switchMap,
take, take,
takeLast, takeLast,
takeUntil, takeUntil,
tap, tap,
throttleTime throttleTime,
withLatestFrom
} from "rxjs" } from "rxjs"
import { import {
ElementOffset, ElementOffset,
getElement, getActiveElement,
getElementSize, getElementSize,
watchElementContentOffset, watchElementContentOffset,
watchElementFocus, watchElementFocus,
@ -62,6 +67,17 @@ export interface Annotation {
offset: ElementOffset /* Annotation offset */ offset: ElementOffset /* Annotation offset */
} }
/* ----------------------------------------------------------------------------
* Helper types
* ------------------------------------------------------------------------- */
/**
* Mount options
*/
interface MountOptions {
target$: Observable<HTMLElement> /* Location target observable */
}
/* ---------------------------------------------------------------------------- /* ----------------------------------------------------------------------------
* Functions * Functions
* ------------------------------------------------------------------------- */ * ------------------------------------------------------------------------- */
@ -82,11 +98,11 @@ export function watchAnnotation(
watchElementContentOffset(container) watchElementContentOffset(container)
])) ]))
.pipe( .pipe(
map(([{ x, y }, scroll]) => { map(([{ x, y }, scroll]): ElementOffset => {
const { width } = getElementSize(el) const { width, height } = getElementSize(el)
return ({ return ({
x: x - scroll.x + width / 2, 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 el - Annotation element
* @param container - Containing element * @param container - Containing element
* @param options - Options
* *
* @returns Annotation component observable * @returns Annotation component observable
*/ */
export function mountAnnotation( export function mountAnnotation(
el: HTMLElement, container: HTMLElement el: HTMLElement, container: HTMLElement, { target$ }: MountOptions
): Observable<Component<Annotation>> { ): Observable<Component<Annotation>> {
const [tooltip, index] = Array.from(el.children)
/* Mount component on subscription */
return defer(() => { return defer(() => {
const push$ = new Subject<Annotation>() const push$ = new Subject<Annotation>()
const done$ = push$.pipe(takeLast(1))
push$.subscribe({ push$.subscribe({
/* Handle emission */ /* Handle emission */
@ -132,7 +153,6 @@ export function mountAnnotation(
}) })
/* Start animation only when annotation is visible */ /* Start animation only when annotation is visible */
const done$ = push$.pipe(takeLast(1))
watchElementVisibility(el) watchElementVisibility(el)
.pipe( .pipe(
takeUntil(done$) takeUntil(done$)
@ -141,11 +161,42 @@ export function mountAnnotation(
el.toggleAttribute("data-md-visible", visible) 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 */ /* Track relative origin of tooltip */
push$ push$
.pipe( .pipe(
throttleTime(500, animationFrameScheduler), throttleTime(125, animationFrameScheduler),
map(() => container.getBoundingClientRect()), filter(() => !!el.offsetParent),
map(() => el.offsetParent!.getBoundingClientRect()),
map(({ x }) => x) map(({ x }) => x)
) )
.subscribe({ .subscribe({
@ -164,15 +215,47 @@ export function mountAnnotation(
} }
}) })
/* Close open annotation on click */ /* Allow to copy link without scrolling to anchor */
const index = getElement(":scope > :last-child", el) fromEvent<MouseEvent>(index, "click")
const blur$ = fromEvent(index, "mousedown", { once: true })
push$
.pipe( .pipe(
switchMap(({ active }) => active ? blur$ : EMPTY), takeUntil(done$),
tap(ev => ev.preventDefault()) 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 */ /* Create and return component */
return watchAnnotation(el, container) return watchAnnotation(el, container)

View File

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

View File

@ -34,8 +34,6 @@ import {
mergeWith, mergeWith,
switchMap, switchMap,
take, take,
takeLast,
takeUntil,
tap tap
} from "rxjs" } from "rxjs"
@ -72,6 +70,7 @@ export interface CodeBlock {
* Mount options * Mount options
*/ */
interface MountOptions { interface MountOptions {
target$: Observable<HTMLElement> /* Location target observable */
print$: Observable<boolean> /* Media print 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 let sequence = 0
@ -147,6 +146,11 @@ export function watchCodeBlock(
* Furthermore, if code annotations are enabled, they are mounted if and only * 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. * 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 el - Code block element
* @param options - Options * @param options - Options
* *
@ -198,7 +202,6 @@ export function mountCodeBlock(
mergeWith( mergeWith(
watchElementSize(container) watchElementSize(container)
.pipe( .pipe(
takeUntil(push$.pipe(takeLast(1))),
map(({ width, height }) => width && height), map(({ width, height }) => width && height),
distinctUntilChanged(), distinctUntilChanged(),
switchMap(active => active ? annotations$ : EMPTY) switchMap(active => active ? annotations$ : EMPTY)
@ -217,11 +220,15 @@ export function mountCodeBlock(
) )
}) })
/* Mount code block on first sight */ /* Mount code block lazily */
return watchElementVisibility(el) if (feature("content.lazy"))
.pipe( return watchElementVisibility(el)
filter(visible => visible), .pipe(
take(1), filter(visible => visible),
switchMap(() => factory$) take(1),
) switchMap(() => factory$)
)
/* Mount code block */
return factory$
} }

View File

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

View File

@ -30,6 +30,8 @@ import {
distinctUntilChanged, distinctUntilChanged,
finalize, finalize,
map, map,
observeOn,
take,
tap, tap,
withLatestFrom withLatestFrom
} from "rxjs" } from "rxjs"
@ -37,7 +39,10 @@ import {
import { import {
Viewport, Viewport,
getElement, getElement,
getElementOffset getElementContainer,
getElementOffset,
getElementSize,
getElements
} from "~/browser" } from "~/browser"
import { Component } from "../_" 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 */ /* Create and return component */
return watchSidebar(el, options) return watchSidebar(el, options)
.pipe( .pipe(

View File

@ -29,8 +29,10 @@ import {
defer, defer,
distinctUntilChanged, distinctUntilChanged,
distinctUntilKeyChanged, distinctUntilKeyChanged,
filter,
finalize, finalize,
map, map,
merge,
of, of,
repeat, repeat,
scan, scan,
@ -48,6 +50,8 @@ import { feature } from "~/_"
import { import {
Viewport, Viewport,
getElement, getElement,
getElementContainer,
getElementSize,
getElements, getElements,
getLocation, getLocation,
getOptionalElement, 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 */ /* Set up anchor tracking, if enabled */
if (feature("navigation.tracking")) if (feature("navigation.tracking"))
viewport$ viewport$

View File

@ -22,26 +22,44 @@
import { h } from "~/utilities" import { h } from "~/utilities"
import { renderTooltip } from "../tooltip"
/* ---------------------------------------------------------------------------- /* ----------------------------------------------------------------------------
* Functions * Functions
* ------------------------------------------------------------------------- */ * ------------------------------------------------------------------------- */
/** /**
* Render an empty annotation * Render an annotation
* *
* @param id - Annotation identifier * @param id - Annotation identifier
* @param prefix - Tooltip identifier prefix
* *
* @returns Element * @returns Element
*/ */
export function renderAnnotation(id: number): HTMLElement { export function renderAnnotation(
return ( id: string | number, prefix?: string
<aside class="md-annotation" tabIndex={0}> ): HTMLElement {
<div class="md-annotation__inner md-tooltip"> prefix = prefix ? `${prefix}_annotation_${id}` : undefined
<div class="md-tooltip__inner md-typeset"></div>
</div> /* Render tooltip with anchor, if given */
<span class="md-annotation__index"> if (prefix) {
<span data-md-annotation-id={id}></span> const anchor = prefix ? `#${prefix}` : undefined
</span> return (
</aside> <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 { ComponentChild } from "preact"
import { feature, translation } from "~/_" import { configuration, feature, translation } from "~/_"
import { import {
SearchDocument, SearchDocument,
SearchMetadata, SearchMetadata,
@ -77,10 +77,11 @@ function renderSearchDocument(
) )
/* Render article or section, depending on flags */ /* Render article or section, depending on flags */
const { tags } = configuration()
return ( return (
<a href={`${url}`} class="md-search-result__link" tabIndex={-1}> <a href={`${url}`} class="md-search-result__link" tabIndex={-1}>
<article <article
class={["md-search-result__article", ...parent class={["md-search-result__article", "md-typeset", ...parent
? ["md-search-result__article--document"] ? ["md-search-result__article--document"]
: [] : []
].join(" ")} ].join(" ")}
@ -93,9 +94,17 @@ function renderSearchDocument(
{truncate(document.text, 320)} {truncate(document.text, 320)}
</p> </p>
} }
{document.tags && document.tags.map(tag => ( {document.tags && document.tags.map(tag => {
<span class="md-tag">{tag}</span> 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 && {teaser > 0 && missing.length > 0 &&
<p class="md-search-result__terms"> <p class="md-search-result__terms">
{translation("search.result.term.missing")}: {...missing} {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 { function renderVersion(version: Version): HTMLElement {
const config = configuration() 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) const url = new URL(`../${version.version}/`, config.base)
return ( return (
<li class="md-version__item"> <li class="md-version__item">

View File

@ -32,26 +32,16 @@
// Modifier to float block elements // Modifier to float block elements
.inline { .inline {
float: left; float: inline-start;
width: px2rem(234px); width: px2rem(234px);
margin-top: 0; margin-top: 0;
margin-inline-end: px2rem(16px); margin-inline-end: px2rem(16px);
margin-bottom: 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) // Modifier to move to end (ltr: right, rtl: left)
&.end { &.end {
float: right; float: inline-end;
margin-inline: px2rem(16px) 0; 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); height: px2rem(20px);
background-color: $clr-blue-a200; background-color: $clr-blue-a200;
mask-image: var(--md-admonition-icon--note); mask-image: var(--md-admonition-icon--note);
mask-position: center;
mask-repeat: no-repeat; mask-repeat: no-repeat;
mask-size: contain; mask-size: contain;
content: ""; content: "";
@ -176,8 +177,6 @@ $admonitions: (
&::before { &::before {
background-color: $tint; background-color: $tint;
mask-image: var(--md-admonition-icon--#{$name}); mask-image: var(--md-admonition-icon--#{$name});
mask-repeat: no-repeat;
mask-size: contain;
} }
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -216,6 +216,7 @@
height: 100%; height: 100%;
background-color: currentcolor; background-color: currentcolor;
mask-image: var(--md-nav-icon--prev); mask-image: var(--md-nav-icon--prev);
mask-position: center;
mask-repeat: no-repeat; mask-repeat: no-repeat;
mask-size: contain; mask-size: contain;
content: ""; content: "";
@ -295,6 +296,7 @@
height: 100%; height: 100%;
background-color: currentcolor; background-color: currentcolor;
mask-image: var(--md-nav-icon--next); mask-image: var(--md-nav-icon--next);
mask-position: center;
mask-repeat: no-repeat; mask-repeat: no-repeat;
mask-size: contain; mask-size: contain;
content: ""; content: "";
@ -439,6 +441,13 @@
// Navigation title // Navigation title
&--secondary &__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 // Adjust snapping behavior
&[for="__toc"] { &[for="__toc"] {
@ -458,6 +467,13 @@
// Navigation title // Navigation title
&--primary &__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 // Adjust snapping behavior
&[for="__drawer"] { &[for="__drawer"] {
@ -524,7 +540,6 @@
// Navigation icon // Navigation icon
&__icon { &__icon {
float: right;
width: px2rem(18px); width: px2rem(18px);
height: px2rem(18px); height: px2rem(18px);
border-radius: 100%; border-radius: 100%;
@ -534,7 +549,6 @@
// Adjust for right-to-left languages // Adjust for right-to-left languages
[dir="rtl"] & { [dir="rtl"] & {
float: left;
transform: rotate(180deg); transform: rotate(180deg);
} }
@ -551,6 +565,7 @@
vertical-align: px2rem(-2px); vertical-align: px2rem(-2px);
background-color: currentcolor; background-color: currentcolor;
mask-image: var(--md-nav-icon--next); mask-image: var(--md-nav-icon--next);
mask-position: center;
mask-repeat: no-repeat; mask-repeat: no-repeat;
mask-size: contain; mask-size: contain;
content: ""; content: "";
@ -583,10 +598,14 @@
// Show navigation link as title // Show navigation link as title
> .md-nav__link { > .md-nav__link {
position: sticky;
top: 0;
z-index: 1;
margin-top: 0; margin-top: 0;
padding: 0 px2rem(12px); padding: 0 px2rem(12px);
font-weight: 700; 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 // Make navigation link clickable
&--index [href] { &--index [href] {

View File

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

View File

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

View File

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

View File

@ -24,42 +24,81 @@
// Rules // Rules
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Tag list // Tag variables
.md-tags { :root {
margin-bottom: px2em(12px); --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 // Scoped in typesetted content to match specificity of regular content
&[href] { .md-typeset {
color: inherit;
outline: none;
-webkit-tap-highlight-color: transparent;
transition:
color 125ms,
background-color 125ms;
// Linked tag on focus/hover // Tag list
&:focus, .md-tags {
&:hover { margin-top: px2em(-2px);
color: var(--md-accent-bg-color); margin-bottom: px2em(12px);
background-color: var(--md-accent-fg-color); }
// 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 // Tag icon
[id] > & { .md-tag-icon {
vertical-align: text-top;
// 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; z-index: 0;
width: var(--md-tooltip-width); width: var(--md-tooltip-width);
max-width: calc(100vw - 2 * #{px2rem(16px)}); max-width: calc(100vw - 2 * #{px2rem(16px)});
max-height: 0;
color: var(--md-default-fg-color); color: var(--md-default-fg-color);
font-family: var(--md-text-font-family);
background-color: var(--md-default-bg-color); background-color: var(--md-default-bg-color);
border-radius: px2rem(2px); border-radius: px2rem(2px);
box-shadow: var(--md-shadow-z2); box-shadow: var(--md-shadow-z2);
@ -81,25 +81,23 @@
backface-visibility: hidden; backface-visibility: hidden;
opacity: 0; opacity: 0;
transition: transition:
transform 0ms 250ms, transform 0ms 250ms,
opacity 250ms, opacity 250ms,
max-height 0ms 250ms, z-index 250ms;
z-index 250ms;
// Tooltip on parent focus // Active tooltip
:focus-within > & { &--active {
max-height: 1000%; z-index: 2;
transform: translateY(0); transform: translateY(0);
opacity: 1; opacity: 1;
transition: transition:
transform 250ms cubic-bezier(0.1, 0.7, 0.1, 1), transform 250ms cubic-bezier(0.1, 0.7, 0.1, 1),
opacity 250ms, opacity 250ms,
max-height 250ms, z-index 0ms;
z-index 0ms;
} }
// Show outline for keyboard devices // Show outline on target and for keyboard devices
.focus-visible > & { :is(.focus-visible > &, &:target) {
outline: var(--md-accent-fg-color) auto; outline: var(--md-accent-fg-color) auto;
} }
@ -124,6 +122,7 @@
// Annotation // Annotation
.md-annotation { .md-annotation {
font-weight: 400;
white-space: normal; white-space: normal;
outline: none; outline: none;
@ -140,40 +139,36 @@
line-height: 1.325; 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 // Annotation index
&__index { &__index {
position: relative; position: relative;
z-index: 0; z-index: 0;
margin: 0 1ch; 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; cursor: pointer;
transition: z-index 250ms;
user-select: none; 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 // Annotation marker the marker must be positioned absolutely behind
// the index, because it shouldn't impact the rendering of a code block. // the index, because it shouldn't impact the rendering of a code block.
// Otherwise, small rounding differences in browsers can sometimes mess up // Otherwise, small rounding differences in browsers can sometimes mess up
// alignment of text following an annotation. // alignment of text following an annotation.
&::after { &::after {
position: absolute; position: absolute;
left: -0.126em; top: 0;
left: px2em(-2px);
z-index: -1; z-index: -1;
// Hack: the first property is used as a fallback for older browsers // Hack: the first property is used as a fallback for older browsers
// which don't support the min/max/clamp math functions. // which don't support the min/max/clamp math functions.
@ -198,13 +193,8 @@
} }
} }
// Annotation marker on focus/hover // Annotation marker for active tooltip
:is(:focus-within, :hover) > & { .md-tooltip--active + & {
background-color: var(--md-accent-fg-color);
}
// Annotation marker on focus
:focus-within > & {
transition: transition:
color 250ms, color 250ms,
background-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 // Annotation marker
[data-md-annotation-id] { [data-md-annotation-id] {
display: inline-block; 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); margin-inline-start: px2rem(8px);
background-color: currentcolor; background-color: currentcolor;
mask-image: var(--md-version-icon); mask-image: var(--md-version-icon);
mask-position: center;
mask-repeat: no-repeat; mask-repeat: no-repeat;
mask-size: contain;
content: ""; content: "";
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -35,3 +35,24 @@
{% set _ = style.append("}\x3c/style\x3e") %} {% set _ = style.append("}\x3c/style\x3e") %}
{{ style | join }} {{ style | join }}
{% endif %} {% 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", "edit.link.title": "Seite editieren",
"footer.previous": "Zurück", "footer.previous": "Zurück",
"footer.next": "Weiter", "footer.next": "Weiter",
"footer.title": "Fußzeile",
"header.title": "Kopfzeile",
"meta.comments": "Kommentare", "meta.comments": "Kommentare",
"meta.source": "Quellcode", "meta.source": "Quellcode",
"nav.title": "Navigation",
"search.config.lang": "de", "search.config.lang": "de",
"search.placeholder": "Suche", "search.placeholder": "Suche",
"search.share": "Teilen", "search.share": "Teilen",
@ -50,9 +53,10 @@
"select.language.title": "Sprache wechseln", "select.language.title": "Sprache wechseln",
"select.version.title": "Version auswählen", "select.version.title": "Version auswählen",
"skip.link.title": "Zum Inhalt", "skip.link.title": "Zum Inhalt",
"source.link.title": "Quellcode", "source.link.title": "Zum Repository",
"source.file.date.updated": "Letztes Update", "source.file.date.updated": "Letztes Update",
"source.file.date.created": "Erstellt", "source.file.date.created": "Erstellt",
"tabs.title": "Hauptnavigation",
"toc.title": "Inhaltsverzeichnis", "toc.title": "Inhaltsverzeichnis",
"top.title": "Zurück zum Seitenanfang" "top.title": "Zurück zum Seitenanfang"
}[key] }}{% endmacro %} }[key] }}{% endmacro %}

View File

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

View File

@ -29,12 +29,24 @@
{% if tags %} {% if tags %}
<nav class="md-tags" {{ hidden }}> <nav class="md-tags" {{ hidden }}>
{% for tag in tags %} {% 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 %} {% if tag.url %}
<a href="{{ tag.url | url }}" class="md-tag"> <a href="{{ tag.url | url }}" class="md-tag{{ icon }}">
{{ tag.name }} {{- tag.name -}}
</a> </a>
<!-- Render tag without link -->
{% else %} {% else %}
<span class="md-tag">{{ tag.name }}</span> <span class="md-tag{{ icon }}">
{{- tag.name -}}
</span>
{% endif %} {% endif %}
{% endfor %} {% endfor %}
</nav> </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 # Initialize plugin
def __init__(self): def on_config(self, config):
self.tags = defaultdict(list) self.tags = defaultdict(list)
self.tags_file = None self.tags_file = None
self.slugify = None
# Retrieve configuration for anchor generation # Retrieve tags mapping from configuration
def on_config(self, config): self.tags_map = config["extra"].get("tags")
if "toc" in config["markdown_extensions"]:
toc = { "slugify": slugify, "separator": "-" }
if "toc" in config["mdx_configs"]:
toc = { **toc, **config["mdx_configs"]["toc"] }
# Partially apply slugify function # Use override of slugify function
self.slugify = lambda value: ( toc = { "slugify": slugify, "separator": "-" }
toc["slugify"](str(value), toc["separator"]) if "toc" in config["mdx_configs"]:
) toc = { **toc, **config["mdx_configs"]["toc"] }
# Hack: 2nd pass for tags index page # Partially apply slugify function
def on_nav(self, nav, files, **kwargs): 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") file = self.config.get("tags_file")
if file: if file:
self.tags_file = files.get_file_from_path(file) self.tags_file = self._get_tags_file(files, 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)
# Build and render tags index page # 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: if page.file == self.tags_file:
return self.__render_tag_index(markdown) return self._render_tag_index(markdown)
# Add page to tags index # Add page to tags index
for tag in page.meta.get("tags", []): for tag in page.meta.get("tags", []):
self.tags[tag].append(page) self.tags[tag].append(page)
# Inject tags into page (after search and before minification) # 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: if "tags" in page.meta:
context["tags"] = [ context["tags"] = [
self.__render_tag(tag) self._render_tag(tag)
for tag in page.meta["tags"] 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 # Render tags index
def __render_tag_index(self, markdown): def _render_tag_index(self, markdown):
if not "[TAGS]" in markdown: if not "[TAGS]" in markdown:
markdown += "\n[TAGS]" markdown += "\n[TAGS]"
# Replace placeholder in Markdown with rendered tags index # Replace placeholder in Markdown with rendered tags index
return markdown.replace("[TAGS]", "\n".join([ return markdown.replace("[TAGS]", "\n".join([
self.__render_tag_links(*args) self._render_tag_links(*args)
for args in sorted(self.tags.items()) for args in sorted(self.tags.items())
])) ]))
# Render the given tag and links to all pages with occurrences # Render the given tag and links to all pages with occurrences
def __render_tag_links(self, tag, pages): def _render_tag_links(self, tag, pages):
content = [f"## <span class=\"md-tag\">{tag}</span>", ""] 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: 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( url = utils.get_relative_url(
page.file.src_path.replace(os.path.sep, "/"), page.file.src_path.replace(os.path.sep, "/"),
self.tags_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 # Render link to page
# file which contains the operating system's path separator. title = page.meta.get("title", page.title)
content.append("- [{}]({})".format( content.append(f"- [{title}]({url})")
page.meta.get("title", page.title),
url
))
# Return rendered tag links # Return rendered tag links
return "\n".join(content) return "\n".join(content)
# Render the given tag, linking to the tags index (if enabled) # 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: if not self.tags_file or not self.slugify:
return dict(name = tag) return dict(name = tag, type = type)
else: else:
url = self.tags_file.url url = f"{self.tags_file.url}#{self.slugify(tag)}"
url += f"#{self.slugify(tag)}" return dict(name = tag, type = type, url = url)
return dict(name = tag, url = url)
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
# Data # Data

View File

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