Skip to content

IconResolver

🛈 DocStrings

Make icons used by pages / social links available to the theme.

MkNodes uses Iconify keys (grommet-icons:install). Icons available in the theme's bundled icon sets get mapped to theme paths (material/wrench), all others get downloaded into the theme override folder (.icons/iconify/<set>/<name>.svg).

Source code in mkdocs_mknodes/writers/zensical.py
class IconResolver:
    """Make icons used by pages / social links available to the theme.

    MkNodes uses Iconify keys (`grommet-icons:install`). Icons available in the theme's
    bundled icon sets get mapped to theme paths (`material/wrench`), all others get
    downloaded into the theme override folder (`.icons/iconify/<set>/<name>.svg`).
    """

    def __init__(self, fetch: Callable[[str], str | None] = _fetch_svg) -> None:
        self.fetch = fetch
        self.bundled = _bundled_icons_dir()
        self.svgs: dict[str, str] = {}
        """Template path (`.icons/...svg`) -> SVG of icons to add to the theme."""
        self._cache: dict[str, str | None] = {}

    def _is_bundled(self, theme_icon: str) -> bool:
        if self.bundled is None:  # can't check, trust the mapping
            return True
        return (self.bundled / f"{theme_icon}.svg").is_file()

    def resolve(self, icon: str) -> str | None:
        """Return the theme icon path for given icon (None if it is not available)."""
        if icon not in self._cache:
            self._cache[icon] = self._resolve(icon)
        return self._cache[icon]

    def _resolve(self, icon: str) -> str | None:
        theme_icon = to_theme_icon(icon)
        if theme_icon and self._is_bundled(theme_icon):
            return theme_icon
        key = to_iconify_key(icon)
        if key is None:
            return None
        prefix, _, name = key.partition(":")
        target = theme_icon or f"iconify/{prefix}/{name}"
        if not (svg := self.fetch(key)):
            return None
        self.svgs[f".icons/{target}.svg"] = svg
        return target

    def update_page(self, markdown: str) -> str:
        """Replace the `icon` of the page front matter with a theme icon path."""
        match = FRONT_MATTER_RE.match(markdown)
        if not match or "icon:" not in match.group(1):
            return markdown

        def replace(m: re.Match[str]) -> str:
            if resolved := self.resolve(m.group(2).strip()):
                return f"icon: {resolved}\n"
            logger.warning("Dropping unsupported page icon %s", m.group(2))
            return ""

        front_matter = ICON_LINE_RE.sub(replace, match.group(1))
        return f"---\n{front_matter}---\n{markdown[match.end() :]}"

    def update_social(self, social: list[dict[str, str]]) -> list[dict[str, str]]:
        """Convert social links into theme `extra.social` entries."""
        result = []
        for entry in social:
            icon = self.resolve(entry.get("icon", ""))
            if icon is None:
                logger.warning("Dropping social link %s: unsupported icon", entry.get("link"))
                continue
            result.append({**entry, "icon": icon})
        return result

svgs instance-attribute

svgs: dict[str, str] = {}

Template path (.icons/...svg) -> SVG of icons to add to the theme.

resolve

resolve(icon: str) -> str | None

Return the theme icon path for given icon (None if it is not available).

Source code in mkdocs_mknodes/writers/zensical.py
def resolve(self, icon: str) -> str | None:
    """Return the theme icon path for given icon (None if it is not available)."""
    if icon not in self._cache:
        self._cache[icon] = self._resolve(icon)
    return self._cache[icon]

update_page

update_page(markdown: str) -> str

Replace the icon of the page front matter with a theme icon path.

Source code in mkdocs_mknodes/writers/zensical.py
def update_page(self, markdown: str) -> str:
    """Replace the `icon` of the page front matter with a theme icon path."""
    match = FRONT_MATTER_RE.match(markdown)
    if not match or "icon:" not in match.group(1):
        return markdown

    def replace(m: re.Match[str]) -> str:
        if resolved := self.resolve(m.group(2).strip()):
            return f"icon: {resolved}\n"
        logger.warning("Dropping unsupported page icon %s", m.group(2))
        return ""

    front_matter = ICON_LINE_RE.sub(replace, match.group(1))
    return f"---\n{front_matter}---\n{markdown[match.end() :]}"

update_social

update_social(social: list[dict[str, str]]) -> list[dict[str, str]]

Convert social links into theme extra.social entries.

Source code in mkdocs_mknodes/writers/zensical.py
def update_social(self, social: list[dict[str, str]]) -> list[dict[str, str]]:
    """Convert social links into theme `extra.social` entries."""
    result = []
    for entry in social:
        icon = self.resolve(entry.get("icon", ""))
        if icon is None:
            logger.warning("Dropping social link %s: unsupported icon", entry.get("link"))
            continue
        result.append({**entry, "icon": icon})
    return result

:fa-brands-github: Show source on GitHub

Page info
Resources
Resources(css=[],
          markdown_extensions={},
          plugins=[Plugin('mkdocstrings')],
          js=[],
          assets=[],
          packages=[])
Metadata
created:
  source_filename: /home/runner/work/mkdocs-mknodes/mkdocs-mknodes/.venv/lib/python3.13/site-packages/mknodes/pages/mkclasspage/__init__.py
  source_function: MkClassPage.__init__
  source_line_no: 46
title: IconResolver