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

Add link_css option #70

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
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
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ plugins:
embed_format: '{img_open}{img_src}{img_close}'
# Glob pattern for matching source files
sources: '*.drawio'
# Replace diagrams' default colors with the theme's
# NOTE: requires support from theme or custom CSS
use_theme_colors: false
```

## Usage
Expand All @@ -77,6 +80,36 @@ If you're working with multi-page documents, append the index of the page as an

The plugin will export the diagram to the `format` specified in your configuration and will rewrite the `<img>` tag in the generated page to match. To speed up your documentation rebuilds, the generated output will be placed into `cache_dir` and then copied to the desired destination. The cached images will only be updated if the source diagram's modification date is newer than the cached export. Thus, bear in mind caching works per file - with large multi-page documents a change to one page will rebuild all pages, which will be slower than separate files per page.

### Linking draw.io colours with theme CSS

If you want to source colors in your diagrams from your MkDocs theme or custom CSS, set `use_theme_colors` to `true` in your configuration. This will replace the colors in your diagrams with the colours defined in your theme or `extra_css`. This is useful if you want to ensure your diagrams match the look and feel of your documentation, especially when toggling between light and dark themes.

You should define the colors in your custom CSS with CSS variables, as follows:

```css
:root {
/* First 8 colors in draw.io Style panel */
--drawio-color-ffffff: #000000;
--drawio-color-f5f5f5: #e9b3b3;
--drawio-color-dae8fc: #9bbbe7;
--drawio-color-d5e8d4: #75c770;
--drawio-color-ffe6cc: #cc9e6d;
--drawio-color-fff2cc: #dabd66;
--drawio-color-f8cecc: #b95c57;
--drawio-color-e1d5e7: #8c49ad;
}

[data-md-color-scheme="slate"] {
/* Same for dark theme */
}
```

To activate the custom CSS for some drawings only, you can use the `attr_list` option in your document:

```md
![My alt text](my-diagram.drawio){ use_theme_colors=true }
```

### GitHub Actions

See [this guide](./docs/github-actions.md).
Expand Down
33 changes: 32 additions & 1 deletion mkdocs_drawio_exporter/exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,34 @@ def validate_config(self, config: Configuration):
'embed_format', config['embed_format'],
'cannot inline content of non-SVG format')

def set_css_classes(self, svg_content, prefix="--drawio-color"):
"""Rewrite SVG styles to use CSS variables.
Will replace all `stroke` and `fill` attributes with CSS variables
such as `var(--drawio-color-ffffff)`.

:param str svg_content: SVG content.
:param str prefix: CSS variable prefix.

:return str: SVG content with styles rewritten.
"""
pattern = re.compile(
(r'(fill|stroke)\s*='
r'\s*\"(\#[A-Fa-f0-9]+|'
r'rgb\([0-9]{1,3}\s*,\s*[0-9]{1,3}\s*,\s*[0-9]{1,3}\))\"'))
Comment on lines +261 to +264
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We'll need tests for this regex. Are you happy to add these, or would you rather I took a look?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes I can add some tests


def apply_style(match):
fill = match.group(2)
if fill.startswith("#"):
hexcolor = fill[1:]
else:
r, g, b = [
int(x) for x in
re.match(r"rgb\((\d+),\s*(\d+),\s*(\d+)\)", fill).groups()]
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Likewise, I think we ought to write tests for this.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll do it.

hexcolor = f"{r:02x}{g:02x}{b:02x}"
return f'{match.group(1)}="{f"var({prefix}-{hexcolor})"}"'

return pattern.sub(apply_style, svg_content)

def rewrite_image_embeds(self, page_dest_path, output_content, config: Configuration):
"""Rewrite image embeds.

Expand Down Expand Up @@ -289,9 +317,12 @@ 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", encoding="utf-8") as f:
content = f.read()

if config["use_theme_colors"] or not re.findall(r'use_theme_colors="(?:false|no|0)"', match.group(0)):
content = self.set_css_classes(content)

return config["embed_format"].format(
img_open=match.group(1), img_close=match.group(3),
img_src=img_src, content=content)
Expand Down
1 change: 1 addition & 0 deletions mkdocs_drawio_exporter/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class DrawIoExporterPlugin(mkdocs.plugins.BasePlugin):
('format', config_options.Type(str, default='svg')),
('embed_format', config_options.Type(str, default='{img_open}{img_src}{img_close}')),
('sources', config_options.Type(str, default='*.drawio')),
('use_theme_colors', config_options.Type(bool, default=False)),
)

exporter = None
Expand Down