From d583313bb1ff7b01a47b082b716da0b8cde4c6f7 Mon Sep 17 00:00:00 2001 From: Chris Sewell Date: Tue, 10 Nov 2026 13:24:08 +0100 Subject: [PATCH 1/3] =?UTF-8?q?=F0=9F=94=A7=20Drop=20sd=5Fcustom=5Froles:?= =?UTF-8?q?=20the=20badge=20roles=20take=20a=20tooltip=20role=20option?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove the unreleased `sd_custom_roles` setting (#295) before it ships in 0.8.0: its config value and validation, the role registration and the process-global registry handling, its documentation and its tests. The badge-role refactor from #295 stays: `_iter_badge_roles` is still the single source of the badge family, and every badge role is built by one constructor that accepts a default tooltip. In its place, the badge roles (plain, link and ref, in every colour) now accept a standard `tooltip` role option, read from the docutils role-function options dictionary. A reStructuredText custom role can preset it (`.. role:: bdg-stable(bdg-success)` with `:tooltip:`), and an extension that presets a badge role passes it the same way. A `; tooltip` suffix still wins over the option, which wins over the constructor default. The docs describe the option, for authors and for extension authors, and recommend the sphinx-ub-directives package for project-defined directive presets. `sd_custom_directives` is unchanged. --- docs/badges_buttons.md | 119 +++----- docs/conf.py | 8 - docs/get_started.md | 13 +- sphinx_design/badges_buttons.py | 164 ++++------- sphinx_design/config.py | 74 ----- sphinx_design/extension.py | 3 +- tests/test_badge_tooltip_option.py | 329 +++++++++++++++++++++ tests/test_custom_roles.py | 455 ----------------------------- tests/test_misc.py | 55 ---- 9 files changed, 433 insertions(+), 787 deletions(-) create mode 100644 tests/test_badge_tooltip_option.py delete mode 100644 tests/test_custom_roles.py diff --git a/docs/badges_buttons.md b/docs/badges_buttons.md index ca0064cc..ccdf942d 100644 --- a/docs/badges_buttons.md +++ b/docs/badges_buttons.md @@ -53,83 +53,11 @@ The syntax is the same as for the `ref` role. ```` ````` -(sd-custom-badge-roles)= - -### Custom badge roles - -When the **same** badge recurs throughout your documentation — status labels -such as *stable*, *beta* or *deprecated* whose colour and tooltip never change — -define it **once** as a custom role via the `sd_custom_roles` configuration -option, rather than retyping the colour and tooltip at every use site. This is -the recommended pattern for such repeated, semantic badges: - -```python -sd_custom_roles = { - "bdg-stable": { - "inherit": "bdg-success", - "tooltip": "A released, supported version", - }, - "bdg-beta": {"inherit": "bdg-warning", "tooltip": "Interface may change"}, - "bdg-deprecated": {"inherit": "bdg-danger", "tooltip": "Scheduled for removal"}, -} -``` - -Each key is the new role name to register; the value is a dictionary with: - -- `inherit` (required): the built-in badge role to inherit from — any of the - `bdg`, `bdg-`, `bdg--line`, `bdg-link-*` or `bdg-ref-*` roles. -- `tooltip` (optional): a default tooltip, applied as the HTML `title` whenever - the role is used *without* a per-instance `; tooltip` suffix. For a - `bdg-link-*`/`bdg-ref-*` role the baked tooltip applies even to the bare - form (`` {bdg-link-*}`` ``), where the suffix grammar deliberately - refuses to split, and it overrides a reference's automatic title. - -Give custom roles a distinguishing prefix (the `bdg-` convention used here is a -good choice): a name that collides with a docutils built-in (`code`, `math`, -`strong`, …) or another extension's role is skipped, so `bdg-`-prefixed names -keep you clear of every such clash. - -The new role then behaves exactly like the role it inherits (same rendering, -links and references), with its tooltip baked in: - -{bdg-stable}`v2.1` {bdg-beta}`v3.0rc1` {bdg-deprecated}`v1.0` - -````{tab-set-code} -```markdown -{bdg-stable}`v2.1` {bdg-beta}`v3.0rc1` {bdg-deprecated}`v1.0` -``` -```rst -:bdg-stable:`v2.1` :bdg-beta:`v3.0rc1` :bdg-deprecated:`v1.0` -``` -```` - -A baked `tooltip` is only the *default*: a per-instance `; tooltip` suffix on an -individual badge **overrides** it, so a config-defined role covers the common -case while the suffix stays available for the occasional one-off: - -{bdg-stable}`v2.1 ; Long-term support release` - -````{tab-set-code} -```markdown -{bdg-stable}`v2.1 ; Long-term support release` -``` -```rst -:bdg-stable:`v2.1 ; Long-term support release` -``` -```` - -Custom roles are the badge analogue of -{ref}`custom directives `. Inheritance is limited to the -badge family listed above; a role whose `inherit` names an unknown badge role, -or whose own name clashes with an existing role, is skipped with a warning. -Editing an entry (or removing it) is picked up on the next build. - ### Badge tooltips -For a **one-off** tooltip (shown on hover, via the HTML `title` attribute) — -rather than a repeated one better served by a -{ref}`custom badge role ` — append a `; tooltip` suffix -to any badge's text. This works for every badge family: +Any badge can be given a tooltip (shown on hover, via the HTML `title` +attribute) by appending a `; tooltip` suffix to its text. +This works for every badge family: {bdg-primary}`stable ; A released, supported version` {bdg-link-info}`docs ; Opens the documentation` @@ -162,6 +90,47 @@ tooltip to a link/ref badge, use the explicit form: `` {bdg-link-primary}`docs ; Opens the docs` ``. A `bdg-ref` tooltip overrides the reference's automatic title. +(sd-badge-tooltip-option)= + +#### The `tooltip` role option + +When the same badge recurs throughout your documentation, such as a status label +whose colour and tooltip never change, it can be defined once instead. +Every badge role accepts a `tooltip` role option, which is the badge's tooltip +when its text has no `; tooltip` suffix (a suffix still overrides it). +In reStructuredText, set it with the `role` directive, which defines a new role based on a badge role: + +```rst +.. role:: bdg-stable(bdg-success) + :tooltip: A released, supported version + +:bdg-stable:`v2.1` :bdg-stable:`v2.2 ; Long-term support release` +``` + +```{eval-rst} +.. role:: bdg-stable(bdg-success) + :tooltip: A released, supported version + +:bdg-stable:`v2.1` :bdg-stable:`v2.2 ; Long-term support release` +``` + +The option also applies to the bare `` form of the link and reference badges, +where the `; tooltip` suffix is not recognised. + +For extension authors: the badge roles follow the docutils convention for role functions. +Their option specification is the role's `options` attribute (`{"tooltip": ...}`), +and the option is read from the `options` dictionary passed to each call, +so an extension that presets a badge role passes `options={"tooltip": "..."}`. + +:::{tip} +To define such presets in your project configuration rather than in each document, +we recommend the [sphinx-ub-directives](https://sphinx-ub-directives.readthedocs.io) package, +from the [sphinx-needs](https://github.com/useblocks/sphinx-needs) project. +Its directive presets already accept sphinx-design directives as a base +and also work in [ubCode](https://ubcode.useblocks.com/); +role presets are planned there. +::: + ```{warning} `title` tooltips are **not** accessible to keyboard or touch users, and are not surfaced by all screen readers. Do not put essential information in a diff --git a/docs/conf.py b/docs/conf.py index 8726be5d..6dfdc803 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -41,14 +41,6 @@ }, } } -sd_custom_roles = { - "bdg-stable": { - "inherit": "bdg-success", - "tooltip": "A released, supported version", - }, - "bdg-beta": {"inherit": "bdg-warning", "tooltip": "Interface may change"}, - "bdg-deprecated": {"inherit": "bdg-danger", "tooltip": "Scheduled for removal"}, -} extlinks = { "pr": ("https://github.com/executablebooks/sphinx-design/pull/%s", "PR #%s"), diff --git a/docs/get_started.md b/docs/get_started.md index dff06869..f59d97d2 100644 --- a/docs/get_started.md +++ b/docs/get_started.md @@ -88,9 +88,16 @@ The key is the new directive name to add, and the value is a dictionary with the - `argument`: The default argument (optional, only for directives that take a single argument) - `options`: A dictionary of default options for the directive (optional) -The same idea is available for roles: `sd_custom_roles` defines reusable badge -roles (e.g. status badges), inheriting a built-in badge role and optionally -baking in a tooltip. See {ref}`Custom badge roles `. +:::{tip} +For project-defined directive presets, we recommend the +[sphinx-ub-directives](https://sphinx-ub-directives.readthedocs.io) package, +from the [sphinx-needs](https://github.com/useblocks/sphinx-needs) project. +Its directive presets already accept sphinx-design directives (such as `dropdown`) as a base, +can be configured in `conf.py` or `ubproject.toml`, +and also work in [ubCode](https://ubcode.useblocks.com/). +Role presets are planned there; until then, a badge role can be preset with +its {ref}`tooltip role option `. +::: ## Supported browsers diff --git a/sphinx_design/badges_buttons.py b/sphinx_design/badges_buttons.py index d24ad563..940702b8 100644 --- a/sphinx_design/badges_buttons.py +++ b/sphinx_design/badges_buttons.py @@ -1,25 +1,19 @@ -from collections.abc import Iterator, Sequence +from collections.abc import Callable, Iterator, Sequence import re -from typing import Any +from typing import Any, ClassVar from docutils import nodes from docutils.parsers.rst import directives -from docutils.parsers.rst import roles as rst_roles from docutils.parsers.rst.states import Inliner, RSTState from docutils.utils import unescape from sphinx import addnodes from sphinx.application import Sphinx -from sphinx.config import Config from sphinx.transforms.post_transforms import SphinxPostTransform from sphinx.util import ws_re from sphinx.util.docutils import ReferenceRole, SphinxRole -from sphinx.util.logging import getLogger -from sphinx_design.config import WARNING_TYPE, SdConfig from sphinx_design.shared import SEMANTIC_COLORS, SdDirective, make_choice, text_align -LOGGER = getLogger(__name__) - ROLE_NAME_BADGE_PREFIX = "bdg" ROLE_NAME_LINK_PREFIX = "bdg-link" ROLE_NAME_REF_PREFIX = "bdg-ref" @@ -38,16 +32,10 @@ def _iter_badge_roles() -> Iterator[BadgeRoleSpec]: """Yield the ``(name, role_class, color, outline)`` of every built-in badge role. - This is the single source of truth for the badge role family, used both to - register the roles (:func:`setup_badges_and_buttons`) and to resolve an - ``sd_custom_roles`` ``inherit`` target (:func:`setup_custom_roles`). - - .. note:: - - The custom-role ``inherit`` mechanism is deliberately limited to this - badge family in v1. Extending it to the icon roles (``icons.py``) or the - button *roles* would mean yielding those here too, and giving their role - constructors the same ``tooltip`` keyword the badge roles now accept. + This is the single source of truth for the badge role family, used to + register the roles (:func:`setup_badges_and_buttons`). Every role class + shares the :class:`_TooltipRoleMixin` constructor and its ``tooltip`` role + option. """ yield ROLE_NAME_BADGE_PREFIX, BadgeRole, None, False yield ROLE_NAME_LINK_PREFIX, LinkBadgeRole, None, False @@ -102,91 +90,6 @@ def setup_badges_and_buttons(app: Sphinx) -> None: app.add_post_transform(BadgeRefTooltipGraft) -#: Marker attribute set on the role instances this extension registers from -#: ``sd_custom_roles``. docutils' role registry (``roles._roles``) is -#: process-global and shared across Sphinx apps, so carrying "ownership" on the -#: stored role object itself lets every ``config-inited`` reconcile *our* roles -#: (refresh or unregister) without a side table that could drift from the -#: registry - e.g. across the many apps a test session builds. -_SD_CUSTOM_ROLE_ATTR = "_sd_custom_role" - - -def _role_name_taken(name: str) -> bool: - """Return whether ``name`` already resolves to a role. - - docutils looks roles up case-insensitively, so the lower-cased name is - compared against both the locally registered roles (``roles._roles``, the - registry Sphinx's own ``add_role`` consults) *and* docutils' canonical - built-in roles (``roles._role_registry``: ``code``/``math``/``strong``/ - ``emphasis``/``literal``/... ). Both are long-stable private attributes; - docutils exposes no public query for either. - """ - key = name.lower() - return key in rst_roles._roles or key in rst_roles._role_registry - - -def setup_custom_roles(app: Sphinx, config: Config) -> None: - """Register (and reconcile) the custom roles declared in ``sd_custom_roles``. - - Parallel to :func:`sphinx_design.shared.setup_custom_directives`: each entry - inherits a built-in sphinx-design *badge* role (v1 scope; see - :func:`_iter_badge_roles`), optionally baking in a default ``tooltip`` used - whenever no per-instance ``; suffix`` overrides it. - - The entry shapes have already been validated on ``config-inited`` - (see ``sphinx_design.config``); here we additionally check ``inherit`` - against the known badge roles. Because it runs on every ``config-inited`` - against a process-global registry, the reconciliation policy is: - - * a name we registered before is **refreshed** (re-registered with override, - picking up tooltip/inherit edits on an in-process rebuild); - * a name we registered before but now absent from the config is - **unregistered**, so it never leaks into a later build or sibling app; - * a name clashing with a *foreign* role (another extension's, or a docutils - built-in such as ``code``/``strong``) is skipped with a warning. - """ - - def _warn(msg: str) -> None: - LOGGER.warning(f"sd_custom_roles: {msg}", type=WARNING_TYPE, subtype="config") - - specs = { - name: (role_cls, color, outline) - for name, role_cls, color, outline in _iter_badge_roles() - } - # extension point: to also inherit icon/button roles, yield them from - # ``_iter_badge_roles`` (and give those constructors a ``tooltip`` keyword). - - # decide the roles to (re)register: a known ``inherit``, and a name that is - # either already ours (refresh) or free (a foreign clash is skipped) - desired: dict[str, tuple[str, dict[str, Any]]] = {} # lower name -> (name, data) - for name, data in SdConfig.from_sphinx(config).custom_roles.items(): - inherit = data["inherit"] - if inherit not in specs: - _warn(f"'{name}.inherit' is an unknown badge role: {inherit}") - continue - existing = rst_roles._roles.get(name.lower()) - if not getattr(existing, _SD_CUSTOM_ROLE_ATTR, False) and _role_name_taken( - name - ): - _warn(f"'{name}' clashes with an existing role, skipping") - continue - desired[name.lower()] = (name, data) - - # unregister any of *our* previously-registered roles dropped from the config - # (the registry is process-global, so this is what stops a stale role - # resolving in a later in-process build or a sibling app) - for key, role in list(rst_roles._roles.items()): - if getattr(role, _SD_CUSTOM_ROLE_ATTR, False) and key not in desired: - del rst_roles._roles[key] - - # (re)register, refreshing tooltip/inherit changes via ``override=True`` - for name, data in desired.values(): - role_cls, color, outline = specs[data["inherit"]] - role = role_cls(color, outline=outline, tooltip=data.get("tooltip")) - setattr(role, _SD_CUSTOM_ROLE_ATTR, True) - app.add_role(name, role, override=True) - - def create_bdg_classes(color: str | None, outline: bool) -> list[str]: """Create the badge classes.""" classes = [ @@ -347,10 +250,20 @@ class _TooltipRoleMixin(SphinxRole): so that ``ReferenceRole``'s title/target parsing still applies to it. The badge roles share this constructor (``color``/``outline``, plus an - optional baked ``tooltip``), so that they - and any config-defined roles - inheriting them (see :func:`setup_custom_roles`) - are built uniformly. + optional default ``tooltip``), and a ``tooltip`` role option (see + :attr:`OPTION_SPEC`). The tooltip of a role invocation is, in order of + precedence: its ``; tooltip`` suffix, the ``tooltip`` role option, then the + constructor default. """ + #: The options the badge roles accept, e.g. from a custom role:: + #: + #: .. role:: bdg-stable(bdg-success) + #: :tooltip: A released, supported version + OPTION_SPEC: ClassVar[dict[str, Callable[[str], Any]]] = { + "tooltip": directives.unchanged_required, + } + #: the tooltip parsed from the current role invocation, if any tooltip: str | None = None @@ -370,16 +283,22 @@ def __init__( :param color: the semantic colour, or ``None`` for the plain badge. :param outline: whether to use the outline (``-line``) variant. - :param tooltip: a baked-in default tooltip, used when no per-instance - ``; suffix`` overrides it (set by config-defined roles). An explicit - suffix always wins. ``None`` for the built-in roles, keeping their - output byte-identical. + :param tooltip: a default tooltip, used when neither a per-instance + ``; suffix`` nor a ``tooltip`` role option is given. ``None`` for + the built-in roles, keeping their output byte-identical. """ super().__init__() self.color = color self.outline = outline - #: the baked default tooltip (see the ``tooltip`` parameter) + #: the default tooltip (see the ``tooltip`` parameter) self.default_tooltip = tooltip + #: this role's option specification: a copy of :attr:`OPTION_SPEC`, + #: since docutils adds a ``class`` option to it when registering the role + self.option_spec = dict(self.OPTION_SPEC) + # between calls, ``options`` is the option specification, which is + # where docutils' ``role`` directive (and any extension presetting a + # role) looks for it, in the docutils convention for role functions + self.options = self.option_spec def __call__( # noqa: PLR0913, PLR0917 self, @@ -391,7 +310,13 @@ def __call__( # noqa: PLR0913, PLR0917 options: dict[str, Any] | None = None, content: Sequence[str] = (), ) -> tuple[list[nodes.Node], list[nodes.system_message]]: - """Split off any tooltip, then defer to the base role.""" + """Split off any tooltip, then defer to the base role. + + ``options`` is the docutils role-function options dictionary: a + ``tooltip`` entry in it (as passed by a ``.. role::`` custom role, or by + an extension calling the role) is used when the text has no ``;`` + tooltip suffix. + """ # ``text`` differs by parser: docutils (rST) encodes a backslash escape # as a NUL marker (``\x00``) + the escaped char, while myst-parser # passes backslashes through verbatim. Restoring NULs to backslashes - @@ -419,10 +344,19 @@ def __call__( # noqa: PLR0913, PLR0917 # no-op for rST, whose escapes are NUL-encoded and resolved downstream text = _RAW_ESCAPED_SEMICOLON_RE.sub(";", text) if self.tooltip is None: - # no per-instance suffix: fall back to any baked default (``None`` - # for the built-in roles). A suffix, when present, always wins. - self.tooltip = self.default_tooltip - return super().__call__(name, rawtext, text, lineno, inliner, options, content) + # no per-instance suffix: fall back to the ``tooltip`` role option, + # then to the constructor default (``None`` for the built-in roles). + # A suffix, when present, always wins. + self.tooltip = (options or {}).get("tooltip") or self.default_tooltip + try: + return super().__call__( + name, rawtext, text, lineno, inliner, options, content + ) + finally: + # ``SphinxRole.__call__`` stores this call's options as ``options``, + # where docutils' ``role`` directive reads the option specification + # from: restore it, so a later ``.. role:: x(bdg-info)`` can use it + self.options = self.option_spec class BadgeRole(_TooltipRoleMixin): diff --git a/sphinx_design/config.py b/sphinx_design/config.py index fee151d7..7522104c 100644 --- a/sphinx_design/config.py +++ b/sphinx_design/config.py @@ -22,7 +22,6 @@ from __future__ import annotations import dataclasses as dc -import re from typing import TYPE_CHECKING, Any, Protocol from sphinx.util.logging import getLogger @@ -204,70 +203,6 @@ def validate_custom_directives( validate_custom_directive(field, name, data) -#: The keys a single ``sd_custom_roles`` entry may declare. -CUSTOM_ROLE_KEYS = ("inherit", "tooltip") - -#: A syntactically usable role name: non-empty and free of whitespace (which -#: docutils' inline-role parser can never match). Unicode letters, digits, -#: hyphens, colons and mixed case are all accepted (docutils looks roles up -#: case-insensitively). -_ROLE_NAME_RE = re.compile(r"\A\S+\Z") - - -def validate_custom_role(field: dc.Field[Any], name: Any, data: Any) -> None: - """Validate the shape of a single custom role (name -> data) entry. - - Note, whether ``data["inherit"]`` refers to a known sphinx-design badge - role can only be checked at registration time - (see ``sphinx_design.badges_buttons.setup_custom_roles``). - - :param field: The dataclass field the entry belongs to. - :param name: The name of the new role. - :param data: The role data, expected shape - ``{inherit: str, tooltip: str}`` (``tooltip`` optional). - :raises TypeError | ValueError: If the entry is invalid. - """ - if not isinstance(name, str): - raise TypeError(f"key must be a string: {name!r}") - if not _ROLE_NAME_RE.match(name): - raise ValueError( - f"role name {name!r} is invalid: it must be non-empty and contain " - "no whitespace (docutils could never parse such a role)" - ) - if not isinstance(data, dict): - raise TypeError(f"{name!r} value must be a dictionary") - if "inherit" not in data: - raise ValueError(f"{name!r} value must have an 'inherit' key") - if not isinstance(data["inherit"], str): - raise TypeError(f"'{name}.inherit' value must be a string") - if "tooltip" in data and not isinstance(data["tooltip"], str): - raise TypeError(f"'{name}.tooltip' value must be a string") - # unlike custom directives (whose option set is directive-specific), a role - # entry has a small, fixed key set, so unknown keys are rejected to catch typos - unknown = [key for key in data if key not in CUSTOM_ROLE_KEYS] - if unknown: - raise ValueError( - f"'{name}' has unknown keys {unknown!r} (allowed: {list(CUSTOM_ROLE_KEYS)!r})" - ) - - -def validate_custom_roles( - inst: Any, field: dc.Field[Any], value: Any, suffix: str = "" -) -> None: - """Validate the custom roles mapping, raising on the first invalid entry. - - :param inst: The dataclass instance (or None if not yet created). - :param field: The dataclass field. - :param value: The value to validate. - :param suffix: Suffix to append to the field name in error messages. - :raises TypeError | ValueError: If the value is invalid. - """ - if not isinstance(value, dict): - raise TypeError(f"'{field.name}{suffix}' must be a dictionary (got {value!r})") - for name, data in value.items(): - validate_custom_role(field, name, data) - - @dc.dataclass class SdConfig: """Global configuration for sphinx-design (all values TOML-compatible). @@ -284,15 +219,6 @@ class SdConfig: "doc_type": "dict[str, dict]", }, ) - custom_roles: dict[str, Any] = dc.field( - default_factory=dict, - metadata={ - "validator": validate_custom_roles, - "entry_validator": validate_custom_role, - "help": "Custom roles, inheriting from sphinx-design badge ones", - "doc_type": "dict[str, dict]", - }, - ) fontawesome_source: str = dc.field( default="none", metadata={ diff --git a/sphinx_design/extension.py b/sphinx_design/extension.py index 8debfe41..b78e78de 100644 --- a/sphinx_design/extension.py +++ b/sphinx_design/extension.py @@ -10,7 +10,7 @@ from .accordion import setup_accordion from .article_info import setup_article_info from .aside import setup_aside -from .badges_buttons import setup_badges_and_buttons, setup_custom_roles +from .badges_buttons import setup_badges_and_buttons from .cards import setup_cards from .config import get_sd_config, setup_sd_config from .dropdown import setup_dropdown @@ -62,7 +62,6 @@ def setup_extension(app: Sphinx) -> None: app.connect( "config-inited", partial(setup_custom_directives, directive_map=directive_map) ) - app.connect("config-inited", setup_custom_roles) @contextmanager diff --git a/tests/test_badge_tooltip_option.py b/tests/test_badge_tooltip_option.py new file mode 100644 index 00000000..01117855 --- /dev/null +++ b/tests/test_badge_tooltip_option.py @@ -0,0 +1,329 @@ +"""Tests for the ``tooltip`` role option of the badge roles. + +Every badge role (``bdg``, ``bdg-``, ``-line``, and the ``bdg-link-*`` +and ``bdg-ref-*`` families) declares a ``tooltip`` option, in the docutils +convention for role functions (an ``options`` option spec on the role, and an +``options`` dictionary passed to each call). So a reStructuredText custom role +can preset a tooltip:: + + .. role:: bdg-stable(bdg-success) + :tooltip: A released, supported version + +and an extension that presets a badge role passes ``options={"tooltip": ...}``. + +The tooltip of a badge is, in order of precedence: its ``; tooltip`` suffix, +the ``tooltip`` option, then the role constructor's default. It renders exactly +like a suffix tooltip (an HTML ``title``), and leaves non-HTML output alone. +""" + +from docutils import nodes +from docutils.parsers.rst import roles +import pytest + +from sphinx_design.badges_buttons import ( + BadgeRole, + LinkBadgeRole, + XRefBadgeRole, + _iter_badge_roles, + sd_badge, +) + + +def _build_rst(sphinx_builder, rst, *, buildername="html", assert_pass=True): + """Build a single reStructuredText document.""" + builder = sphinx_builder( + buildername=buildername, conf_kwargs={"extensions": ["sphinx_design"]} + ) + builder.src_path.joinpath("index.rst").write_text(rst, encoding="utf8") + builder.build(assert_pass=assert_pass) + return builder + + +def _badge_refs(doctree): + """The (resolved) badge references in a doctree.""" + return [r for r in doctree.findall(nodes.reference) if "sd-badge" in r["classes"]] + + +# --------------------------------------------------------------------------- +# the option spec +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("role_cls", [BadgeRole, LinkBadgeRole, XRefBadgeRole]) +def test_option_spec(role_cls): + """Each badge role declares the ``tooltip`` option, as its own copy. + + docutils adds a ``class`` option to the spec of every role it registers, so + a spec shared between instances would grow one for every role (this test + also runs after the other tests have registered the badge roles). + """ + role = role_cls() + assert set(role.options) == {"tooltip"} + assert role.options is role.option_spec + assert role.options is not role_cls.OPTION_SPEC + roles.set_implicit_options(role) + assert set(role.options) == {"class", "tooltip"} + assert set(role_cls.OPTION_SPEC) == {"tooltip"} + + +def test_every_badge_role_declares_the_option(): + """Every role of the badge family accepts the option (it shares one mixin).""" + for name, role_cls, color, outline in _iter_badge_roles(): + role = role_cls(color, outline=outline) + assert "tooltip" in role.options, name + + +# --------------------------------------------------------------------------- +# plain badges, through a ``.. role::`` custom role +# --------------------------------------------------------------------------- + +PLAIN = """ +Heading +======= + +.. role:: bdg-stable(bdg-success) + :tooltip: A released & supported version + +Preset :bdg-stable:`v1` here. + +Override :bdg-stable:`v2 ; Long-term support` there. + +Base :bdg-success:`v3` everywhere. +""" + + +def test_plain_badge_option(sphinx_builder): + """The option is the badge's ``title``; a ``; suffix`` overrides it.""" + builder = _build_rst(sphinx_builder, PLAIN) + html = (builder.out_path / "index.html").read_text(encoding="utf8") + classes = "sd-sphinx-override sd-badge sd-bg-success sd-bg-text-success" + # the option becomes an (escaped) title on the inherited badge + assert ( + f'' + "v1" in html + ) + # a per-instance suffix wins over the option + assert f'v2' in html + # the base role is unaffected by the custom role's option + assert f'v3' in html + + badges = list(builder.get_doctree("index").findall(sd_badge)) + assert [b.get("tooltip") for b in badges] == [ + "A released & supported version", + "Long-term support", + None, + ] + # the custom role renders exactly as its base: no extra (role-name) class + assert all(b["classes"] == classes.split() for b in badges) + + +# --------------------------------------------------------------------------- +# link and reference badges +# --------------------------------------------------------------------------- + +LINK = """ +Heading +======= + +.. role:: bdg-docs(bdg-link-info) + :tooltip: Opens the documentation + +Explicit :bdg-docs:`docs `. + +Bare :bdg-docs:`https://example.com/a;b`. + +Override :bdg-docs:`docs ; Other tip`. +""" + + +def test_link_badge_option(sphinx_builder): + """A link badge's option is its ``reftitle``, also on the bare form.""" + builder = _build_rst(sphinx_builder, LINK) + refs = _badge_refs(builder.get_doctree("index")) + assert [r["refuri"] for r in refs] == [ + "https://example.com", + # the bare target is never split at ``;`` - yet the option applies + "https://example.com/a;b", + "https://example.com", + ] + assert [r.get("reftitle") for r in refs] == [ + "Opens the documentation", + "Opens the documentation", + "Other tip", + ] + assert all("sd-bg-info" in r["classes"] for r in refs) + html = (builder.out_path / "index.html").read_text(encoding="utf8") + assert html.count('title="Opens the documentation"') == 2 + assert html.count('title="Other tip"') == 1 + + +REF = """ +Heading +======= + +.. _my-target: + +My Target Section +----------------- + +.. role:: bdg-jump(bdg-ref-primary) + :tooltip: Jump to the target + +Explicit :bdg-jump:`Target `. + +Bare :bdg-jump:`my-target`. + +Override :bdg-jump:`Target ; Other tip`. +""" + + +def test_ref_badge_option(sphinx_builder): + """A ref badge's option survives resolution, replacing the automatic title.""" + builder = _build_rst(sphinx_builder, REF) + html = (builder.out_path / "index.html").read_text(encoding="utf8") + assert html.count('href="#my-target"') == 3 + assert html.count('title="Jump to the target"') == 2 + assert html.count('title="Other tip"') == 1 + + refs = _badge_refs(builder.get_doctree("index", post_transforms=True)) + assert [r.get("reftitle") for r in refs] == [ + "Jump to the target", + "Jump to the target", + "Other tip", + ] + assert all("sd-bg-primary" in r["classes"] for r in refs) + + +# --------------------------------------------------------------------------- +# the option spec survives use of the role +# --------------------------------------------------------------------------- + +AFTER_USE = """ +Heading +======= + +First :bdg-info:`a`, then :bdg-info:`b ; Suffix`. + +.. role:: bdg-later(bdg-info) + :tooltip: Defined after use + +.. role:: bdg-bare(bdg-info) + +Later :bdg-later:`c`, bare :bdg-bare:`d`. +""" + + +def test_option_spec_survives_role_use(sphinx_builder): + """A custom role defined after its base role has been used still takes the option. + + ``SphinxRole`` stores each call's options on the role instance, which would + shadow the option spec docutils' ``role`` directive reads; the badge roles + drop them again after the call. + """ + builder = _build_rst(sphinx_builder, AFTER_USE) + assert not builder.warnings + badges = list(builder.get_doctree("index").findall(sd_badge)) + assert [b.get("tooltip") for b in badges] == [ + None, + "Suffix", + "Defined after use", + None, + ] + + +EMPTY = """ +Heading +======= + +.. role:: bdg-empty(bdg-info) + :tooltip: + +Text. +""" + + +def test_empty_option_is_an_error(sphinx_builder): + """An empty ``:tooltip:`` is refused, as the button ``:tooltip:`` option is.""" + builder = _build_rst(sphinx_builder, EMPTY, assert_pass=False) + assert 'Error in "role" directive' in builder.warnings + assert "tooltip" in builder.warnings + + +# --------------------------------------------------------------------------- +# calling a role with the option, as an extension would +# --------------------------------------------------------------------------- + + +def test_options_dict_and_constructor_default(sphinx_builder): + """The ``options`` dictionary of a call beats the constructor default. + + This is how an extension presets a badge role: wrap it, or register a + ``docutils`` ``CustomRole`` around it, and pass the ``tooltip`` option. + """ + builder = sphinx_builder(conf_kwargs={"extensions": ["sphinx_design"]}) + # register, for this app only (the fixture resets docutils' role registry): + # a role with a constructor default, and a docutils custom role over it + roles.register_local_role( + "bdg-default", BadgeRole("warning", tooltip="Constructor default") + ) + roles.register_local_role( + "bdg-preset", + roles.CustomRole( + "bdg-preset", + roles._roles["bdg-default"], + {"tooltip": "From options"}, + ), + ) + builder.src_path.joinpath("index.rst").write_text( + "Heading\n=======\n\n" + ":bdg-default:`a` :bdg-preset:`b` :bdg-preset:`c ; From suffix`\n", + encoding="utf8", + ) + builder.build() + badges = list(builder.get_doctree("index").findall(sd_badge)) + assert [b.get("tooltip") for b in badges] == [ + "Constructor default", + "From options", + "From suffix", + ] + + +# --------------------------------------------------------------------------- +# non-HTML builders +# --------------------------------------------------------------------------- + +NON_HTML = """ +Heading +======= + +.. _my-target: + +My Target Section +----------------- + +.. role:: bdg-stable(bdg-success) + :tooltip: TIP-PLAIN + +.. role:: bdg-docs(bdg-link-info) + :tooltip: TIP-LINK + +.. role:: bdg-jump(bdg-ref-primary) + :tooltip: TIP-REF + +Plain :bdg-stable:`v1`, link :bdg-docs:`docs `, +ref :bdg-jump:`Target `. +""" + + +@pytest.mark.parametrize( + ("buildername", "suffix"), [("text", ".txt"), ("latex", ".tex"), ("man", ".1")] +) +def test_non_html_builders_unaffected(sphinx_builder, buildername, suffix): + """Non-HTML output shows the badge text only, never the option's tooltip.""" + builder = _build_rst(sphinx_builder, NON_HTML, buildername=buildername) + (outfile,) = builder.out_path.glob(f"*{suffix}") + output = outfile.read_text(encoding="utf8") + assert "v1" in output + assert "docs" in output + assert "Target" in output + assert "TIP-" not in output diff --git a/tests/test_custom_roles.py b/tests/test_custom_roles.py deleted file mode 100644 index a0d757c5..00000000 --- a/tests/test_custom_roles.py +++ /dev/null @@ -1,455 +0,0 @@ -"""Tests for config-defined custom badge roles (``sd_custom_roles``). - -Each ``sd_custom_roles`` entry registers a new role that inherits a built-in -sphinx-design *badge* role (the v1 scope: ``bdg``/``bdg-``/``-line`` and -the ``bdg-link-*``/``bdg-ref-*`` families), optionally baking in a default -``tooltip``. The custom role renders identically to the role it inherits, and: - -* a baked ``tooltip`` becomes the default HTML ``title`` (via the same - mechanisms as the per-instance ``; tooltip`` suffix - a ``sd_badge`` node for - plain badges, ``reftitle`` for link/ref badges), -* a per-instance ``; tooltip`` suffix **overrides** the baked value, -* a custom role *without* a tooltip is byte-identical to the inherited role, -* an unknown ``inherit`` or a clash with an existing role warns and is skipped. - -Registration is reconciled on every ``config-inited`` against docutils' -process-global role registry, so this module also covers: a clash with a -docutils canonical role (``code``/``strong``/...) is warned and skipped; an -in-process rebuild refreshes an edited tooltip; and a role dropped from the -config is unregistered (rather than leaking into a later build or sibling app). - -Written to also run under ``py311-no-myst``: core assertions use -reStructuredText, and the MyST variants are guarded by ``MYST_PARAM``. -""" - -import io - -from docutils import nodes -import pytest -from sphinx.application import Sphinx -from sphinx.util.docutils import docutils_namespace - -from sphinx_design.badges_buttons import sd_badge - -try: - import myst_parser # noqa: F401 - - MYST_INSTALLED = True -except ImportError: - MYST_INSTALLED = False - -# guard MyST variants so the ``py311-no-myst`` environment still passes -MYST_PARAM = pytest.param( - "myst", - marks=pytest.mark.skipif(not MYST_INSTALLED, reason="myst-parser not installed"), -) - -# the custom roles shared by the rendering tests below -CUSTOM_ROLES = { - "bdg-stable": { - "inherit": "bdg-success", - "tooltip": "A released, supported version", - }, - "bdg-plain": {"inherit": "bdg-info"}, - "bdg-docs": {"inherit": "bdg-link-info", "tooltip": "Opens the documentation"}, - "bdg-jump": {"inherit": "bdg-ref-primary", "tooltip": "Jump to the target"}, -} - - -def _build(sphinx_builder, fmt, content, *, custom_roles=None, assert_pass=True): - """Build a single-document project from a ``{"rst": ..., "myst": ...}`` map.""" - custom_roles = CUSTOM_ROLES if custom_roles is None else custom_roles - if fmt == "rst": - builder = sphinx_builder( - conf_kwargs={ - "extensions": ["sphinx_design"], - "sd_custom_roles": custom_roles, - } - ) - builder.src_path.joinpath("index.rst").write_text( - content["rst"], encoding="utf8" - ) - else: - builder = sphinx_builder( - conf_kwargs={ - "extensions": ["myst_parser", "sphinx_design"], - "myst_enable_extensions": ["colon_fence"], - "sd_custom_roles": custom_roles, - } - ) - builder.src_path.joinpath("index.md").write_text( - content["myst"], encoding="utf8" - ) - builder.build(assert_pass=assert_pass) - return builder - - -# --------------------------------------------------------------------------- -# plain badge inheritance: baked tooltip + suffix precedence -# --------------------------------------------------------------------------- - -PLAIN = { - "rst": """ -Heading -======= - -Baked :bdg-stable:`v1` here. - -Override :bdg-stable:`v1 ; Custom override` there. -""", - "myst": """ -# Heading - -Baked {bdg-stable}`v1` here. - -Override {bdg-stable}`v1 ; Custom override` there. -""", -} - - -@pytest.mark.parametrize("fmt", ["rst", MYST_PARAM]) -def test_baked_tooltip_and_suffix_override(fmt, sphinx_builder): - """A baked tooltip is the default ``title``; a ``; suffix`` overrides it.""" - builder = _build(sphinx_builder, fmt, PLAIN) - html = (builder.out_path / "index.html").read_text(encoding="utf8") - # inherits bdg-success's classes, and bakes in the default tooltip - assert ( - 'v1' in html - ) - # the per-instance suffix overrides the baked default - assert ( - 'v1' in html - ) - # the baked default never appears alongside the override - assert 'title="A released, supported version">v1' in html - - doctree = builder.get_doctree("index") - badges = list(doctree.findall(sd_badge)) - assert len(badges) == 2 - assert badges[0]["tooltip"] == "A released, supported version" - assert badges[1]["tooltip"] == "Custom override" - - -# --------------------------------------------------------------------------- -# byte-identity: a no-tooltip custom role == the inherited role -# --------------------------------------------------------------------------- - -IDENTICAL = { - "rst": """ -Heading -======= - -Custom :bdg-plain:`hello` and inherited :bdg-info:`hello`. -""", - "myst": """ -# Heading - -Custom {bdg-plain}`hello` and inherited {bdg-info}`hello`. -""", -} - - -@pytest.mark.parametrize("fmt", ["rst", MYST_PARAM]) -def test_no_tooltip_custom_role_byte_identical(fmt, sphinx_builder): - """A tooltip-less custom role renders byte-identically to its inherited role.""" - builder = _build(sphinx_builder, fmt, IDENTICAL) - html = (builder.out_path / "index.html").read_text(encoding="utf8") - span = 'hello' - # the custom and the inherited badge produce the exact same span (no title) - assert html.count(span) == 2 - - # ... and the doctree nodes are equivalent: neither carries a tooltip - doctree = builder.get_doctree("index") - badges = list(doctree.findall(sd_badge)) - assert len(badges) == 2 - for badge in badges: - assert "tooltip" not in badge - assert badge["classes"] == [ - "sd-sphinx-override", - "sd-badge", - "sd-bg-info", - "sd-bg-text-info", - ] - - -# --------------------------------------------------------------------------- -# link badge inheritance (reference reftitle) -# --------------------------------------------------------------------------- - -LINK = { - "rst": """ -Heading -======= - -Baked :bdg-docs:`docs `. - -Override :bdg-docs:`docs ; Other tip`. -""", - "myst": """ -# Heading - -Baked {bdg-docs}`docs `. - -Override {bdg-docs}`docs ; Other tip`. -""", -} - - -@pytest.mark.parametrize("fmt", ["rst", MYST_PARAM]) -def test_link_badge_custom_role(fmt, sphinx_builder): - """A custom link badge bakes its tooltip into ``reftitle``; a suffix wins.""" - builder = _build(sphinx_builder, fmt, LINK) - doctree = builder.get_doctree("index") - refs = [r for r in doctree.findall(nodes.reference) if "sd-badge" in r["classes"]] - assert len(refs) == 2 - assert refs[0]["refuri"] == "https://example.com" - assert refs[0]["reftitle"] == "Opens the documentation" - assert refs[1]["reftitle"] == "Other tip" - # inherits the bdg-link-info colour classes - assert "sd-bg-info" in refs[0]["classes"] - - -LINK_BARE = { - "rst": """ -Heading -======= - -Bare :bdg-docs:`https://example.com/a;b`. -""", - "myst": """ -# Heading - -Bare {bdg-docs}`https://example.com/a;b`. -""", -} - - -@pytest.mark.parametrize("fmt", ["rst", MYST_PARAM]) -def test_link_badge_baked_tooltip_bare_form(fmt, sphinx_builder): - """A baked tooltip applies even to a bare-form link badge. - - The ``; tooltip`` *suffix* is only recognised after the explicit - ``text `` form for link/ref badges (``;`` is legal in URLs), so a - bare target is never split. A *baked* tooltip is not a suffix, so it still - applies here - reaching a use where the per-instance grammar could not. - """ - builder = _build(sphinx_builder, fmt, LINK_BARE) - doctree = builder.get_doctree("index") - refs = [r for r in doctree.findall(nodes.reference) if "sd-badge" in r["classes"]] - assert len(refs) == 1 - # the bare target is untouched (the whole text is the URL, ``;`` and all) - assert refs[0]["refuri"] == "https://example.com/a;b" - # yet the baked tooltip is applied - assert refs[0]["reftitle"] == "Opens the documentation" - - -# --------------------------------------------------------------------------- -# cross-reference badge inheritance (reftitle grafted post-resolution) -# --------------------------------------------------------------------------- - -REF = { - "rst": """ -Heading -======= - -.. _my-target: - -My Target Section ------------------ - -Baked :bdg-jump:`Target `. - -Override :bdg-jump:`Target ; Other tip`. -""", - "myst": """ -# Heading - -(my-target)= - -## My Target Section - -Baked {bdg-jump}`Target `. - -Override {bdg-jump}`Target ; Other tip`. -""", -} - - -@pytest.mark.parametrize("fmt", ["rst", MYST_PARAM]) -def test_ref_badge_custom_role(fmt, sphinx_builder): - """A custom ref badge bakes its tooltip, applied to the resolved reference.""" - builder = _build(sphinx_builder, fmt, REF) - html = (builder.out_path / "index.html").read_text(encoding="utf8") - assert html.count('href="#my-target"') == 2 - - doctree = builder.get_doctree("index", post_transforms=True) - refs = [r for r in doctree.findall(nodes.reference) if "sd-badge" in r["classes"]] - assert len(refs) == 2 - titles = {r.get("reftitle") for r in refs} - assert titles == {"Jump to the target", "Other tip"} - # inherits the bdg-ref-primary colour classes - assert all("sd-bg-primary" in r["classes"] for r in refs) - - -# --------------------------------------------------------------------------- -# registration edge cases: clash + unknown inherit warn and skip -# --------------------------------------------------------------------------- - -CLASH = { - "rst": """ -Heading -======= - -A :bdg-primary:`p` badge. -""", - "myst": """ -# Heading - -A {bdg-primary}`p` badge. -""", -} - - -@pytest.mark.parametrize("fmt", ["rst", MYST_PARAM]) -def test_clash_with_existing_role_warns_and_skips(fmt, sphinx_builder): - """A custom role named like an existing role warns and leaves it untouched.""" - builder = _build( - sphinx_builder, - fmt, - CLASH, - custom_roles={"bdg-primary": {"inherit": "bdg-danger", "tooltip": "nope"}}, - assert_pass=False, - ) - assert ( - "sd_custom_roles: 'bdg-primary' clashes with an existing role, skipping" - in builder.warnings - ) - html = (builder.out_path / "index.html").read_text(encoding="utf8") - # the built-in bdg-primary is retained (primary classes, no baked tooltip) - assert ( - '' - "p" in html - ) - assert 'title="nope"' not in html - - -CONTENT = { - "rst": "Heading\n=======\n\ncontent\n", - "myst": "# Heading\n\ncontent\n", -} - - -@pytest.mark.parametrize("fmt", ["rst", MYST_PARAM]) -def test_unknown_inherit_warns_and_skips(fmt, sphinx_builder): - """A custom role inheriting an unknown badge role warns and is not registered.""" - builder = _build( - sphinx_builder, - fmt, - CONTENT, - custom_roles={"bdg-foo": {"inherit": "not-a-badge"}}, - assert_pass=False, - ) - assert ( - "sd_custom_roles: 'bdg-foo.inherit' is an unknown badge role: not-a-badge" - in builder.warnings - ) - - -CANONICAL = { - "rst": """ -Heading -======= - -Bold **b**, role :strong:`s`, and code :code:`x = 1`. -""", - "myst": """ -# Heading - -Bold **b**, role {strong}`s`, and code {code}`x = 1`. -""", -} - - -@pytest.mark.parametrize("fmt", ["rst", MYST_PARAM]) -def test_canonical_role_clash_warns_and_skips(fmt, sphinx_builder): - """A custom role named after a docutils canonical role is skipped, not a hijack. - - ``strong``/``code``/... live in docutils' canonical registry (not the local - one Sphinx's ``add_role`` checks), so they must be recognised as clashes - - otherwise a custom role would silently override ``**bold**`` / ``:code:``. - """ - builder = _build( - sphinx_builder, - fmt, - CANONICAL, - custom_roles={ - "strong": {"inherit": "bdg-danger", "tooltip": "HIJACK"}, - "code": {"inherit": "bdg-info", "tooltip": "HIJACK"}, - }, - assert_pass=False, - ) - assert "'strong' clashes with an existing role, skipping" in builder.warnings - assert "'code' clashes with an existing role, skipping" in builder.warnings - html = (builder.out_path / "index.html").read_text(encoding="utf8") - # neither canonical role was overridden: no badge, no baked tooltip - assert "HIJACK" not in html - assert "sd-badge" not in html - # ``**b**`` and ``:strong:`s``` still render as real ```` - assert html.count("") == 2 - - -def _raw_build(tmp_path, sub, custom_roles): - """Build a tiny rST project with a raw ``Sphinx`` app (no fixture isolation). - - Returns the rendered ``index.html``. Used to exercise the process-global - docutils role registry that the fixtures otherwise reset between apps. - """ - src = tmp_path / sub - src.mkdir() - (src / "conf.py").write_text( - "extensions = ['sphinx_design']\n" + f"sd_custom_roles = {custom_roles!r}\n", - encoding="utf8", - ) - (src / "index.rst").write_text("H\n=\n\nUse :bdg-stable:`v1`.\n", encoding="utf8") - app = Sphinx( - str(src), - str(src), - str(src / "_out"), - str(src / "_dt"), - "html", - warningiserror=False, - status=None, - warning=io.StringIO(), - ) - app.build() - return (src / "_out" / "index.html").read_text(encoding="utf8") - - -def test_reconcile_refresh_and_unregister_in_process(tmp_path): - """In one process (shared role registry): edits refresh, drops unregister. - - The pytest fixtures reset docutils' global role state between apps, which - would mask the reconciliation; building several raw apps inside a single - ``docutils_namespace`` exercises the real shared registry (and restores it - on exit, so other tests are unaffected). - """ - stable = {"inherit": "bdg-success"} - with docutils_namespace(): - html1 = _raw_build( - tmp_path, "a", {"bdg-stable": {**stable, "tooltip": "FIRST"}} - ) - assert 'title="FIRST"' in html1 - - # an edited tooltip is picked up on the in-process rebuild (no stale value) - html2 = _raw_build( - tmp_path, "b", {"bdg-stable": {**stable, "tooltip": "SECOND"}} - ) - assert 'title="SECOND"' in html2 - assert 'title="FIRST"' not in html2 - - # dropping the role unregisters it: it no longer resolves as a badge - html3 = _raw_build(tmp_path, "c", {}) - assert "sd-badge" not in html3 - assert "problematic" in html3 # the now-unknown role errors instead diff --git a/tests/test_misc.py b/tests/test_misc.py index 25c2ec66..1e0004b7 100644 --- a/tests/test_misc.py +++ b/tests/test_misc.py @@ -506,7 +506,6 @@ def test_button_i18n_translated(sphinx_builder): INVALID_CONFIG_VALUES = { "custom_directives": (["not", "a", "dict"], "must be a dictionary"), - "custom_roles": (["not", "a", "dict"], "must be a dictionary"), "fontawesome_source": ("invalid", "must be one of"), "fontawesome_cdn_url": (123, "must be of type"), "fontawesome_version": ("7", "must be one of"), @@ -580,42 +579,6 @@ def test_config_custom_directives_unknown_inherit(sphinx_builder): assert "'foo.inherit' is an unknown directive key: unknown" in builder.warnings -def test_config_custom_roles_invalid_entry(sphinx_builder): - """An invalid ``sd_custom_roles`` entry should emit a ``design.config`` - warning and be discarded, without affecting valid entries. - """ - builder = sphinx_builder( - conf_kwargs={ - "extensions": ["sphinx_design"], - "sd_custom_roles": { - "bdg-stable": {"inherit": "bdg-success", "tooltip": "Stable"}, - "bdg-bad": {"tooltip": "no inherit"}, - "bdg-typo": {"inherit": "bdg-info", "tootlip": "misspelt key"}, - "bad name": {"inherit": "bdg-info"}, - }, - } - ) - _write_index_rst(builder) - builder.build(assert_pass=False) - assert "'bdg-bad' value must have an 'inherit' key" in builder.warnings - assert "'bdg-typo' has unknown keys" in builder.warnings - assert "role name 'bad name' is invalid" in builder.warnings - assert list(get_sd_config(builder.app.env).custom_roles) == ["bdg-stable"] - - -def test_config_custom_roles_unknown_inherit(sphinx_builder): - """An unknown ``inherit`` badge role should emit a ``design.config`` warning.""" - builder = sphinx_builder( - conf_kwargs={ - "extensions": ["sphinx_design"], - "sd_custom_roles": {"bdg-foo": {"inherit": "not-a-badge"}}, - } - ) - _write_index_rst(builder) - builder.build(assert_pass=False) - assert "'bdg-foo.inherit' is an unknown badge role: not-a-badge" in builder.warnings - - def test_config_warnings_suppressible(sphinx_builder): """Config warnings are emitted with the ``design.config`` type/subtype, so they can be suppressed via ``suppress_warnings``. @@ -646,14 +609,6 @@ def test_config_strict_validation(): SdConfig(custom_directives="not-a-dict") with pytest.raises(ValueError, match="must have an 'inherit' key"): SdConfig(custom_directives={"foo": {}}) - with pytest.raises(TypeError, match="'custom_roles' must be a dictionary"): - SdConfig(custom_roles="not-a-dict") - with pytest.raises(ValueError, match="must have an 'inherit' key"): - SdConfig(custom_roles={"bdg-foo": {}}) - with pytest.raises(ValueError, match="has unknown keys"): - SdConfig(custom_roles={"bdg-foo": {"inherit": "bdg", "bad": 1}}) - with pytest.raises(ValueError, match="role name 'bad name' is invalid"): - SdConfig(custom_roles={"bad name": {"inherit": "bdg"}}) def test_config_toml_round_trip(): @@ -674,10 +629,6 @@ def test_config_toml_round_trip(): [custom_directives.dropdown-syntax.options] color = "primary" icon = "code" - - [custom_roles.bdg-stable] - inherit = "bdg-success" - tooltip = "A released, supported version" """ data = tomllib.loads(toml_str) assert set(data) == {f.name for f in dc.fields(SdConfig)}, ( @@ -697,12 +648,6 @@ def test_config_toml_round_trip(): "options": {"color": "primary", "icon": "code"}, } } - assert config.custom_roles == { - "bdg-stable": { - "inherit": "bdg-success", - "tooltip": "A released, supported version", - } - } ACCORDION_NESTED = { From 91c10a01eaf761fe49ee4edd3502837a5dc9a077 Mon Sep 17 00:00:00 2001 From: Chris Sewell Date: Tue, 10 Nov 2026 13:45:25 +0100 Subject: [PATCH 2/3] =?UTF-8?q?=F0=9F=93=9A=20Badge=20tooltip=20option=20d?= =?UTF-8?q?ocs:=20rst=5Fprolog=20for=20project-wide=20roles,=20accurate=20?= =?UTF-8?q?pointers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The role directive defines a role for the document it is in, so say so and show rst_prolog for using one in every reStructuredText document. Point to sphinx-ub-directives for what it does today (role presets are planned there), frame the get_started tip as what sd_custom_directives does not do, and move the tooltip accessibility warning above the role-option subsection. --- docs/badges_buttons.md | 50 ++++++++++++++++++++++++++++-------------- docs/get_started.md | 16 +++++++------- 2 files changed, 42 insertions(+), 24 deletions(-) diff --git a/docs/badges_buttons.md b/docs/badges_buttons.md index ae75cdc3..9a7bb223 100644 --- a/docs/badges_buttons.md +++ b/docs/badges_buttons.md @@ -90,15 +90,22 @@ tooltip to a link/ref badge, use the explicit form: `` {bdg-link-primary}`docs ; Opens the docs` ``. A `bdg-ref` tooltip overrides the reference's automatic title. +```{warning} +`title` tooltips are **not** accessible to keyboard or touch users, and are +not surfaced by all screen readers. Do not put essential information in a +tooltip alone -- keep it in the visible badge text (or nearby prose) as well. +``` + (sd-badge-tooltip-option)= #### The `tooltip` role option -When the same badge recurs throughout your documentation, such as a status label -whose colour and tooltip never change, it can be defined once instead. +When the same badge recurs, such as a status label whose colour and tooltip never change, +its tooltip can be given once rather than in every use. Every badge role accepts a `tooltip` role option, which is the badge's tooltip when its text has no `; tooltip` suffix (a suffix still overrides it). -In reStructuredText, set it with the `role` directive, which defines a new role based on a badge role: +In reStructuredText, set it with the `role` directive, which defines a new role based on a badge role +for the document it appears in: ```rst .. role:: bdg-stable(bdg-success) @@ -114,29 +121,40 @@ In reStructuredText, set it with the `role` directive, which defines a new role :bdg-stable:`v2.1` :bdg-stable:`v2.2 ; Long-term support release` ``` +To use such a role in every reStructuredText document, +put the `role` directive in [`rst_prolog`](https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-rst_prolog) +in your `conf.py`, which is read at the start of each reStructuredText document +(Markdown documents parsed by MyST do not read it): + +```python +rst_prolog = """ +.. role:: bdg-stable(bdg-success) + :tooltip: A released, supported version +""" +``` + +Defining the role in only one document is not enough for the others: +a document that uses a role defined elsewhere can fail with an "Unknown interpreted text role" error, +for example in an incremental or parallel build. + The option also applies to the bare `` form of the link and reference badges, where the `; tooltip` suffix is not recognised. For extension authors: the badge roles follow the docutils convention for role functions. -Their option specification is the role's `options` attribute (`{"tooltip": ...}`), +Their option specification is the role's `options` attribute (`{"tooltip": ...}`; +docutils also adds `class` when the role is registered, which badges accept and ignore), and the option is read from the `options` dictionary passed to each call, so an extension that presets a badge role passes `options={"tooltip": "..."}`. :::{tip} -To define such presets in your project configuration rather than in each document, -we recommend the [sphinx-ub-directives](https://sphinx-ub-directives.readthedocs.io) package, -from the [sphinx-needs](https://github.com/useblocks/sphinx-needs) project. -Its directive presets already accept sphinx-design directives as a base -and also work in [ubCode](https://ubcode.useblocks.com/); -role presets are planned there. +Role presets in the project configuration are planned for the +[sphinx-ub-directives](https://sphinx-ub-directives.readthedocs.io) package, +from the [sphinx-needs](https://github.com/useblocks/sphinx-needs) project, +whose directive presets already accept sphinx-design directives as a base +and also work in [ubCode](https://ubcode.useblocks.com/). +Until then, use `rst_prolog` as above. ::: -```{warning} -`title` tooltips are **not** accessible to keyboard or touch users, and are -not surfaced by all screen readers. Do not put essential information in a -tooltip alone -- keep it in the visible badge text (or nearby prose) as well. -``` - See [Bootstrap badges](https://getbootstrap.com/docs/5.0/components/badge/) for more information, and related [Material Design chips](https://material.io/components/chip). (buttons)= diff --git a/docs/get_started.md b/docs/get_started.md index f59d97d2..5af4ebc7 100644 --- a/docs/get_started.md +++ b/docs/get_started.md @@ -89,14 +89,14 @@ The key is the new directive name to add, and the value is a dictionary with the - `options`: A dictionary of default options for the directive (optional) :::{tip} -For project-defined directive presets, we recommend the -[sphinx-ub-directives](https://sphinx-ub-directives.readthedocs.io) package, -from the [sphinx-needs](https://github.com/useblocks/sphinx-needs) project. -Its directive presets already accept sphinx-design directives (such as `dropdown`) as a base, -can be configured in `conf.py` or `ubproject.toml`, -and also work in [ubCode](https://ubcode.useblocks.com/). -Role presets are planned there; until then, a badge role can be preset with -its {ref}`tooltip role option `. +For presets beyond default option values, +see the [sphinx-ub-directives](https://sphinx-ub-directives.readthedocs.io) package, +from the [sphinx-needs](https://github.com/useblocks/sphinx-needs) project, +whose directive presets accept sphinx-design directives (such as `dropdown`) as a base. +It adds appended and forced option values, need-type bases (with sphinx-needs), and template directives, +and its presets can also be configured in `ubproject.toml`, +which [ubCode](https://ubcode.useblocks.com/) reads. +To preset a badge's tooltip, see the badge roles' {ref}`tooltip role option `. ::: ## Supported browsers From 779e442735c6615d15b7d982029a5369006b10b5 Mon Sep 17 00:00:00 2001 From: Chris Sewell Date: Tue, 10 Nov 2026 14:13:30 +0100 Subject: [PATCH 3/3] =?UTF-8?q?=F0=9F=A7=AA=20Badge=20tooltip=20option=20t?= =?UTF-8?q?ests:=20class=20on=20a=20later=20custom=20role,=20restore=20on?= =?UTF-8?q?=20error?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A custom role defined after its base badge role was used now also passes `:class:`, which pins that the restored option spec is the one docutils registered (with its `class` entry): restoring a fresh copy of the class-level spec would refuse `:class:` there. Also test that the spec is restored when the base role raises. --- tests/test_badge_tooltip_option.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/tests/test_badge_tooltip_option.py b/tests/test_badge_tooltip_option.py index 01117855..7450e1c8 100644 --- a/tests/test_badge_tooltip_option.py +++ b/tests/test_badge_tooltip_option.py @@ -16,6 +16,8 @@ like a suffix tooltip (an HTML ``title``), and leaves non-HTML output alone. """ +from unittest.mock import Mock + from docutils import nodes from docutils.parsers.rst import roles import pytest @@ -206,6 +208,7 @@ def test_ref_badge_option(sphinx_builder): .. role:: bdg-later(bdg-info) :tooltip: Defined after use + :class: foo .. role:: bdg-bare(bdg-info) @@ -218,7 +221,8 @@ def test_option_spec_survives_role_use(sphinx_builder): ``SphinxRole`` stores each call's options on the role instance, which would shadow the option spec docutils' ``role`` directive reads; the badge roles - drop them again after the call. + restore the spec after the call. The restored spec is the one docutils + registered, so it still includes the ``class`` option docutils added then. """ builder = _build_rst(sphinx_builder, AFTER_USE) assert not builder.warnings @@ -231,6 +235,22 @@ def test_option_spec_survives_role_use(sphinx_builder): ] +def test_option_spec_restored_when_the_role_raises(monkeypatch): + """The option spec is restored even when the base role raises.""" + role = BadgeRole("info") + roles.set_implicit_options(role) + spec = role.options + + def _raise(self): + raise RuntimeError("boom") + + monkeypatch.setattr(BadgeRole, "run", _raise) + with pytest.raises(RuntimeError, match="boom"): + role("bdg-info", ":bdg-info:`a`", "a", 1, Mock(), {"tooltip": "T"}) + assert role.options is spec + assert set(role.options) == {"class", "tooltip"} + + EMPTY = """ Heading =======