Skip to content

Commit

Permalink
fix: compatibility with Python 3.7+
Browse files Browse the repository at this point in the history
  • Loading branch information
adrienbrignon committed May 8, 2023
1 parent 2fd737e commit 853a393
Show file tree
Hide file tree
Showing 10 changed files with 68 additions and 35 deletions.
11 changes: 6 additions & 5 deletions mkdocs_exporter/browser.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import asyncio

from typing import Self
from tempfile import NamedTemporaryFile
from mkdocs_exporter.logging import logger
from playwright.async_api import async_playwright
Expand Down Expand Up @@ -29,7 +30,7 @@ def __init__(self):
self.lock = asyncio.Lock()


async def launch(self) -> Self:
async def launch(self) -> Browser:
"""Launches the browser."""

if self.launched:
Expand All @@ -50,15 +51,15 @@ async def launch(self) -> Self:
return self


async def close(self) -> Self:
async def close(self) -> Browser:
"""Closes the browser."""

if self.context:
await self.context.close()
if self.browser:
await self.browser.close()
if self.playwright:
await self.playwright.stop()

self._launched = False

return self

Expand Down
3 changes: 2 additions & 1 deletion mkdocs_exporter/page.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from typing import Optional
from mkdocs.structure.pages import Page as BasePage


Expand All @@ -8,7 +9,7 @@ class Page(BasePage):
def __init__(self, *args, **kwargs):
"""The constructor."""

self.html: None | str = None
self.html: Optional[str] = None
"""The page's HTML content."""

self.formats: dict[str, str]
Expand Down
2 changes: 1 addition & 1 deletion mkdocs_exporter/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def on_pre_page(self, page: Page, **kwargs) -> None:


@event_priority(-100)
def on_post_page(self, html: str, **kwargs) -> str | None:
def on_post_page(self, html: str, **kwargs) -> str:
"""Invoked after a page has been built (and after all other plugins)."""

preprocessor = Preprocessor()
Expand Down
8 changes: 4 additions & 4 deletions mkdocs_exporter/plugins/extras/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,16 @@
class ButtonConfig(BaseConfig):
"""The configuration of a button."""

title = c.Type(str | Callable)
title = c.Type((str, Callable))
"""The button's title."""

icon = c.Type(str | Callable)
icon = c.Type((str, Callable))
"""The button's icon (typically, an SVG element)."""

href = c.Type(str | Callable)
href = c.Type((str, Callable))
"""The button's 'href' attribute."""

download = c.Optional(c.Type(bool | str | Callable))
download = c.Optional(c.Type((bool, str, Callable)))
"""The button's 'download' attribute."""

target = c.Optional(c.Choice(('_blank', '_self', '_parent', '_top')))
Expand Down
3 changes: 2 additions & 1 deletion mkdocs_exporter/plugins/extras/plugin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from typing import Optional
from mkdocs.plugins import BasePlugin
from mkdocs_exporter.page import Page
from mkdocs_exporter.preprocessor import Preprocessor
Expand All @@ -8,7 +9,7 @@ class Plugin(BasePlugin[Config]):
"""The plugin."""


def on_post_page(self, html: str, page: Page, **kwargs) -> None | str:
def on_post_page(self, html: str, page: Page, **kwargs) -> Optional[str]:
"""Invoked after a page has been built."""

preprocessor = Preprocessor()
Expand Down
9 changes: 5 additions & 4 deletions mkdocs_exporter/plugins/pdf/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import asyncio

from weasyprint import urls
from typing import Optional
from mkdocs.plugins import BasePlugin
from mkdocs_exporter.page import Page
from mkdocs.structure.pages import Page
Expand All @@ -20,9 +21,9 @@ class Plugin(BasePlugin[Config]):
def __init__(self):
"""The constructor."""

self.renderer: None | Renderer = None
self.renderer: Optional[Renderer] = None
self.tasks: list[types.CoroutineType] = []
self.loop: None | asyncio.AbstractEventLoop = None
self.loop: Optional[asyncio.AbstractEventLoop] = None


def on_config(self, config: dict) -> None:
Expand Down Expand Up @@ -101,7 +102,7 @@ def on_pre_page(self, page: Page, config: dict, **kwargs):


@event_priority(-75)
def on_post_page(self, html: str, page: Page, config: dict) -> None | str:
def on_post_page(self, html: str, page: Page, config: dict) -> Optional[str]:
"""Invoked after a page has been built."""

page.html = html
Expand All @@ -125,7 +126,7 @@ async def render(page: Page) -> None:
return page.html


def on_post_build(self, **kwargs):
def on_post_build(self, **kwargs) -> None:
"""Invoked after the build process."""

if not self.config.enabled:
Expand Down
15 changes: 8 additions & 7 deletions mkdocs_exporter/plugins/pdf/renderer.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from __future__ import annotations

import os
import importlib.resources
import importlib_resources

from typing import Self
from mkdocs_exporter.page import Page
from mkdocs_exporter.resources import js
from mkdocs_exporter.browser import Browser
Expand All @@ -22,23 +23,23 @@ def __init__(self, browser: Browser = None):
self.browser = browser or Browser()


def add_stylesheet(self, path: str) -> Self:
def add_stylesheet(self, path: str) -> Renderer:
"""Adds a stylesheet to the renderer."""

self.stylesheets.append(path)

return self


def add_script(self, path: str) -> Self:
def add_script(self, path: str) -> Renderer:
"""Adds a script to the renderer."""

self.scripts.append(path)

return self


def cover(self, template: str) -> Self:
def cover(self, template: str) -> Renderer:
"""Renders a cover."""

content = template.strip('\n')
Expand Down Expand Up @@ -70,14 +71,14 @@ async def render(self, page: Page, **kwargs) -> bytes:
preprocessor.script(file.read())

if kwargs.get('polyfills', True):
preprocessor.script(importlib.resources.files(js).joinpath('pagedjs.min.js').read_text())
preprocessor.script(importlib_resources.files(js).joinpath('pagedjs.min.js').read_text())

html = preprocessor.done()

return await self.browser.print(html)


async def dispose(self):
async def dispose(self) -> None:
"""Dispose of the renderer."""

if self.browser:
Expand Down
28 changes: 18 additions & 10 deletions mkdocs_exporter/preprocessor.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from __future__ import annotations

import os
import sass

from weasyprint import urls
from bs4 import BeautifulSoup, Tag
from typing import Any, Callable, Self
from typing import Any, Callable, Union
from mkdocs_exporter.logging import logger


Expand All @@ -16,15 +18,15 @@ def __init__(self, html: str = None):
self.preprocess(html)


def preprocess(self, html: str) -> Self:
def preprocess(self, html: str) -> Preprocessor:
"""Gives the preprocessor some HTML to work on."""

self.html = BeautifulSoup(html, 'lxml') if isinstance(html, str) else None

return self


def button(self, title: str, href: str, icon: str, **kwargs) -> Self:
def button(self, title: str, href: str, icon: str, **kwargs) -> Preprocessor:
"""Adds a button at the top of the page."""

button = self.html.new_tag('a', title=title, href=href, **kwargs, attrs={'class': 'md-content__button md-icon'})
Expand All @@ -36,7 +38,7 @@ def button(self, title: str, href: str, icon: str, **kwargs) -> Self:
return self


def teleport(self) -> Self:
def teleport(self) -> Preprocessor:
"""Teleport elements to their destination."""

for element in self.html.select('*[data-teleport]'):
Expand All @@ -59,7 +61,7 @@ def teleport(self) -> Self:
return self


def script(self, script: str = None, type: str = 'text/javascript', **kwargs):
def script(self, script: str = None, type: str = 'text/javascript', **kwargs) -> Preprocessor:
"""Appends a script to the document's body."""

element = self.html.new_tag('script', type=type, **kwargs)
Expand All @@ -68,8 +70,10 @@ def script(self, script: str = None, type: str = 'text/javascript', **kwargs):

self.html.body.append(element)

return self


def stylesheet(self, stylesheet: str, **kwargs) -> Self:
def stylesheet(self, stylesheet: str, **kwargs) -> Preprocessor:
"""Appends a stylesheet to the document's head."""

css = sass.compile(string=stylesheet, output_style='compressed')
Expand All @@ -79,8 +83,10 @@ def stylesheet(self, stylesheet: str, **kwargs) -> Self:

self.html.head.append(element)

return self

def remove(self, selectors: str | list[str]) -> Self:

def remove(self, selectors: Union[str, list[str]]) -> Preprocessor:
"""Removes some elements."""

if isinstance(selectors, str):
Expand All @@ -90,8 +96,10 @@ def remove(self, selectors: str | list[str]) -> Self:
for element in self.html.select(selector):
element.decompose()

return self


def remove_scripts(self, predicate: Callable[[Any], bool] = lambda _: True) -> Self:
def remove_scripts(self, predicate: Callable[[Any], bool] = lambda _: True) -> Preprocessor:
"""Remove all script tags."""

for element in self.html.find_all('script'):
Expand All @@ -101,7 +109,7 @@ def remove_scripts(self, predicate: Callable[[Any], bool] = lambda _: True) -> S
return self


def update_links(self, base: str, root: str = None) -> Self:
def update_links(self, base: str, root: str = None) -> Preprocessor:
"""Updates links to their new base location."""

for element in self.html.find_all('link', href=True):
Expand All @@ -122,7 +130,7 @@ def done(self) -> str:
return result


def _resolve_link(self, url: str, base: str, root: str = None):
def _resolve_link(self, url: str, base: str, root: str = None) -> str:
"""Resolves a link to its new base location."""

if urls.url_is_absolute(url):
Expand Down
21 changes: 20 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "poetry.core.masonry.api"

[tool.poetry]
name = "mkdocs-exporter"
version = "0.0.1"
version = "0.0.2"
repository = "https://github.com/adrienbrignon/mkdocs-exporter"
keywords = ["mkdocs", "pdf", "exporter"]
description = "A highly-configurable plugin for MkDocs that exports your pages to PDF files."
Expand All @@ -27,6 +27,7 @@ beautifulsoup4 = ">=4.12.2"
weasyprint = ">=50.0"
lxml = ">=4.9"
libsass = ">=0.22.0"
importlib-resources = "*"

[tool.poetry.plugins."mkdocs.plugins"]
"mkdocs/exporter" = "mkdocs_exporter.plugin:Plugin"
Expand Down

0 comments on commit 853a393

Please sign in to comment.