Skip to content

Commit

Permalink
feat: misc. fixes and enhancements
Browse files Browse the repository at this point in the history
- Improved error handling when compiling SCSS files
- Fixed issues when using old plugin name (such as `mkdocs/exporter/extras`)
- Improved documentation
  - Enabled social cards
  - Minor documentation enhancements
- Updated dependencies
  • Loading branch information
adrienbrignon committed Dec 4, 2023
1 parent 33db06a commit 793ba69
Show file tree
Hide file tree
Showing 13 changed files with 324 additions and 38 deletions.
6 changes: 3 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ ifeq ($(origin .RECIPEPREFIX), undefined)
$(error This Make does not support .RECIPEPREFIX. Please use GNU Make 4.0 or later)
endif

PDF = false
PDF = true
DEBUG = false

.RECIPEPREFIX = >
Expand All @@ -17,10 +17,10 @@ browser:
> poetry run playwright install $(if $(FORCE),--force,) --with-deps

build:
>@ poetry run mkdocs build
>@ MKDOCS_EXPORTER_PDF=$(PDF) poetry run mkdocs build

serve:
>@ poetry run mkdocs serve
>@ MKDOCS_EXPORTER_PDF=$(PDF) poetry run mkdocs serve

clean:
> $(RM) -rf dist/
Expand Down
10 changes: 7 additions & 3 deletions docs/setup/setting-up-documents.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,11 @@ plugins:
This architecture reduces code duplication and maintains a generic base that can be used to export
your pages to formats other than PDF (although this is currently the only format supported).
To sum things up, the `exporter` should always be registered first as it provides a common ground for
To sum things up, the `exporter` plugin should always be registered first as it provides a common ground for
other plugins to rely on.

<div class="page-break"></div>

## Usage

### Toggling documents generation
Expand All @@ -67,8 +69,6 @@ Here's how cover pages are set up for this documentation.

The following examples use the [`macros`](https://github.com/fralau/mkdocs_macros_plugin) plugin for *extra powerful* pages.

<div class="page-break"></div>

=== "`mkdocs.yml`"

```yaml
Expand All @@ -86,6 +86,8 @@ Here's how cover pages are set up for this documentation.

> :material-file-code: See the full content of this file [here](https://github.com/adrienbrignon/mkdocs-exporter/blob/master/mkdocs.yml).

<div class="page-break"></div>

=== "`resources/templates/covers/front.html.j2`"

```html
Expand Down Expand Up @@ -129,6 +131,8 @@ Here's how cover pages are set up for this documentation.

> :material-file-code: See the full content of this file [here](https://github.com/adrienbrignon/mkdocs-exporter/blob/master/resources/stylesheets/pdf.scss).

<div class="page-break"></div>

### Increasing concurrency

PDF are, by default, generated concurrently which greatly reduces the overall build time.
Expand Down
6 changes: 6 additions & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@ theme:
- navigation.footer
- navigation.indexes
- navigation.instant
- navigation.instant.progress
- navigation.sections
- navigation.tabs
- navigation.top
- navigation.tracking
- navigation.prune
- toc.follow

extra:
Expand All @@ -42,6 +44,7 @@ plugins:
- exporter:
- exporter-pdf:
concurrency: 16
enabled: !ENV [MKDOCS_EXPORTER_PDF, true]
stylesheets:
- resources/stylesheets/pdf.scss
covers:
Expand Down Expand Up @@ -72,6 +75,9 @@ plugins:
'index.md': 'getting-started.md'
- minify:
minify_html: true
- social:
cards_layout_options:
background_color: '#EA2027'

markdown_extensions:
- admonition
Expand Down
8 changes: 4 additions & 4 deletions mkdocs_exporter/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,18 +67,18 @@ def on_post_build(self, **kwargs) -> None:
content = None

with open(stylesheet.abs_dest_path, 'r', encoding='utf-8') as reader:
content = self.theme.stylesheet(reader.read())
content = self.theme.stylesheet(stylesheet, reader.read())
with open(stylesheet.abs_dest_path, 'w+', encoding='utf-8') as writer:
writer.write(content)


class PluginDeprecated(Plugin):
class DeprecatedPlugin(Plugin):
"""Deprecated plugin, will be removed in the next major release."""


def on_config(self, config: dict) -> None:
def on_config(self, config: dict, **kwargs) -> None:
"""Invoked when the configuration has been loaded."""

logger.warning("The plugin name 'mkdocs/exporter' will stop working soon, please replace it with 'exporter'")

super().on_config(config)
super().on_config(config, **kwargs)
12 changes: 9 additions & 3 deletions mkdocs_exporter/plugins/extras/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ class Plugin(BasePlugin[Config]):
"""The plugin."""


def on_config(self, *args, **kwargs) -> None:
"""Invoked when the configuration has been loaded."""

pass


@event_priority(-85)
def on_post_page(self, html: str, page: Page, config: dict, **kwargs) -> Optional[str]:
"""Invoked after a page has been built."""
Expand Down Expand Up @@ -40,13 +46,13 @@ def resolve(object):
return preprocessor.done()


class PluginDeprecated(Plugin):
class DeprecatedPlugin(Plugin):
"""Deprecated plugin, will be removed in the next major release."""


def on_config(self, config: dict) -> None:
def on_config(self, *args, **kwargs) -> None:
"""Invoked when the configuration has been loaded."""

logger.warning("The plugin name 'mkdocs/exporter/extras' will stop working soon, please replace it with 'exporter-extras'")

super().on_config(config)
super().on_config(*args, **kwargs)
6 changes: 3 additions & 3 deletions mkdocs_exporter/plugins/pdf/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,13 +170,13 @@ def _enabled(self, page: Page = None) -> bool:
return True


class PluginDeprecated(Plugin):
class DeprecatedPlugin(Plugin):
"""Deprecated plugin, will be removed in the next major release."""


def on_config(self, config: dict) -> None:
def on_config(self, config: dict, **kwargs) -> None:
"""Invoked when the configuration has been loaded."""

logger.warning("The plugin name 'mkdocs/exporter/pdf' will stop working soon, please replace it with 'exporter-pdf'")

super().on_config(config)
super().on_config(config, **kwargs)
2 changes: 1 addition & 1 deletion mkdocs_exporter/plugins/pdf/renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def preprocess(self, page: Page) -> str:
preprocessor.stylesheet(file.read())
for script in self.scripts:
with open(script, 'r', encoding='utf-8') as file:
preprocessor.script(file.read())
preprocessor.script(file.read(), path=stylesheet)

preprocessor.script(importlib_resources.files(js).joinpath('pdf.js').read_text(encoding='utf-8'))
preprocessor.script(importlib_resources.files(js).joinpath('pagedjs.min.js').read_text(encoding='utf-8'))
Expand Down
16 changes: 12 additions & 4 deletions mkdocs_exporter/preprocessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import sass

from typing import Union
from sass import CompileError
from urllib.parse import urlparse
from bs4 import BeautifulSoup, Tag

Expand Down Expand Up @@ -46,7 +47,7 @@ def teleport(self) -> Preprocessor:
"""Teleport elements to their destination."""

for element in self.html.select('*[data-teleport]'):
selector = element.attrs['data-teleport']
selector = element.attrs.get('data-teleport')
destination = self.html.select_one(selector)
tag = Tag(None, name=element.name, attrs=element.attrs)

Expand All @@ -58,8 +59,7 @@ def teleport(self) -> Preprocessor:

continue

element.attrs['data-teleport'] = None

element.attrs.pop('data-teleport', None)
destination.append(element)

return self
Expand Down Expand Up @@ -89,7 +89,15 @@ def script(self, script: str = None, type: str = 'text/javascript', **kwargs) ->
def stylesheet(self, stylesheet: str, **kwargs) -> Preprocessor:
"""Appends a stylesheet to the document's head."""

css = sass.compile(string=stylesheet, output_style='compressed')
css = None

try:
css = sass.compile(string=stylesheet, output_style='compressed')
except CompileError as error:
logger.error(error)

return self

element = self.html.new_tag('style', type='text/css', rel='stylesheet', **kwargs)

element.string = css
Expand Down
4 changes: 2 additions & 2 deletions mkdocs_exporter/resources/js/pdf.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ window.PagedConfig = {
try {
await window.MkDocsExporter.render(this);
} catch (error) {
console.error('[mkdocs-exporter] Failed to invoke render function', error);
console.error('[mkdocs-exporter] Failed to invoke render function:', error);
}
}
}
Expand All @@ -27,6 +27,6 @@ window.PagedConfig = {
*/
after: () => {
document.body.setAttribute('mkdocs-exporter', 'true');
},
}

};
7 changes: 5 additions & 2 deletions mkdocs_exporter/theme.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
from __future__ import annotations

from abc import abstractmethod
from mkdocs.structure.files import File
from mkdocs.theme import Theme as BaseTheme


Expand Down Expand Up @@ -26,7 +29,7 @@ def button(self, preprocessor, title: str, icon: str, attributes: dict = {}):
raise NotImplementedError()


def stylesheet(self, css: str) -> str:
def stylesheet(self, stylesheet: File, content: str) -> str:
"""Transforms a stylesheet."""

return css
return content
6 changes: 4 additions & 2 deletions mkdocs_exporter/themes/readthedocs/theme.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

import importlib_resources

from mkdocs.structure.files import File

from mkdocs_exporter.resources import css
from mkdocs_exporter.theme import Theme as BaseTheme
from mkdocs_exporter.preprocessor import Preprocessor
Expand Down Expand Up @@ -37,7 +39,7 @@ def icon(self, name: str):
return None


def stylesheet(self, css: str) -> str:
def stylesheet(self, stylesheet: File, content: str) -> str:
"""Transforms a stylesheet."""

return css.replace(':nth-of-type(3n+1)', ':nth-of-type(3n)')
return content.replace(':nth-of-type(3n+1)', ':nth-of-type(3n)')
Loading

0 comments on commit 793ba69

Please sign in to comment.