Repository: LukeCarrier/mkdocs-drawio-exporter

Issue:
Compatibility Issue with `mkdocs-glightbox`
Hello!

First of all, I have to say that your plugin has saved me a lot of time in converting Draw.io files to PNG.

I found an issue when using it alongside the [mkdocs-glightbox](https://github.com/blueswen/mkdocs-glightbox) plugin. This plugin wraps images with an anchor tag, using the image `src` as the anchor `href`. This occurs in the [`on_page_content` function](https://github.com/blueswen/mkdocs-glightbox/blob/14e152ae45e8be6fc27f50689ba5e9757462f254/mkdocs_glightbox/plugin.py#L151), which means the anchor is added before your plugin modifies the image `src` in `on_post_build` function (if I understand your code correctly). 

As a result, the anchor `href` remains broken, still pointing to the original `.drawio` file rather than the generated `.png`, `.svg`, or other formats created by your plugin.


Discussion:

Patch:
diff --git a/.gitignore b/.gitignore
index c1e2068..8f271dc 100644
--- a/.gitignore
+++ b/.gitignore
@@ -11,6 +11,3 @@ __pycache__/
 /*.egg-info/
 /build/
 /dist/
-
-# Very meta
-/docs/docs/drawio-exporter/
diff --git a/README.md b/README.md
index 3a0ec32..db37e79 100644
--- a/README.md
+++ b/README.md
@@ -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'
 ```
diff --git a/docs/.gitignore b/docs/.gitignore
new file mode 100644
index 0000000..faf41ab
--- /dev/null
+++ b/docs/.gitignore
@@ -0,0 +1,5 @@
+# mkdocs-drawio-exporter
+/docs/drawio-exporter/
+
+# Python virtual environment
+/venv/
diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml
index ea51e0d..022dd9a 100644
--- a/docs/mkdocs.yml
+++ b/docs/mkdocs.yml
@@ -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:
diff --git a/docs/requirements.txt b/docs/requirements.txt
index b3b682a..3e504c8 100644
--- a/docs/requirements.txt
+++ b/docs/requirements.txt
@@ -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
@@ -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
diff --git a/mkdocs_drawio_exporter/exporter.py b/mkdocs_drawio_exporter/exporter.py
index 5d3037c..3fdd0b2 100644
--- a/mkdocs_drawio_exporter/exporter.py
+++ b/mkdocs_drawio_exporter/exporter.py
@@ -12,7 +12,7 @@ from typing import TypedDict
 import urllib.parse
 
 
-IMAGE_RE = re.compile('(<img[^>]+src=")([^">]+)("\\s*\\/?>)')
+IMAGE_RE = re.compile(r'!\[(?P<alt>[^\]]*)\]\((?P<filename>[^\)]*)\)')
 
 
 class Configuration(TypedDict):
@@ -262,12 +262,13 @@ class DrawIoExporter:
 
         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)
@@ -276,7 +277,7 @@ class DrawIoExporter:
                 # 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'])
 
@@ -289,12 +290,11 @@ class DrawIoExporter:
                         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)
diff --git a/mkdocs_drawio_exporter/plugin.py b/mkdocs_drawio_exporter/plugin.py
index 7569a7e..e1bfa67 100644
--- a/mkdocs_drawio_exporter/plugin.py
+++ b/mkdocs_drawio_exporter/plugin.py
@@ -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')),
     )
 
@@ -33,7 +33,7 @@ class DrawIoExporterPlugin(mkdocs.plugins.BasePlugin):
 
     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(
@@ -53,21 +53,21 @@ class DrawIoExporterPlugin(mkdocs.plugins.BasePlugin):
                 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 = []


Test patch:
diff --git a/mkdocs_drawio_exporter/tests/exporter.py b/mkdocs_drawio_exporter/tests/exporter.py
index c9e3644..a6f9458 100644
--- a/mkdocs_drawio_exporter/tests/exporter.py
+++ b/mkdocs_drawio_exporter/tests/exporter.py
@@ -34,7 +34,7 @@ class ExporterTests(unittest.TestCase):
             '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
@@ -103,8 +103,9 @@ class ExporterTests(unittest.TestCase):
 
     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()