vexy-python-markdown-figure-groups 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,226 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ *.lcov
51
+ .hypothesis/
52
+ .pytest_cache/
53
+ cover/
54
+
55
+ # Translations
56
+ *.mo
57
+ *.pot
58
+
59
+ # Django stuff:
60
+ *.log
61
+ local_settings.py
62
+ db.sqlite3
63
+ db.sqlite3-journal
64
+
65
+ # Flask stuff:
66
+ instance/
67
+ .webassets-cache
68
+
69
+ # Scrapy stuff:
70
+ .scrapy
71
+
72
+ # Sphinx documentation
73
+ docs/_build/
74
+
75
+ # PyBuilder
76
+ .pybuilder/
77
+ target/
78
+
79
+ # Jupyter Notebook
80
+ .ipynb_checkpoints
81
+
82
+ # IPython
83
+ profile_default/
84
+ ipython_config.py
85
+
86
+ # pyenv
87
+ # For a library or package, you might want to ignore these files since the code is
88
+ # intended to run in multiple environments; otherwise, check them in:
89
+ # .python-version
90
+
91
+ # pipenv
92
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
93
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
94
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
95
+ # install all needed dependencies.
96
+ # Pipfile.lock
97
+
98
+ # uv
99
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
100
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
101
+ # commonly ignored for libraries.
102
+ # uv.lock
103
+
104
+ # poetry
105
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
106
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
107
+ # commonly ignored for libraries.
108
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
109
+ # poetry.lock
110
+ # poetry.toml
111
+
112
+ # pdm
113
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
114
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
115
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
116
+ # pdm.lock
117
+ # pdm.toml
118
+ .pdm-python
119
+ .pdm-build/
120
+
121
+ # pixi
122
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
123
+ # pixi.lock
124
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
125
+ # in the .venv directory. It is recommended not to include this directory in version control.
126
+ .pixi/*
127
+ !.pixi/config.toml
128
+
129
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
130
+ __pypackages__/
131
+
132
+ # Celery stuff
133
+ celerybeat-schedule*
134
+ celerybeat.pid
135
+
136
+ # Redis
137
+ *.rdb
138
+ *.aof
139
+ *.pid
140
+
141
+ # RabbitMQ
142
+ mnesia/
143
+ rabbitmq/
144
+ rabbitmq-data/
145
+
146
+ # ActiveMQ
147
+ activemq-data/
148
+
149
+ # SageMath parsed files
150
+ *.sage.py
151
+
152
+ # Environments
153
+ .env
154
+ .envrc
155
+ .venv
156
+ env/
157
+ venv/
158
+ ENV/
159
+ env.bak/
160
+ venv.bak/
161
+
162
+ # Conda environments
163
+ conda-meta/
164
+
165
+ # Spyder project settings
166
+ .spyderproject
167
+ .spyproject
168
+
169
+ # Rope project settings
170
+ .ropeproject
171
+
172
+ # mkdocs/Zensical documentation
173
+ /site
174
+
175
+ # mypy
176
+ .mypy_cache/
177
+ .dmypy.json
178
+ dmypy.json
179
+
180
+ # Pyre type checker
181
+ .pyre/
182
+
183
+ # pytype static type analyzer
184
+ .pytype/
185
+
186
+ # Cython debug symbols
187
+ cython_debug/
188
+
189
+ # PyCharm
190
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
191
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
192
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
193
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
194
+ # .idea/
195
+
196
+ # Abstra
197
+ # Abstra is an AI-powered process automation framework.
198
+ # Ignore directories containing user credentials, local state, and settings.
199
+ # Learn more at https://abstra.io/docs
200
+ .abstra/
201
+
202
+ # Visual Studio Code
203
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore that
204
+ # can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
205
+ # and can be added to the global gitignore or merged into this file. However, if you prefer, you
206
+ # could uncomment the following to ignore the entire vscode folder
207
+ # .vscode/
208
+ # Temporary file for partial code execution
209
+ tempCodeRunnerFile.py
210
+
211
+ # Ruff stuff:
212
+ .ruff_cache/
213
+
214
+ # PyPI configuration file
215
+ .pypirc
216
+
217
+ # Marimo
218
+ marimo/_static/
219
+ marimo/_lsp/
220
+ __marimo__/
221
+
222
+ # Streamlit
223
+ .streamlit/secrets.toml
224
+ __version__.py
225
+ _private/
226
+
@@ -0,0 +1,25 @@
1
+ ---
2
+ this_file: AGENTS.md
3
+ ---
4
+
5
+ # Development
6
+
7
+ The package lives in `src/vexy_markdown_figure_groups/`. Keep the grouping
8
+ rules in `group_figures()` so the Markdown postprocessor and callers with
9
+ rendered HTML produce the same result.
10
+
11
+ Run from the project root on Python 3.13.
12
+
13
+ ```sh
14
+ uv sync --all-extras --python 3.13
15
+ uv run pytest -q
16
+ uv run ruff check .
17
+ uv run ruff format --check .
18
+ uv run mypy src
19
+ uv build
20
+ ```
21
+
22
+ The tests cover grouping, option validation and the installed Markdown entry
23
+ point. The parity tests compare output with golden HTML from the original Fly
24
+ theme. The wheel must include the `vexy_figure_groups` entry point in
25
+ `markdown.extensions`, the generated `__version__.py` and the `py.typed` marker.
@@ -0,0 +1,19 @@
1
+ ---
2
+ this_file: CHANGELOG.md
3
+ ---
4
+
5
+ # Changelog
6
+
7
+ ## 0.1.0 — 2026-11-23
8
+
9
+ - Extracted margin-figure grouping from the Fly documentation theme as
10
+ `group_figures()`, with configurable figure classes, wrapper classes and
11
+ a CSS custom property for the paragraph count.
12
+ - Added the `vexy_figure_groups` Python-Markdown extension for figures available
13
+ in the renderer's final HTML.
14
+ - Match whole class tokens for both grouping and cut figures. Track nesting
15
+ in one pass and reuse compiled patterns across calls with the same options.
16
+ - Included `py.typed` in the package. Added CI for Python 3.12–3.14 and a
17
+ tag-triggered PyPI release workflow.
18
+ - Captured 28 HTML examples from the original Fly implementation to test
19
+ output bytes and idempotence without a theme checkout.
@@ -0,0 +1,16 @@
1
+ ---
2
+ this_file: DEPENDENCIES.md
3
+ ---
4
+
5
+ # Dependencies
6
+
7
+ | Dependency | Purpose |
8
+ | --- | --- |
9
+ | Markdown >=3.5 | Provides the extension and postprocessor API. The HTML grouping function uses the Python standard library. |
10
+ | hatchling | Builds the wheel and source distribution. |
11
+ | hatch-vcs | Derives the version from Git and writes the version module at build time. |
12
+ | pytest | Runs the HTML, Markdown and reference parity tests. |
13
+ | pytest-cov | Measures test coverage. |
14
+ | ruff | Lints and formats the source and tests. |
15
+ | mypy | Checks the package in strict mode. |
16
+ | types-Markdown | Supplies Markdown type annotations for mypy. |
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,147 @@
1
+ Metadata-Version: 2.5
2
+ Name: vexy-python-markdown-figure-groups
3
+ Version: 0.1.0
4
+ Summary: Group a margin figure with the paragraphs it illustrates in rendered HTML.
5
+ Project-URL: Homepage, https://github.com/vexyart/vexy-python-markdown-figure-groups
6
+ Project-URL: Repository, https://github.com/vexyart/vexy-python-markdown-figure-groups
7
+ Author-email: Vexy Lines Team <help@vexy.art>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: figures,html,margin figures,markdown
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Topic :: Text Processing :: Markup :: HTML
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.12
19
+ Requires-Dist: markdown>=3.5
20
+ Provides-Extra: dev
21
+ Requires-Dist: mypy; extra == 'dev'
22
+ Requires-Dist: pytest; extra == 'dev'
23
+ Requires-Dist: pytest-cov; extra == 'dev'
24
+ Requires-Dist: ruff; extra == 'dev'
25
+ Requires-Dist: types-markdown; extra == 'dev'
26
+ Description-Content-Type: text/markdown
27
+
28
+ <!-- this_file: README.md -->
29
+
30
+ # vexy-python-markdown-figure-groups
31
+
32
+ Place a figure beside the paragraphs it illustrates. The package wraps the figure
33
+ and its text in one HTML block and gives your stylesheet a paragraph count.
34
+
35
+ ## Install
36
+
37
+ Requires Python 3.12 or later. Install the `vexy-python-markdown-figure-groups`
38
+ distribution and import it as `vexy_markdown_figure_groups`.
39
+
40
+ ```sh
41
+ pip install vexy-python-markdown-figure-groups
42
+ # Or, in a uv project
43
+ uv add vexy-python-markdown-figure-groups
44
+ ```
45
+
46
+ ## Before and after
47
+
48
+ Put the figure immediately after the paragraph it illustrates. Use a double-quoted
49
+ `class` attribute on the figure.
50
+
51
+ ```html
52
+ <p>The crossbar sits below the centre of the A.</p>
53
+ <figure class="img-small"><img src="a.svg" alt="A with a low crossbar"></figure>
54
+ <p>This leaves room for the counter above.</p>
55
+ ```
56
+
57
+ The two paragraphs give the figure two grid rows to span.
58
+
59
+ ```html
60
+ <div class="figure-group" style="--rows: 2"><p>The crossbar sits below the centre of the A.</p>
61
+ <figure class="img-small"><img src="a.svg" alt="A with a low crossbar"></figure>
62
+ <p>This leaves room for the counter above.</p></div>
63
+ ```
64
+
65
+ Consecutive paragraphs join the group until another block intervenes or a
66
+ paragraph has a figure of its own. A figure immediately after a heading groups
67
+ with the paragraphs that follow it. A cut figure moves ahead of its paragraph
68
+ so text can wrap around a float.
69
+
70
+ Grouping applies to top-level article content. It skips lists, divs, details,
71
+ blockquotes, tables and nested figures. It preserves comments and the contents
72
+ of `script`, `style`, `pre` and `textarea`. Running it twice keeps a single wrapper.
73
+
74
+ ## Use with Python-Markdown
75
+
76
+ Enable the `vexy_figure_groups` extension to group figures in Markdown's final HTML,
77
+ after the renderer restores raw HTML blocks.
78
+
79
+ ```python
80
+ import markdown
81
+
82
+ text = """The crossbar sits below the centre of the A.
83
+
84
+ <figure class="img-small"><img src="a.svg" alt="A with a low crossbar"></figure>
85
+
86
+ This leaves room for the counter above."""
87
+ html = markdown.markdown(text, extensions=["md_in_html", "attr_list", "vexy_figure_groups"])
88
+ ```
89
+
90
+ Pass options through `extension_configs`, for example
91
+ `extension_configs={"vexy_figure_groups": {"group_class": "margin-note"}}`.
92
+
93
+ ## Use with rendered HTML
94
+
95
+ If a site creates figures after Markdown rendering, call the public
96
+ `group_figures()` function from your own plugin after the figures exist.
97
+ For example, a MkDocs plugin that creates figures in `on_page_content` can
98
+ return `group_figures(html)` at the end of that hook.
99
+
100
+ ```python
101
+ from vexy_markdown_figure_groups import group_figures
102
+
103
+ html = '<p>Check the crossbar.</p><figure class="img-cut"><img src="a.svg" alt="A"></figure>'
104
+ grouped = group_figures(html, group_class="fly-aside", cut_class="fly-cut")
105
+ ```
106
+
107
+ ## Options
108
+
109
+ The extension and the function accept the same options. Pass the function's
110
+ options by keyword. Use lists or tuples for class collections and literal CSS
111
+ identifiers for class names. Invalid names raise `ValueError`.
112
+
113
+ | Option | Default | Meaning |
114
+ | --- | --- | --- |
115
+ | `figure_classes` | `("img-small", "img-tall", "img-cut")` | Figure classes eligible for grouping. |
116
+ | `cut_classes` | `("img-cut",)` | Classes that move an eligible figure ahead of its paragraph. |
117
+ | `group_class` | `"figure-group"` | Class added to every wrapper. |
118
+ | `cut_class` | `"figure-group-cut"` | Additional wrapper class for cut figures. |
119
+ | `rows_property` | `"--rows"` | CSS custom property holding the paragraph count. Its name starts with `--`. |
120
+
121
+ ## Layout
122
+
123
+ On wide screens, give the figure a margin column spanning the paragraph rows.
124
+ Cut figures can float into the text instead.
125
+
126
+ ```css
127
+ @media (min-width: 48rem) {
128
+ .figure-group {
129
+ display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 16rem); column-gap: 2rem;
130
+ }
131
+ .figure-group > p { grid-column: 1; }
132
+ .figure-group > figure { grid-column: 2; grid-row: 1 / span var(--rows); margin: 0; }
133
+ .figure-group img { max-width: 100%; height: auto; }
134
+ .figure-group-cut { display: flow-root; }
135
+ .figure-group-cut > figure { float: right; width: 35%; margin: 0 0 1rem 1.5rem; }
136
+ }
137
+ ```
138
+
139
+ ## Releasing
140
+
141
+ For the first release, build from a clean checkout at the local `v0.1.0` tag
142
+ with `uv build`, then run `uv publish` on that machine using a PyPI API token.
143
+ In the project's PyPI publishing settings, register a GitHub trusted publisher
144
+ for `vexyart/vexy-python-markdown-figure-groups`, workflow `release.yml`,
145
+ environment `pypi`. Push a new `v*` tag for each subsequent release.
146
+
147
+ Licensed under Apache-2.0.
@@ -0,0 +1,120 @@
1
+ <!-- this_file: README.md -->
2
+
3
+ # vexy-python-markdown-figure-groups
4
+
5
+ Place a figure beside the paragraphs it illustrates. The package wraps the figure
6
+ and its text in one HTML block and gives your stylesheet a paragraph count.
7
+
8
+ ## Install
9
+
10
+ Requires Python 3.12 or later. Install the `vexy-python-markdown-figure-groups`
11
+ distribution and import it as `vexy_markdown_figure_groups`.
12
+
13
+ ```sh
14
+ pip install vexy-python-markdown-figure-groups
15
+ # Or, in a uv project
16
+ uv add vexy-python-markdown-figure-groups
17
+ ```
18
+
19
+ ## Before and after
20
+
21
+ Put the figure immediately after the paragraph it illustrates. Use a double-quoted
22
+ `class` attribute on the figure.
23
+
24
+ ```html
25
+ <p>The crossbar sits below the centre of the A.</p>
26
+ <figure class="img-small"><img src="a.svg" alt="A with a low crossbar"></figure>
27
+ <p>This leaves room for the counter above.</p>
28
+ ```
29
+
30
+ The two paragraphs give the figure two grid rows to span.
31
+
32
+ ```html
33
+ <div class="figure-group" style="--rows: 2"><p>The crossbar sits below the centre of the A.</p>
34
+ <figure class="img-small"><img src="a.svg" alt="A with a low crossbar"></figure>
35
+ <p>This leaves room for the counter above.</p></div>
36
+ ```
37
+
38
+ Consecutive paragraphs join the group until another block intervenes or a
39
+ paragraph has a figure of its own. A figure immediately after a heading groups
40
+ with the paragraphs that follow it. A cut figure moves ahead of its paragraph
41
+ so text can wrap around a float.
42
+
43
+ Grouping applies to top-level article content. It skips lists, divs, details,
44
+ blockquotes, tables and nested figures. It preserves comments and the contents
45
+ of `script`, `style`, `pre` and `textarea`. Running it twice keeps a single wrapper.
46
+
47
+ ## Use with Python-Markdown
48
+
49
+ Enable the `vexy_figure_groups` extension to group figures in Markdown's final HTML,
50
+ after the renderer restores raw HTML blocks.
51
+
52
+ ```python
53
+ import markdown
54
+
55
+ text = """The crossbar sits below the centre of the A.
56
+
57
+ <figure class="img-small"><img src="a.svg" alt="A with a low crossbar"></figure>
58
+
59
+ This leaves room for the counter above."""
60
+ html = markdown.markdown(text, extensions=["md_in_html", "attr_list", "vexy_figure_groups"])
61
+ ```
62
+
63
+ Pass options through `extension_configs`, for example
64
+ `extension_configs={"vexy_figure_groups": {"group_class": "margin-note"}}`.
65
+
66
+ ## Use with rendered HTML
67
+
68
+ If a site creates figures after Markdown rendering, call the public
69
+ `group_figures()` function from your own plugin after the figures exist.
70
+ For example, a MkDocs plugin that creates figures in `on_page_content` can
71
+ return `group_figures(html)` at the end of that hook.
72
+
73
+ ```python
74
+ from vexy_markdown_figure_groups import group_figures
75
+
76
+ html = '<p>Check the crossbar.</p><figure class="img-cut"><img src="a.svg" alt="A"></figure>'
77
+ grouped = group_figures(html, group_class="fly-aside", cut_class="fly-cut")
78
+ ```
79
+
80
+ ## Options
81
+
82
+ The extension and the function accept the same options. Pass the function's
83
+ options by keyword. Use lists or tuples for class collections and literal CSS
84
+ identifiers for class names. Invalid names raise `ValueError`.
85
+
86
+ | Option | Default | Meaning |
87
+ | --- | --- | --- |
88
+ | `figure_classes` | `("img-small", "img-tall", "img-cut")` | Figure classes eligible for grouping. |
89
+ | `cut_classes` | `("img-cut",)` | Classes that move an eligible figure ahead of its paragraph. |
90
+ | `group_class` | `"figure-group"` | Class added to every wrapper. |
91
+ | `cut_class` | `"figure-group-cut"` | Additional wrapper class for cut figures. |
92
+ | `rows_property` | `"--rows"` | CSS custom property holding the paragraph count. Its name starts with `--`. |
93
+
94
+ ## Layout
95
+
96
+ On wide screens, give the figure a margin column spanning the paragraph rows.
97
+ Cut figures can float into the text instead.
98
+
99
+ ```css
100
+ @media (min-width: 48rem) {
101
+ .figure-group {
102
+ display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 16rem); column-gap: 2rem;
103
+ }
104
+ .figure-group > p { grid-column: 1; }
105
+ .figure-group > figure { grid-column: 2; grid-row: 1 / span var(--rows); margin: 0; }
106
+ .figure-group img { max-width: 100%; height: auto; }
107
+ .figure-group-cut { display: flow-root; }
108
+ .figure-group-cut > figure { float: right; width: 35%; margin: 0 0 1rem 1.5rem; }
109
+ }
110
+ ```
111
+
112
+ ## Releasing
113
+
114
+ For the first release, build from a clean checkout at the local `v0.1.0` tag
115
+ with `uv build`, then run `uv publish` on that machine using a PyPI API token.
116
+ In the project's PyPI publishing settings, register a GitHub trusted publisher
117
+ for `vexyart/vexy-python-markdown-figure-groups`, workflow `release.yml`,
118
+ environment `pypi`. Push a new `v*` tag for each subsequent release.
119
+
120
+ Licensed under Apache-2.0.
@@ -0,0 +1,72 @@
1
+ # this_file: pyproject.toml
2
+ [build-system]
3
+ requires = ["hatchling", "hatch-vcs"]
4
+ build-backend = "hatchling.build"
5
+
6
+ [project]
7
+ name = "vexy-python-markdown-figure-groups"
8
+ dynamic = ["version"]
9
+ description = "Group a margin figure with the paragraphs it illustrates in rendered HTML."
10
+ readme = "README.md"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ requires-python = ">=3.12"
14
+ authors = [{ name = "Vexy Lines Team", email = "help@vexy.art" }]
15
+ dependencies = ["Markdown>=3.5"]
16
+ keywords = ["markdown", "html", "figures", "margin figures"]
17
+ classifiers = [
18
+ "Development Status :: 4 - Beta",
19
+ "License :: OSI Approved :: Apache Software License",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Topic :: Text Processing :: Markup :: HTML",
24
+ "Typing :: Typed",
25
+ ]
26
+
27
+ [project.optional-dependencies]
28
+ dev = ["pytest", "pytest-cov", "ruff", "mypy", "types-Markdown"]
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/vexyart/vexy-python-markdown-figure-groups"
32
+ Repository = "https://github.com/vexyart/vexy-python-markdown-figure-groups"
33
+
34
+ [project.entry-points."markdown.extensions"]
35
+ vexy_figure_groups = "vexy_markdown_figure_groups:FigureGroupsExtension"
36
+
37
+ [tool.hatch.version]
38
+ source = "vcs"
39
+ raw-options = { fallback_version = "0.0.0" }
40
+
41
+ [tool.hatch.build.hooks.vcs]
42
+ version-file = "src/vexy_markdown_figure_groups/__version__.py"
43
+ template = """
44
+ # this_file: src/vexy_markdown_figure_groups/__version__.py
45
+ # Generated by hatch-vcs.
46
+ __version__ = "{version}"
47
+ """
48
+
49
+ [tool.hatch.build.targets.wheel]
50
+ packages = ["src/vexy_markdown_figure_groups"]
51
+
52
+ [tool.hatch.build.targets.sdist]
53
+ include = ["src/", "tests/", "README.md", "LICENSE", "CHANGELOG.md", "AGENTS.md", "DEPENDENCIES.md"]
54
+
55
+ [tool.ruff]
56
+ line-length = 100
57
+ target-version = "py312"
58
+
59
+ [tool.ruff.lint]
60
+ select = ["E", "W", "F", "I", "B", "C4", "UP", "ARG", "PIE", "PL", "RUF"]
61
+ ignore = ["PLR0913", "PLR2004"]
62
+
63
+ [tool.ruff.lint.per-file-ignores]
64
+ "tests/*" = ["ARG001"]
65
+
66
+ [tool.mypy]
67
+ python_version = "3.12"
68
+ strict = true
69
+ mypy_path = "src"
70
+
71
+ [tool.pytest.ini_options]
72
+ testpaths = ["tests"]
@@ -0,0 +1,12 @@
1
+ # this_file: src/vexy_markdown_figure_groups/__init__.py
2
+ """Group a margin figure with its paragraphs in rendered HTML."""
3
+
4
+ from .extension import FigureGroupsExtension, makeExtension
5
+ from .grouping import group_figures
6
+
7
+ __all__ = ["FigureGroupsExtension", "__version__", "group_figures", "makeExtension"]
8
+
9
+ try:
10
+ from .__version__ import __version__ as __version__
11
+ except ImportError:
12
+ __version__ = "0.0.0"
@@ -0,0 +1,3 @@
1
+ # this_file: src/vexy_markdown_figure_groups/__version__.py
2
+ # Generated by hatch-vcs.
3
+ __version__ = "0.1.0"
@@ -0,0 +1,39 @@
1
+ # this_file: src/vexy_markdown_figure_groups/extension.py
2
+ """Run figure grouping after Python-Markdown restores raw HTML."""
3
+
4
+ from markdown import Markdown
5
+ from markdown.extensions import Extension
6
+ from markdown.postprocessors import Postprocessor
7
+
8
+ from .grouping import DEFAULT_CUT_CLASSES, DEFAULT_FIGURE_CLASSES, group_figures
9
+
10
+
11
+ class _FigureGroupsPostprocessor(Postprocessor):
12
+ def __init__(self, md: Markdown, extension: Extension) -> None:
13
+ super().__init__(md)
14
+ self.extension = extension
15
+
16
+ def run(self, text: str) -> str:
17
+ return group_figures(text, **self.extension.getConfigs())
18
+
19
+
20
+ class FigureGroupsExtension(Extension):
21
+ """Group figures in the final HTML using the options accepted by group_figures."""
22
+
23
+ def __init__(self, **kwargs: object) -> None:
24
+ self.config = {
25
+ "figure_classes": [DEFAULT_FIGURE_CLASSES, "Classes that identify margin figures."],
26
+ "cut_classes": [DEFAULT_CUT_CLASSES, "Classes that move a figure ahead of its text."],
27
+ "group_class": ["figure-group", "Class for each group wrapper."],
28
+ "cut_class": ["figure-group-cut", "Additional wrapper class for cut figures."],
29
+ "rows_property": ["--rows", "CSS custom property holding the paragraph count."],
30
+ }
31
+ super().__init__(**kwargs)
32
+
33
+ def extendMarkdown(self, md: Markdown) -> None:
34
+ md.postprocessors.register(_FigureGroupsPostprocessor(md, self), "vexy_figure_groups", -100)
35
+
36
+
37
+ def makeExtension(**kwargs: object) -> FigureGroupsExtension:
38
+ """Create an extension instance for Python-Markdown."""
39
+ return FigureGroupsExtension(**kwargs)
@@ -0,0 +1,125 @@
1
+ # this_file: src/vexy_markdown_figure_groups/grouping.py
2
+ """Group margin figures in rendered article HTML while preserving the original markup."""
3
+
4
+ import re
5
+ from collections.abc import Sequence
6
+ from functools import lru_cache
7
+
8
+ DEFAULT_FIGURE_CLASSES = ("img-small", "img-tall", "img-cut")
9
+ DEFAULT_CUT_CLASSES = ("img-cut",)
10
+
11
+ _IDENTIFIER = re.compile(r"(?:--|-?(?:[A-Za-z_]|[^\x00-\x7f]))(?:[A-Za-z0-9_-]|[^\x00-\x7f])*")
12
+ _ATTRS = r"""(?:[^>"']|"[^"]*"|'[^']*')*"""
13
+ _OPAQUE = re.compile(r"<!--.*?-->|<(script|style|pre|textarea)\b.*?</\1\s*>", re.I | re.S)
14
+ _NESTING = re.compile(
15
+ rf"<(/?)(li|ul|ol|dl|div|details|blockquote|table|figure)(?=[\s>/])({_ATTRS})>", re.I
16
+ )
17
+ _PARA = r"<p\b[^>]*>(?:(?!</p>).)*</p>"
18
+ _SPACE = r" \t\n\f\r"
19
+ _FIGURE_CLASS = rf'<figure(?=[{_SPACE}]){_ATTRS}[{_SPACE}]class="[^"]*'
20
+ _FIGURE_START = re.compile(r"<figure\b", re.I)
21
+ _PARA_START = re.compile(r"<p\b", re.I)
22
+
23
+
24
+ def _identifier(name: str, option: str) -> str:
25
+ if not isinstance(name, str) or not _IDENTIFIER.fullmatch(name):
26
+ raise ValueError(f"{option} requires a literal CSS identifier, got {name!r}")
27
+ return name
28
+
29
+
30
+ def _class_names(names: Sequence[str], option: str) -> tuple[str, ...]:
31
+ if not isinstance(names, Sequence) or isinstance(names, (str, bytes, bytearray)):
32
+ raise ValueError(f"{option} requires a sequence of CSS class names")
33
+ return tuple(names)
34
+
35
+
36
+ def _class_pattern(names: tuple[str, ...], option: str) -> str:
37
+ if not names:
38
+ return "(?!)"
39
+ choices = "|".join(re.escape(_identifier(name, option)) for name in names)
40
+ return rf'(?<=["{_SPACE}])(?:{choices})(?=["{_SPACE}])'
41
+
42
+
43
+ @lru_cache
44
+ def _patterns(
45
+ figure_classes: tuple[str, ...],
46
+ cut_classes: tuple[str, ...],
47
+ group_class: str,
48
+ cut_class: str,
49
+ rows_property: str,
50
+ ) -> tuple[re.Pattern[str], re.Pattern[str]]:
51
+ selected = _class_pattern(figure_classes, "figure_classes")
52
+ cut = re.compile(_FIGURE_CLASS + _class_pattern(cut_classes, "cut_classes"), re.I)
53
+ _identifier(group_class, "group_class")
54
+ _identifier(cut_class, "cut_class")
55
+ if not _identifier(rows_property, "rows_property").startswith("--") or len(rows_property) == 2:
56
+ raise ValueError("rows_property requires a custom property name starting with '--'")
57
+
58
+ figure = rf'{_FIGURE_CLASS}{selected}[^"]*"{_ATTRS}>.*?</figure>'
59
+ following = rf"((?:\s*{_PARA}(?!\s*{figure}))*)"
60
+ groups = re.compile(
61
+ rf"({_PARA})(\s*)({figure}){following}"
62
+ rf"|(?<=</h[1-6]>)(\s*)({figure})(?=\s*<p\b){following}",
63
+ re.I | re.S,
64
+ )
65
+ return groups, cut
66
+
67
+
68
+ def group_figures(
69
+ html: str,
70
+ *,
71
+ figure_classes: Sequence[str] = DEFAULT_FIGURE_CLASSES,
72
+ cut_classes: Sequence[str] = DEFAULT_CUT_CLASSES,
73
+ group_class: str = "figure-group",
74
+ cut_class: str = "figure-group-cut",
75
+ rows_property: str = "--rows",
76
+ ) -> str:
77
+ """Wrap top-level margin figures with adjacent paragraphs and count their rows.
78
+
79
+ Start with the figure's preceding paragraph, or with the figure itself after a
80
+ heading. Stop at the next non-paragraph or paragraph with its own figure. Cut
81
+ figures move before their paragraph so text can flow around a floated figure.
82
+ """
83
+ try:
84
+ groups, cut = _patterns(
85
+ _class_names(figure_classes, "figure_classes"),
86
+ _class_names(cut_classes, "cut_classes"),
87
+ group_class,
88
+ cut_class,
89
+ rows_property,
90
+ )
91
+ except TypeError as exc:
92
+ # Unhashable option values cannot enter the configuration cache.
93
+ raise ValueError("class names and rows_property must be strings") from exc
94
+
95
+ masked = _OPAQUE.sub(lambda m: " " * len(m[0]), html)
96
+ parts: list[str] = []
97
+ containers = _NESTING.finditer(masked)
98
+ tag = next(containers, None)
99
+ depth = 0
100
+ last = 0
101
+ for match in groups.finditer(masked):
102
+ while tag is not None and tag.end() <= match.start():
103
+ if not tag[3].endswith("/"):
104
+ depth += -1 if tag[1] else 1
105
+ tag = next(containers, None)
106
+ paragraph, gap, after_paragraph, tail, leading, after_heading, rest = match.groups()
107
+ fig = after_paragraph or after_heading
108
+ if (
109
+ html[match.start() : match.end()] != match[0]
110
+ or depth
111
+ or len(_FIGURE_START.findall(fig)) != 1
112
+ ):
113
+ continue
114
+ is_cut = cut.match(fig)
115
+ cls = f"{group_class} {cut_class}" if is_cut else group_class
116
+ if paragraph is None:
117
+ rows = len(_PARA_START.findall(rest))
118
+ inner = fig + rest
119
+ else:
120
+ rows = 1 + len(_PARA_START.findall(tail))
121
+ inner = (fig + gap + paragraph if is_cut else paragraph + gap + fig) + tail
122
+ parts.extend((html[last : match.start()], leading or ""))
123
+ parts.append(f'<div class="{cls}" style="{rows_property}: {rows}">{inner}</div>')
124
+ last = match.end()
125
+ return "".join(parts) + html[last:]
@@ -0,0 +1,48 @@
1
+ # this_file: tests/test_extension.py
2
+ """Exercise the installed Python-Markdown entry point with rendered and raw HTML."""
3
+
4
+ from importlib.metadata import distribution
5
+
6
+ import markdown
7
+
8
+ from vexy_markdown_figure_groups import FigureGroupsExtension, group_figures, makeExtension
9
+
10
+
11
+ def test_figure_groups_when_installed_then_extension_is_discoverable() -> None:
12
+ entries = distribution("vexy-python-markdown-figure-groups").entry_points
13
+ (entry,) = entries.select(group="markdown.extensions")
14
+ assert entry.name == "vexy_figure_groups"
15
+ assert isinstance(entry.load()(), FigureGroupsExtension)
16
+ assert isinstance(makeExtension(), FigureGroupsExtension)
17
+
18
+
19
+ def test_figure_groups_when_markdown_restores_raw_figure_then_groups_rendered_paragraphs() -> None:
20
+ figure = '<figure class="img-small">Diagram</figure>'
21
+ source = f"A *line*.\n{{: .lead}}\n\n{figure}\n\nAnother line."
22
+ html = markdown.markdown(source, extensions=["md_in_html", "attr_list", "vexy_figure_groups"])
23
+ assert html.startswith('<div class="figure-group" style="--rows: 2"><p class="lead">')
24
+ assert "<em>line</em>" in html
25
+ assert figure in html
26
+ assert html.endswith("<p>Another line.</p></div>")
27
+
28
+
29
+ def test_figure_groups_when_configured_then_matches_custom_function_options() -> None:
30
+ figure = '<figure class="-inset">Diagram</figure>'
31
+ source = f"Text.\n\n{figure}"
32
+ options = {
33
+ "figure_classes": ["-inset"],
34
+ "cut_classes": ["-inset"],
35
+ "group_class": "_box",
36
+ "cut_class": "cut-2",
37
+ "rows_property": "--line-count",
38
+ }
39
+ expected = f'<div class="_box cut-2" style="--line-count: 1">{figure}\n<p>Text.</p></div>'
40
+ assert group_figures(f"<p>Text.</p>\n{figure}", **options) == expected
41
+ assert (
42
+ markdown.markdown(
43
+ source,
44
+ extensions=["vexy_figure_groups"],
45
+ extension_configs={"vexy_figure_groups": options},
46
+ )
47
+ == expected
48
+ )
@@ -0,0 +1,217 @@
1
+ # this_file: tests/test_grouping.py
2
+ """Golden HTML examples remain runnable without the theme checkout."""
3
+
4
+ from time import perf_counter
5
+
6
+ import pytest
7
+
8
+ from vexy_markdown_figure_groups import group_figures
9
+
10
+ SMALL = '<figure class="img-small"><img/></figure>'
11
+ TALL = '<figure class="img-tall"><img/></figure>'
12
+ CUT = '<figure class="img-cut"><img/></figure>'
13
+ IMAGE = '<figure class="img-small"><img src="s.png"/></figure>'
14
+ A = "<p>a</p>"
15
+ B = "<p>b</p>"
16
+ C = "<p>c</p>"
17
+ D = "<p>d</p>"
18
+ DEPTH_PREFIX = '<div data-x="a/>"><!-- <div> </li> --><script>"</div>"</script><p>'
19
+
20
+
21
+ # Expected HTML from group_margin_figures in fontlab-www-docstheme.fly,
22
+ # commit 29f882097424964e79c5429848c2764c3962cb57, theme/fly_january/markup.py.
23
+ # Each tuple is (description, original HTML, expected HTML). None means byte-for-byte unchanged.
24
+ CASES = [
25
+ (
26
+ "small figure after inline markup",
27
+ f"{A}\n<p>b <em>x</em></p>\n{IMAGE}\n<h2>H</h2>",
28
+ '<p>a</p>\n<div class="fly-aside" style="--rows: 1"><p>b <em>x</em></p>\n'
29
+ '<figure class="img-small"><img src="s.png"/></figure></div>\n<h2>H</h2>',
30
+ ),
31
+ (
32
+ "following paragraphs count as rows",
33
+ f"{A}{TALL}\n{B}\n{C}<ul><li>x</li></ul>",
34
+ '<div class="fly-aside" style="--rows: 3"><p>a</p><figure class="img-tall"><img/>'
35
+ "</figure>\n<p>b</p>\n<p>c</p></div><ul><li>x</li></ul>",
36
+ ),
37
+ ("wide figure", f'{B}<figure class="img-wide"><img/></figure>', None),
38
+ ("heading without a following paragraph", f"<h3>H</h3>{SMALL}", None),
39
+ (
40
+ "paragraph with its own figure",
41
+ f"{A}{SMALL}{B}{C}{TALL}{D}",
42
+ '<div class="fly-aside" style="--rows: 2"><p>a</p><figure class="img-small"><img/>'
43
+ '</figure><p>b</p></div><div class="fly-aside" style="--rows: 2"><p>c</p>'
44
+ '<figure class="img-tall"><img/></figure><p>d</p></div>',
45
+ ),
46
+ ("list item", f"<ul><li>{A}{SMALL}{B}</li></ul>", None),
47
+ ("admonition", f'<div class="admonition note">{A}{SMALL}</div>', None),
48
+ ("details", f"<details><summary>s</summary>{A}{SMALL}</details>", None),
49
+ (
50
+ "paragraph after a closed list",
51
+ f"<ul><li>x</li></ul>{A}{SMALL}",
52
+ '<ul><li>x</li></ul><div class="fly-aside" style="--rows: 1"><p>a</p>'
53
+ '<figure class="img-small"><img/></figure></div>',
54
+ ),
55
+ (
56
+ "heading followed by figure and paragraphs",
57
+ f"<h3>H</h3>\n{TALL}\n{A}\n{B}<h3>I</h3>",
58
+ '<h3>H</h3>\n<div class="fly-aside" style="--rows: 2"><figure class="img-tall">'
59
+ "<img/></figure>\n<p>a</p>\n<p>b</p></div><h3>I</h3>",
60
+ ),
61
+ (
62
+ "outer figure containing a figure",
63
+ f'{A}<figure class="img-small"><figure><img/></figure><figcaption>c</figcaption></figure>',
64
+ None,
65
+ ),
66
+ ("paragraph inside a figure", f"<figure>{A}{SMALL}</figure>", None),
67
+ ("table", f"<table><tr><td>{A}{SMALL}</td></tr></table>", None),
68
+ ("comment", f"<!-- {A}{SMALL} -->", None),
69
+ ("pre", f"<pre>{A}{SMALL}</pre>", None),
70
+ (
71
+ "closing div in comment",
72
+ f'<div class="admonition"><!-- </div> -->{A}{SMALL}</div>',
73
+ None,
74
+ ),
75
+ (
76
+ "cut moves before its paragraph",
77
+ f"{A}\n{CUT}\n{B}\n<h2>H</h2>",
78
+ '<div class="fly-aside fly-cut" style="--rows: 2"><figure class="img-cut"><img/>'
79
+ "</figure>\n<p>a</p>\n<p>b</p></div>\n<h2>H</h2>",
80
+ ),
81
+ (
82
+ "cut after heading",
83
+ f"<h3>H</h3>\n{CUT}\n{B}",
84
+ '<h3>H</h3>\n<div class="fly-aside fly-cut" style="--rows: 1">'
85
+ '<figure class="img-cut"><img/></figure>\n<p>b</p></div>',
86
+ ),
87
+ ("depth prefix", DEPTH_PREFIX, None),
88
+ *(
89
+ (tag, f"<{tag}>{A}{SMALL}</{tag}>", None)
90
+ for tag in ("script", "style", "textarea", "ol", "dl", "blockquote")
91
+ ),
92
+ ("opaque content between blocks", f"{A}<!-- intervening comment -->{SMALL}", None),
93
+ (
94
+ "depth through quoted attributes and opaque regions",
95
+ f"{DEPTH_PREFIX}nested</p>{SMALL}</div>{B}{SMALL}",
96
+ '<div data-x="a/>"><!-- <div> </li> --><script>"</div>"</script><p>nested</p>'
97
+ '<figure class="img-small"><img/></figure></div>'
98
+ '<div class="fly-aside" style="--rows: 1"><p>b</p><figure class="img-small"><img/>'
99
+ "</figure></div>",
100
+ ),
101
+ (
102
+ "mixed-case HTML and multiple classes",
103
+ '<P>a</P>\t<FIGURE CLASS="photo IMG-CUT lead">x</FIGURE>',
104
+ '<div class="fly-aside fly-cut" style="--rows: 1">'
105
+ '<FIGURE CLASS="photo IMG-CUT lead">x</FIGURE>\t<P>a</P></div>',
106
+ ),
107
+ ]
108
+
109
+ THEME_OPTIONS = {
110
+ "figure_classes": ("img-small", "img-tall", "img-cut"),
111
+ "cut_classes": ("img-cut",),
112
+ "group_class": "fly-aside",
113
+ "cut_class": "fly-cut",
114
+ }
115
+
116
+
117
+ @pytest.mark.parametrize("html,expected", [(h, e) for _, h, e in CASES], ids=[c[0] for c in CASES])
118
+ def test_group_figures_when_given_article_blocks_then_preserves_or_groups_them(
119
+ html: str, expected: str | None
120
+ ) -> None:
121
+ first = group_figures(html, **THEME_OPTIONS)
122
+ assert first.encode() == (html if expected is None else expected).encode()
123
+ assert group_figures(first, **THEME_OPTIONS) == first
124
+
125
+
126
+ def test_group_figures_when_using_defaults_then_emits_default_classes() -> None:
127
+ assert group_figures(A + CUT) == (
128
+ f'<div class="figure-group figure-group-cut" style="--rows: 1">{CUT}{A}</div>'
129
+ )
130
+ assert group_figures(A + SMALL) == (
131
+ f'<div class="figure-group" style="--rows: 1">{A}{SMALL}</div>'
132
+ )
133
+
134
+
135
+ @pytest.mark.parametrize(
136
+ "attrs",
137
+ [
138
+ 'class="not-img-small"',
139
+ 'class="img-small-x"',
140
+ 'class="img-tall.other"',
141
+ 'data-class="img-small" class="photo"',
142
+ """class="photo" title='uses class="img-small"'""",
143
+ ],
144
+ )
145
+ def test_group_figures_when_class_token_is_absent_then_preserves_html(attrs: str) -> None:
146
+ html = f"{A}<figure {attrs}>Map</figure>"
147
+ assert group_figures(html) == html
148
+
149
+
150
+ @pytest.mark.parametrize(
151
+ "classes", ["img-cut photo lead", "photo\timg-cut\nlead", "lead photo img-cut"]
152
+ )
153
+ def test_group_figures_when_cut_class_occurs_anywhere_then_moves_figure(classes: str) -> None:
154
+ fig = f'<figure class="{classes}">Map</figure>'
155
+ assert group_figures(A + fig) == (
156
+ f'<div class="figure-group figure-group-cut" style="--rows: 1">{fig}{A}</div>'
157
+ )
158
+
159
+
160
+ def test_group_figures_when_cut_class_is_partial_then_keeps_order() -> None:
161
+ html = f'{A}<figure class="not-img-cut img-small img-cut-x">Map</figure>'
162
+ assert group_figures(html) == f'<div class="figure-group" style="--rows: 1">{html}</div>'
163
+
164
+
165
+ def test_group_figures_when_class_list_changes_then_uses_current_options() -> None:
166
+ html = A + SMALL
167
+ classes = ["img-small"]
168
+ assert group_figures(html, figure_classes=classes) == group_figures(html)
169
+ classes[0] = "small"
170
+ assert group_figures(html, figure_classes=classes) == html
171
+
172
+
173
+ def test_group_figures_when_grouping_a_thousand_figures_then_finishes_within_a_second() -> None:
174
+ separator = f"<blockquote>{A}{SMALL}</blockquote>"
175
+ html = (A + SMALL + separator) * 1000
176
+ start = perf_counter()
177
+ grouped = group_figures(html)
178
+ elapsed = perf_counter() - start
179
+ assert (
180
+ grouped
181
+ == (f'<div class="figure-group" style="--rows: 1">{A}{SMALL}</div>' + separator) * 1000
182
+ )
183
+ assert elapsed < 1, f"Grouping 1,000 figures took {elapsed:.3f}s"
184
+
185
+
186
+ def test_group_figures_when_class_has_nonbreaking_space_then_matches_whole_token() -> None:
187
+ name = "map\u00a0side"
188
+ html = f'{A}<figure class="{name}">Map</figure>'
189
+ assert group_figures(html, figure_classes=("side",)) == html
190
+ assert group_figures(html, figure_classes=(name,)) == (
191
+ f'<div class="figure-group" style="--rows: 1">{html}</div>'
192
+ )
193
+
194
+
195
+ def test_group_figures_when_classes_are_empty_then_disables_requested_rule() -> None:
196
+ assert group_figures(A + SMALL, figure_classes=()) == A + SMALL
197
+ assert group_figures(A + CUT, cut_classes=()) == (
198
+ f'<div class="figure-group" style="--rows: 1">{A}{CUT}</div>'
199
+ )
200
+
201
+
202
+ @pytest.mark.parametrize(
203
+ "options",
204
+ [
205
+ {"figure_classes": ("img-small", "x|y")},
206
+ {"figure_classes": ("9bad",)},
207
+ {"figure_classes": "tiny"},
208
+ {"figure_classes": [["img-small"]]},
209
+ {"cut_classes": ("tiny image",)},
210
+ {"group_class": 'g" onclick="bad'},
211
+ {"cut_class": ""},
212
+ {"rows_property": "--rows; color:red"},
213
+ ],
214
+ )
215
+ def test_group_figures_when_option_is_invalid_then_raises_value_error(options: dict) -> None:
216
+ with pytest.raises(ValueError):
217
+ group_figures("", **options)