Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rewrite embeds in on_page_markdown #75

Merged
merged 4 commits into from
Nov 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,3 @@ __pycache__/
/*.egg-info/
/build/
/dist/

# Very meta
/docs/docs/drawio-exporter/
5 changes: 2 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,13 @@ plugins:
# Output format (see draw.io --help | grep format)
format: svg
# Embed format
# * The default is to embed via the <img> tag, only rewriting the
# value of the src attribute.
# * The default is to embed via the <img> tag.
# * Consider <object type="image/svg+xml" data="{img_src}"></object>
# to enable interactive elements (like hyperlinks) in SVGs.
# * Consider {content} to inline SVGs into documents directly, useful
# for styling with CSS, preserving interactivity, and improving
# search by indexing diagram text.
embed_format: '{img_open}{img_src}{img_close}'
embed_format: '<img alt="{img_alt}" src="{img_src}">'
# Glob pattern for matching source files
sources: '*.drawio'
```
Expand Down
5 changes: 5 additions & 0 deletions docs/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# mkdocs-drawio-exporter
/docs/drawio-exporter/

# Python virtual environment
/venv/
3 changes: 2 additions & 1 deletion docs/mkdocs.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
site_name: mkdocs-drawio-exporter example
plugins:
- search
- glightbox
- drawio-exporter:
embed_format: "{content}"
format: svg
drawio_args: [--no-sandbox, --disable-gpu]

nav:
Expand Down
9 changes: 9 additions & 0 deletions docs/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
click==8.1.7
docstring-to-markdown==0.15
ghp-import==2.1.0
jedi==0.19.1
Jinja2==3.1.4
livereload==2.6.3
Markdown==3.6
Expand All @@ -8,12 +10,19 @@ mergedeep==1.3.4
mkdocs==1.6.0
mkdocs-drawio-exporter==0.9.1
mkdocs-get-deps==0.2.0
mkdocs-glightbox==0.4.0
packaging==24.1
parso==0.8.4
pathspec==0.12.1
platformdirs==4.2.2
pluggy==1.4.0
python-dateutil==2.9.0.post0
python-lsp-jsonrpc==1.1.2
python-lsp-server==1.11.0
PyYAML==6.0.1
pyyaml_env_tag==0.1
setuptools==69.5.1.post0
six==1.16.0
tornado==6.4.1
ujson==5.9.0
watchdog==4.0.1
18 changes: 9 additions & 9 deletions mkdocs_drawio_exporter/exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import urllib.parse


IMAGE_RE = re.compile('(<img[^>]+src=")([^">]+)("\\s*\\/?>)')
IMAGE_RE = re.compile(r'!\[(?P<alt>[^\]]*)\]\((?P<filename>[^\)]*)\)')


class Configuration(TypedDict):
Expand Down Expand Up @@ -262,12 +262,13 @@ def rewrite_image_embeds(self, page_dest_path, output_content, config: Configura

def replace(match):
try:
filename, page_index = match.group(2).rsplit('#', 1)
filename, page_index = match.group('filename').rsplit('#', 1)
except ValueError:
filename = match.group(2)
filename = match.group('filename')
page_index = 0
img_alt = match.group('alt')

if fnmatch.fnmatch(filename, config["sources"]):
if fnmatch.fnmatch(filename, config['sources']):
source = Source(filename, page_index)
source.resolve_rel_path(page_dest_path)
content_sources.append(source)
Expand All @@ -276,7 +277,7 @@ def replace(match):
# Cache the file on-demand and read file content only if we
# need to inline the file's content.
content = None
if "{content}" in config["embed_format"]:
if '{content}' in config['embed_format']:
img_path = self.make_cache_filename(
source.source_rel, page_index, config['cache_dir'])

Expand All @@ -289,12 +290,11 @@ def replace(match):
self.log.error(f'Export failed with exit status {exit_status}; skipping rewrite')
return match.group(0)

with open(img_path, "r") as f:
with open(img_path, 'r') as f:
content = f.read()

return config["embed_format"].format(
img_open=match.group(1), img_close=match.group(3),
img_src=img_src, content=content)
return config['embed_format'].format(
img_alt=img_alt, img_src=img_src, content=content)
else:
return match.group(0)
output_content = IMAGE_RE.sub(replace, output_content)
Expand Down
12 changes: 6 additions & 6 deletions mkdocs_drawio_exporter/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,15 @@ class DrawIoExporterPlugin(mkdocs.plugins.BasePlugin):
('drawio_executable', config_options.Type(str)),
('drawio_args', config_options.Type(list, default=[])),
('format', config_options.Type(str, default='svg')),
('embed_format', config_options.Type(str, default='{img_open}{img_src}{img_close}')),
('embed_format', config_options.Type(str, default='<img alt="{img_alt}" src="{img_src}">')),
('sources', config_options.Type(str, default='*.drawio')),
)

exporter = None

sources = []

def on_config(self, config):
def on_config(self, config, **kwargs):
self.exporter = DrawIoExporter(log, config['docs_dir'])

self.config['cache_dir'] = self.exporter.prepare_cache_dir(
Expand All @@ -53,21 +53,21 @@ def on_config(self, config):
f'arguments {self.config["drawio_args"]} and '
f'cache directory "{self.config["cache_dir"]}"')

def on_post_page(self, output_content, page, **kwargs):
def on_page_markdown(self, markdown, page, **kwargs):
output_content, content_sources = self.exporter.rewrite_image_embeds(
page.file.dest_path, output_content, self.config)
page.file.dest_path, markdown, self.config)

self.sources += content_sources

return output_content

def on_files(self, files, config):
def on_files(self, files, config, **kwargs):
keep = self.exporter.filter_cache_files(files, self.config['cache_dir'])
log.debug(f'{len(keep)} files left after excluding cache')

return Files(keep)

def on_post_build(self, config):
def on_post_build(self, config, **kwargs):
sources = set(self.sources)
log.debug(f'Found {len(sources)} unique sources in {len(self.sources)} total embeds')
self.sources = []
Expand Down
7 changes: 4 additions & 3 deletions mkdocs_drawio_exporter/tests/exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def make_config(self, **kwargs):
'drawio_executable': 'drawio',
'drawio_args': [],
'format': 'svg',
'embed_format': '{img_open}{img_src}{img_close}',
'embed_format': '<img alt="{img_alt}" src="{img_src}">',
'sources': '*.drawio',
}
# FIXME: when dropping support for Python 3.8, replace with the merge
Expand Down Expand Up @@ -103,8 +103,9 @@ def test_prepare_drawio_executable_raises_on_failure(self):

def test_rewrite_image_embeds(self):
page_dest_path = "index.html"
source = '''<h1>Example text</h1>
<img alt="Some text" src="../some-diagram.drawio" />'''
source = '''# Example text

![Some text](../some-diagram.drawio)'''
object_embed_format = '<object type="image/svg+xml" data="{img_src}"></object>'

exporter = self.make_exporter()
Expand Down
Loading