|
1 | 1 | import re |
2 | 2 | import xml.etree.ElementTree as etree |
3 | 3 | from abc import abstractmethod |
| 4 | +from pathlib import Path |
4 | 5 | from typing import cast |
5 | | -from urllib.parse import urlencode |
| 6 | +from urllib.parse import urlencode, urlparse |
6 | 7 |
|
7 | 8 | from markdown import Extension |
8 | 9 | from markdown.preprocessors import Preprocessor |
@@ -96,9 +97,16 @@ def convert_tag(self, line) -> str: |
96 | 97 | pass |
97 | 98 |
|
98 | 99 | class ElementExamplePreProcessor(ElementHtmlPreProcessor): |
99 | | - def __init__(self, examples_base, *args, **kwargs): |
| 100 | + def __init__(self, examples_base, page, *args, **kwargs): |
100 | 101 | """Initialize.""" |
101 | 102 | self.examples_base = examples_base |
| 103 | + self.page = page |
| 104 | + url = urlparse(self.examples_base) |
| 105 | + # If no scheme, we assume we need to build a relative path to the examples |
| 106 | + if url.scheme == '': |
| 107 | + segments = self.page.split('/') |
| 108 | + base = Path('/'.join(['..' if segment else '' for segment in segments])) |
| 109 | + self.examples_base = str(base / self.examples_base.lstrip('/')) |
102 | 110 | super().__init__('si-docs-component', *args, **kwargs) |
103 | 111 |
|
104 | 112 | def convert_tag(self, line) -> str: |
@@ -132,13 +140,19 @@ class ElementDocsExtension(Extension): |
132 | 140 | def __init__(self, *args, **kwargs): |
133 | 141 | """Initialize.""" |
134 | 142 | self.config = { |
135 | | - 'examples_base': ['', 'Base URL for the examples.'] |
| 143 | + 'examples_base': ['', 'Base URL for the examples.'], |
| 144 | + 'md_file': ['', 'The markdown file being processed.'] |
136 | 145 | } |
137 | 146 | super().__init__(*args, **kwargs) |
138 | 147 |
|
139 | 148 | def extendMarkdown(self, md): |
140 | 149 | """Add Tabbed to Markdown instance.""" |
141 | | - md.preprocessors.register(ElementExamplePreProcessor(self.config.get('examples_base')[0], md), 'element_example', 10) |
| 150 | + # Extract current page path |
| 151 | + current_page = self.config.get('md_file')[0].config._current_page |
| 152 | + page = '' |
| 153 | + if hasattr(current_page, 'abs_url'): |
| 154 | + page = current_page.abs_url |
| 155 | + md.preprocessors.register(ElementExamplePreProcessor(self.config.get('examples_base')[0], page, md), 'element_example', 10) |
142 | 156 | md.treeprocessors.register(ElementTabTreeProcessor(md), 'element_tabs', 10) |
143 | 157 |
|
144 | 158 |
|
|
0 commit comments