Skip to content

Commit

Permalink
Rewrite embeds in on_page_markdown
Browse files Browse the repository at this point in the history
Pre-process the Markdown before it's converted to Markdown, improving
compatibility with other plugins.

There are breaking changes here:

- In the `embed_format` configuration option:
  - `img_open` and `img_close` are no longer valid placeholders.
  - `img_alt` and `img_src` replace them.
  - The new default is `<img alt="{img_alt}" src="{img_src}">`.

Fixes #72
  • Loading branch information
LukeCarrier committed Nov 9, 2024
1 parent a5405aa commit f56f3d1
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 18 deletions.
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
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
6 changes: 3 additions & 3 deletions mkdocs_drawio_exporter/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ 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')),
)

Expand Down Expand Up @@ -53,9 +53,9 @@ def on_config(self, config, **kwargs):
f'arguments {self.config["drawio_args"]} and '
f'cache directory "{self.config["cache_dir"]}"')

def on_page_markdown(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

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

0 comments on commit f56f3d1

Please sign in to comment.