diff --git a/docs/badges_buttons.md b/docs/badges_buttons.md index ca0064c..3034bf6 100644 --- a/docs/badges_buttons.md +++ b/docs/badges_buttons.md @@ -308,6 +308,35 @@ Use the `click-parent` option to make the button's parent container also clickab ::: +Use the `new-tab` option to open the button's link in a new browser tab. +Since this changes what the reader expects a link to do, +say so in the button text: + +```{button-link} https://example.com +:color: primary +:new-tab: + +example.com (opens in a new tab) +``` + +````{tab-set-code} +```markdown +:::{button-link} https://example.com +:color: primary +:new-tab: + +example.com (opens in a new tab) +::: +``` +```rst +.. button-link:: https://example.com + :color: primary + :new-tab: + + example.com (opens in a new tab) +``` +```` + ### `button-link` and `button-ref` options ref-type (`button-ref` only) @@ -329,6 +358,13 @@ expand click-parent : Make parent container also clickable +new-tab +: Open the link in a new browser tab (`target="_blank"`, `rel="noreferrer noopener"`). + Works for both `button-link` and `button-ref`. + Sphinx renders the `rel` attribute only from version 7.4; + browsers already treat `target="_blank"` links as `noopener`. + It affects only HTML-based output (HTML, EPUB); other formats ignore it. + tooltip : Add tooltip on hover diff --git a/docs/cards.md b/docs/cards.md index 0c21a97..f225255 100644 --- a/docs/cards.md +++ b/docs/cards.md @@ -174,6 +174,14 @@ Try hovering over then clicking on the cards below: The entire card can be clicked to navigate to `https://example.com`. ::: +:::{card} Clickable Card (external, new tab) +:link: https://example.com +:link-alt: example.com (opens in a new tab) +:link-new-tab: + +The entire card can be clicked to open `https://example.com` in a new tab. +::: + :::{card} Clickable Card (internal) :link: cards-clickable :link-type: ref @@ -322,6 +330,17 @@ link-type link-alt : Alternative text for the link (that will be used by screen-readers). +link-new-tab +: Flag. When set, the card link opens in a new browser tab + (`target="_blank"`, `rel="noreferrer noopener"`). + Works with all `link-type` values; has no effect without `link`. + Sphinx renders the `rel` attribute only from version 7.4; + browsers already treat `target="_blank"` links as `noopener`. + It affects only HTML-based output (HTML, EPUB); other formats ignore it. + Tell readers the link opens a new tab, for example in `link-alt`. + To open every external link in a new tab, site-wide, + see the [sphinx-new-tab-link](https://pypi.org/project/sphinx-new-tab-link/) extension. + shadow : The size of the shadow below the card: `none`, `sm` (default), `md`, `lg`. diff --git a/docs/snippets/myst/card-link.txt b/docs/snippets/myst/card-link.txt index fdd6ff6..3b7dbdd 100644 --- a/docs/snippets/myst/card-link.txt +++ b/docs/snippets/myst/card-link.txt @@ -17,6 +17,14 @@ The entire card can be clicked to navigate to . The entire card can be clicked to navigate to . ::: +:::{card} Clickable Card (external, new tab) +:link: https://example.com +:link-alt: example.com (opens in a new tab) +:link-new-tab: + +The entire card can be clicked to open in a new tab. +::: + :::{card} Clickable Card (internal) :link: cards-clickable :link-type: ref diff --git a/docs/snippets/rst/card-link.txt b/docs/snippets/rst/card-link.txt index e721db0..f7e032e 100644 --- a/docs/snippets/rst/card-link.txt +++ b/docs/snippets/rst/card-link.txt @@ -16,6 +16,13 @@ Using the ``link`` and ``link-type`` options, you can turn an entire card into a The entire card can be clicked to navigate to https://example.com. +.. card:: Clickable Card (external, new tab) + :link: https://example.com + :link-alt: example.com (opens in a new tab) + :link-new-tab: + + The entire card can be clicked to open https://example.com in a new tab. + .. card:: Clickable Card (internal) :link: cards-clickable :link-type: ref diff --git a/sphinx_design/badges_buttons.py b/sphinx_design/badges_buttons.py index d24ad56..fc481db 100644 --- a/sphinx_design/badges_buttons.py +++ b/sphinx_design/badges_buttons.py @@ -554,6 +554,8 @@ class _ButtonDirective(SdDirective): "expand": directives.flag, # make parent also clickable "click-parent": directives.flag, + # open the link in a new browser tab + "new-tab": directives.flag, "tooltip": directives.unchanged_required, "shadow": directives.flag, # ref button only @@ -634,7 +636,6 @@ def run_with_defaults(self) -> list[nodes.Node]: if "class" in self.options: classes.extend(self.options["class"]) node = self.create_ref_node(rawtext, target, bool(self.content), classes) - # TODO open in new tab self.set_source_info(node) if "tooltip" in self.options: # ``reftitle`` is rendered as the HTML ``title`` attribute, whose @@ -661,6 +662,11 @@ def run_with_defaults(self) -> list[nodes.Node]: container = nodes.paragraph( classes=self.options.get("align", []), translatable=False ) + if "new-tab" in self.options: + # the reference itself may be a ``pending_xref``, replaced on + # resolution, so mark the container: ``target``/``rel`` are set on + # the resolved reference by the ``doctree-resolved`` handler + container["sd_new_tab"] = True self.set_source_info(container) container += node diff --git a/sphinx_design/cards.py b/sphinx_design/cards.py index 50cbc79..a5f4b7e 100644 --- a/sphinx_design/cards.py +++ b/sphinx_design/cards.py @@ -85,6 +85,7 @@ class CardDirective(SdDirective): "link": directives.unchanged_required, "link-type": make_choice(["url", "any", "ref", "doc"]), "link-alt": directives.unchanged, + "link-new-tab": directives.flag, "shadow": make_choice(["none", "sm", "md", "lg"]), # inline one-liner slots (compose with the body content); # mutually exclusive with the card-header/card-footer sub-directives @@ -103,7 +104,7 @@ def run_with_defaults(self) -> list[nodes.Node]: return [self.create_card(self, self.arguments, self.options)] @classmethod - def create_card( # noqa: PLR0915 + def create_card( cls, inst: SphinxDirective, arguments: list | None, options: dict ) -> nodes.Node: """Run the directive.""" @@ -196,41 +197,56 @@ def create_card( # noqa: PLR0915 container.append(image_bottom) if "link" in options: - link_container = PassthroughTextElement() - _classes = ["sd-stretched-link", "sd-hide-link-text"] - link_type = options.get("link-type", "url") - # the raw (un-normalised) target, kept for user-visible fallback text - link_raw = options["link"] - link_target = cls.get_link_target(link_raw, link_type) - _rawtext = options.get("link-alt") or link_raw - if link_type == "url": - link = nodes.reference( - _rawtext, - "", - nodes.inline(_rawtext, _rawtext), - refuri=link_target, - classes=_classes, - ) - else: - ref_options = { - # TODO the presence of classes raises an error if the link cannot be found - "classes": _classes, - "reftarget": link_target, - "refdoc": inst.env.docname, - "refdomain": "" if link_type == "any" else "std", - "reftype": link_type, - "refexplicit": "link-alt" in options, - "refwarn": True, - } - link = addnodes.pending_xref( - _rawtext, nodes.inline(_rawtext, _rawtext), **ref_options - ) - inst.set_source_info(link) - link_container += link - container.append(link_container) + container.append(cls._create_link(inst, options)) return card + @classmethod + def _create_link( + cls, inst: SphinxDirective, options: dict + ) -> PassthroughTextElement: + """Create the stretched link that makes the whole card clickable. + + With ``link-new-tab``, the container is marked ``sd_new_tab``; + the ``doctree-resolved`` handler then sets ``target``/``rel`` + on the reference, once any cross-reference has been resolved. + """ + link_container = PassthroughTextElement() + _classes = ["sd-stretched-link", "sd-hide-link-text"] + link_type = options.get("link-type", "url") + # the raw (un-normalised) target, kept for user-visible fallback text + link_raw = options["link"] + link_target = cls.get_link_target(link_raw, link_type) + _rawtext = options.get("link-alt") or link_raw + link: nodes.Element + if link_type == "url": + link = nodes.reference( + _rawtext, + "", + nodes.inline(_rawtext, _rawtext), + refuri=link_target, + classes=_classes, + ) + else: + ref_options = { + # TODO the presence of classes raises an error if the link cannot be found + "classes": _classes, + "reftarget": link_target, + "refdoc": inst.env.docname, + "refdomain": "" if link_type == "any" else "std", + "reftype": link_type, + "refexplicit": "link-alt" in options, + "refwarn": True, + } + link = addnodes.pending_xref( + _rawtext, nodes.inline(_rawtext, _rawtext), **ref_options + ) + inst.set_source_info(link) + if "link-new-tab" in options: + link_container["sd_new_tab"] = True + link_container += link + return link_container + @staticmethod def get_link_target(target: str, link_type: str) -> str: """Normalise a ``link`` option value into a reference target. diff --git a/sphinx_design/extension.py b/sphinx_design/extension.py index 8debfe4..65c0080 100644 --- a/sphinx_design/extension.py +++ b/sphinx_design/extension.py @@ -62,6 +62,7 @@ def setup_extension(app: Sphinx) -> None: app.connect( "config-inited", partial(setup_custom_directives, directive_map=directive_map) ) + app.connect("doctree-resolved", _resolve_new_tab_refs) app.connect("config-inited", setup_custom_roles) @@ -80,6 +81,32 @@ def _add_directive(name, directive, **kwargs): app.add_directive = add_directive # type: ignore[method-assign] +def _has_new_tab_marker(node: nodes.Node) -> bool: + """Return whether ``node`` is an element marked to open its links in a new tab.""" + return isinstance(node, nodes.Element) and bool(node.get("sd_new_tab")) + + +def _resolve_new_tab_refs(app: Sphinx, doctree: nodes.document, docname: str) -> None: + """Set ``target`` and ``rel`` on the link references that request a new tab. + + A component that opens in a new tab (a card with ``link-new-tab``, + a button with ``new-tab``) marks the element containing its reference + with ``sd_new_tab``. + Cross-references are resolved to ``nodes.reference`` during the write + phase, before ``doctree-resolved`` fires, so we can safely walk the tree + here for both URL and internal links. + A reference that already has a ``target`` (for example a link nested in + a button's text, given its own attributes) is left as authored. + Writers other than HTML ignore both attributes. + """ + for container in doctree.findall(_has_new_tab_marker): + for ref in container.findall(nodes.reference): + if "target" in ref: + continue + ref["target"] = "_blank" + ref["rel"] = "noreferrer noopener" + + def add_static_assets(app: Sphinx) -> None: """Register the extension's static assets (HTML-format builders only).""" if app.builder.format != "html": diff --git a/sphinx_design/grids.py b/sphinx_design/grids.py index 5bd9e72..bc6f11b 100644 --- a/sphinx_design/grids.py +++ b/sphinx_design/grids.py @@ -228,6 +228,7 @@ class GridItemCardDirective(SdDirective): "link": directives.unchanged_required, "link-type": make_choice(["url", "any", "ref", "doc"]), "link-alt": directives.unchanged, + "link-new-tab": directives.flag, "shadow": make_choice(["none", "sm", "md", "lg"]), # inline one-liner slots (see CardDirective) "header": directives.unchanged, @@ -274,6 +275,7 @@ def run_with_defaults(self) -> list[nodes.Node]: "link", "link-type", "link-alt", + "link-new-tab", "shadow", "header", "footer", diff --git a/sphinx_design/testing.py b/sphinx_design/testing.py index 47d33b3..791c65f 100644 --- a/sphinx_design/testing.py +++ b/sphinx_design/testing.py @@ -57,6 +57,7 @@ "opened", "refexplicit", "refwarn", + "sd_new_tab", "selected", "translatable", "translated", diff --git a/tests/test_buttons.py b/tests/test_buttons.py index 2e68567..4b88398 100644 --- a/tests/test_buttons.py +++ b/tests/test_buttons.py @@ -12,6 +12,8 @@ warning and still build (no traceback). * #156 - a button whose RST content is a line block renders its lines as separate lines, rather than keeping the literal ``|`` markers. +* #170 - the ``new-tab`` flag opens the link of either button in a new tab, + in HTML only. """ import re @@ -19,7 +21,11 @@ from babel.messages.catalog import Catalog from babel.messages.mofile import write_mo from docutils import nodes +from docutils.frontend import get_default_settings +from docutils.parsers.rst import Parser +from docutils.utils import new_document import pytest +import sphinx from sphinx_design.badges_buttons import ( _BUTTON_REF_MARKER_PREFIX, @@ -27,6 +33,7 @@ ButtonRefDirective, _line_block_lines, ) +from sphinx_design.extension import _resolve_new_tab_refs from sphinx_design.icons import sd_icon try: @@ -676,6 +683,234 @@ def test_button_link_line_block_translated(sphinx_builder): assert _button_texts(html) == ["hallo
neue Zeile"] +# --------------------------------------------------------------------------- +# new-tab tests (#170) +# --------------------------------------------------------------------------- + +# Sphinx's HTML writer renders a reference's ``rel`` attribute only from 7.4; +# ``target`` is rendered on every supported version. +RENDERS_REL = sphinx.version_info >= (7, 4) + +_BUTTON_TAG_RE = re.compile(r']*class="[^"]*\bsd-btn\b[^"]*"[^>]*>') + + +def _button_tags(html: str) -> list[str]: + """Return the opening ```` tag of every button.""" + return _BUTTON_TAG_RE.findall(html) + + +def _opens_in_new_tab(tag: str) -> bool: + """Return whether a button's opening tag opens its link in a new tab. + + The ``rel`` value is checked exactly where Sphinx renders it, + and checked absent where it does not. + """ + rel_ok = 'rel="noreferrer noopener"' in tag if RENDERS_REL else "rel=" not in tag + return 'target="_blank"' in tag and rel_ok + + +NEW_TAB = { + "rst": """ +Heading +======= + +.. _target-section: + +Target Section +-------------- + +.. button-link:: https://example.com + :new-tab: + + Link new tab + +.. button-ref:: target-section + :ref-type: ref + :new-tab: + + Ref *new* tab + +.. button-ref:: target-section + :new-tab: + :expand: + :click-parent: + +.. button-link:: https://example.org + + Link same tab + +.. button-ref:: target-section + :ref-type: ref + + Ref same tab + +A plain https://example.net link. +""", + "myst": """ +# Heading + +(target-section)= + +## Target Section + +```{button-link} https://example.com +:new-tab: + +Link new tab +``` + +```{button-ref} target-section +:ref-type: ref +:new-tab: + +Ref *new* tab +``` + +```{button-ref} target-section +:new-tab: +:expand: +:click-parent: +``` + +```{button-link} https://example.org +Link same tab +``` + +```{button-ref} target-section +:ref-type: ref + +Ref same tab +``` + +A plain link. +""", +} + + +@pytest.mark.parametrize("fmt", ["rst", MYST_PARAM]) +def test_button_new_tab(fmt, sphinx_builder): + """``new-tab`` opens a ``button-link`` or ``button-ref`` in a new tab. + + The ``button-ref`` is a ``pending_xref`` that resolution replaces + (and whose rich content the stash/graft post-transforms restore), + so the marker sits on the button's container, and the attributes are + set on the resolved reference; ``expand`` wraps the reference in one + more element, which must not hide it. + Buttons without the flag, and other links, are left alone. + """ + builder = _build(sphinx_builder, fmt, NEW_TAB["rst"], NEW_TAB["myst"]) + html = (builder.out_path / "index.html").read_text(encoding="utf8") + tags = _button_tags(html) + assert len(tags) == 5, tags + hrefs = [re.search(r'href="([^"]*)"', tag).group(1) for tag in tags] + assert hrefs == [ + "https://example.com", + "#target-section", + "#target-section", + "https://example.org", + "#target-section", + ] + assert [_opens_in_new_tab(tag) for tag in tags] == [True, True, True, False, False] + for tag in tags[3:]: + assert "target=" not in tag, tag + assert "rel=" not in tag, tag + # the rich content of the new-tab ``button-ref`` survives resolution + assert "new" in html + # the plain link outside any button is untouched + [plain] = re.findall(r']*href="https://example.net"[^>]*>', html) + assert "target=" not in plain, plain + # the marker itself never reaches the output + assert "sd_new_tab" not in html + + +NEW_TAB_NON_HTML_RST = """ +Heading +======= + +.. _target-section: + +Target Section +-------------- + +.. button-link:: https://example.com + :new-tab: + + Link new tab + +.. button-ref:: target-section + :ref-type: ref + :new-tab: + + Ref new tab + +.. card:: Card new tab + :link: https://example.org + :link-new-tab: + + Card body +""" + + +@pytest.mark.parametrize( + ("buildername", "pattern"), [("latex", "*.tex"), ("text", "index.txt")] +) +def test_new_tab_non_html(buildername, pattern, sphinx_builder): + """``new-tab`` / ``link-new-tab`` build without warnings for other formats, + which do not render ``target`` or ``rel``. + """ + builder = _build_rst(sphinx_builder, NEW_TAB_NON_HTML_RST, buildername) + [output] = builder.out_path.glob(pattern) + text = output.read_text(encoding="utf8") + assert "Link new tab" in text + assert "_blank" not in text + assert "noreferrer" not in text + if buildername == "latex": + assert r"\sphinxhref{https://example.com}{Link new tab}" in text + + +def _new_tab_doctree() -> nodes.document: + """Return a document with one reference in each kind of container.""" + document = new_document("test", get_default_settings(Parser)) + for marked in (True, False): + paragraph = nodes.paragraph() + if marked: + paragraph["sd_new_tab"] = True + paragraph += nodes.inline("", "", nodes.reference("", "x", refuri="a")) + document += paragraph + return document + + +def test_resolve_new_tab_refs_any_marked_element(): + """The handler sets ``target``/``rel`` inside any marked element, + including on nested references, and nowhere else. + """ + document = _new_tab_doctree() + _resolve_new_tab_refs(None, document, "test") + marked, unmarked = document.findall(nodes.reference) + assert marked["target"] == "_blank" + assert marked["rel"] == "noreferrer noopener" + assert "target" not in unmarked + assert "rel" not in unmarked + + +def test_resolve_new_tab_refs_keeps_authored_target(): + """A reference inside a marked element that already has a ``target`` + (e.g. a link with its own attributes nested in a button's text) + is left as authored, while its sibling references are still stamped. + """ + document = new_document("test", get_default_settings(Parser)) + paragraph = nodes.paragraph(sd_new_tab=True) + paragraph += nodes.reference("", "x", refuri="a") + paragraph += nodes.reference("", "y", refuri="b", target="_self", rel="me") + document += paragraph + _resolve_new_tab_refs(None, document, "test") + stamped, authored = document.findall(nodes.reference) + assert stamped["target"] == "_blank" + assert stamped["rel"] == "noreferrer noopener" + assert authored["target"] == "_self" + assert authored["rel"] == "me" + + # Bodies that look like a line block at their outermost indent, but are not # only line-block lines. Each must be parsed once, as inline text, exactly as # before #156 was fixed: ``(body, expected button text, expected warnings)``. diff --git a/tests/test_card_link.py b/tests/test_card_link.py index b4cce89..805348f 100644 --- a/tests/test_card_link.py +++ b/tests/test_card_link.py @@ -16,6 +16,7 @@ from docutils.parsers.rst import directives import pytest +import sphinx from sphinx_design.cards import CardDirective @@ -273,3 +274,232 @@ def test_card_ref_unresolved_warns(sphinx_builder): # build completed and the content survives, just without a resolved link assert "Card body" in html assert _stretched_link_hrefs(html) == [] + + +# --------------------------------------------------------------------------- +# link-new-tab tests +# --------------------------------------------------------------------------- + +# Sphinx's HTML writer renders a reference's ``rel`` attribute only from 7.4; +# ``target`` is rendered on every supported version. +# Browsers imply ``noopener`` for ``target="_blank"`` anyway. +RENDERS_REL = sphinx.version_info >= (7, 4) + + +def _stretched_link_tags(html): + """Return the opening ```` tag of every card ``sd-stretched-link``.""" + return re.findall(r"]*\bsd-stretched-link\b[^>]*>", html) + + +def _assert_opens_in_new_tab(html): + """The card's only stretched link opens in a new tab.""" + tags = _stretched_link_tags(html) + assert len(tags) == 1, tags + assert 'target="_blank"' in tags[0], tags[0] + if RENDERS_REL: + assert 'rel="noreferrer noopener"' in tags[0], tags[0] + else: + assert "rel=" not in tags[0], tags[0] + + +NEW_TAB_URL_RST = """ +Heading +======= + +.. card:: New-tab URL card + :link: https://example.com + :link-new-tab: + + Card body +""" + +NEW_TAB_URL_MYST = """ +# Heading + +:::{card} New-tab URL card +:link: https://example.com +:link-new-tab: + +Card body +::: +""" + + +@pytest.mark.parametrize("fmt", ["rst", MYST_PARAM]) +def test_card_url_new_tab(fmt, sphinx_builder): + """``link-new-tab`` adds ``target="_blank"`` and ``rel="noreferrer noopener"`` + to a URL card link. + """ + builder = _build(sphinx_builder, fmt, NEW_TAB_URL_RST, NEW_TAB_URL_MYST) + html = (builder.out_path / "index.html").read_text(encoding="utf8") + assert _stretched_link_hrefs(html) == ["https://example.com"] + _assert_opens_in_new_tab(html) + + +NEW_TAB_REF_RST = """ +Heading +======= + +My Section +---------- + +Some content. + +.. card:: New-tab internal card + :link: my section + :link-type: ref + :link-new-tab: + + Card body +""" + +NEW_TAB_REF_MYST = """ +# Heading + +## My Section + +Some content. + +:::{card} New-tab internal card +:link: my section +:link-type: ref +:link-new-tab: + +Card body +::: +""" + + +@pytest.mark.parametrize("fmt", ["rst", MYST_PARAM]) +def test_card_ref_new_tab(fmt, sphinx_builder): + """``link-new-tab`` also applies to internal cross-reference cards. + + ``pending_xref`` is resolved to ``nodes.reference`` before + ``doctree-resolved`` fires, so the event handler can stamp the + ``target`` and ``rel`` attributes onto the real anchor. + """ + builder = _build(sphinx_builder, fmt, NEW_TAB_REF_RST, NEW_TAB_REF_MYST) + html = (builder.out_path / "index.html").read_text(encoding="utf8") + assert _stretched_link_hrefs(html) == ["#my-section"] + _assert_opens_in_new_tab(html) + + +@pytest.mark.parametrize("fmt", ["rst", MYST_PARAM]) +def test_card_doc_new_tab(fmt, sphinx_builder): + """``link-new-tab`` applies to a ``link-type: doc`` card linking to another page.""" + if fmt == "rst": + builder = sphinx_builder(conf_kwargs={"extensions": ["sphinx_design"]}) + index = ( + "Heading\n=======\n\n" + ".. toctree::\n\n other\n\n" + ".. card:: New-tab doc card\n" + " :link: other\n :link-type: doc\n :link-new-tab:\n\n" + " Card body\n" + ) + builder.src_path.joinpath("index.rst").write_text(index, encoding="utf8") + builder.src_path.joinpath("other.rst").write_text( + "Other\n=====\n", encoding="utf8" + ) + else: + builder = sphinx_builder() + index = ( + "# Heading\n\n" + "```{toctree}\nother\n```\n\n" + ":::{card} New-tab doc card\n" + ":link: other\n:link-type: doc\n:link-new-tab:\n\n" + "Card body\n:::\n" + ) + builder.src_path.joinpath("index.md").write_text(index, encoding="utf8") + builder.src_path.joinpath("other.md").write_text("# Other\n", encoding="utf8") + builder.build() + html = (builder.out_path / "index.html").read_text(encoding="utf8") + assert _stretched_link_hrefs(html) == ["other.html"] + _assert_opens_in_new_tab(html) + + +NEW_TAB_GRID_RST = """ +Heading +======= + +.. grid:: 1 + + .. grid-item-card:: New-tab grid card + :link: https://example.com + :link-new-tab: + + Grid card body +""" + +NEW_TAB_GRID_MYST = """ +# Heading + +::::{grid} 1 + +:::{grid-item-card} New-tab grid card +:link: https://example.com +:link-new-tab: + +Grid card body +::: + +:::: +""" + + +@pytest.mark.parametrize("fmt", ["rst", MYST_PARAM]) +def test_grid_item_card_new_tab(fmt, sphinx_builder): + """``link-new-tab`` works on ``grid-item-card`` (synced ``option_spec``).""" + builder = _build(sphinx_builder, fmt, NEW_TAB_GRID_RST, NEW_TAB_GRID_MYST) + html = (builder.out_path / "index.html").read_text(encoding="utf8") + assert _stretched_link_hrefs(html) == ["https://example.com"] + _assert_opens_in_new_tab(html) + + +NO_NEW_TAB_RST = """ +Heading +======= + +My Section +---------- + +.. card:: URL card + :link: https://example.com + + Card body + +.. card:: Internal card + :link: my section + :link-type: ref + + Card body +""" + +NO_NEW_TAB_MYST = """ +# Heading + +## My Section + +:::{card} URL card +:link: https://example.com + +Card body +::: + +:::{card} Internal card +:link: my section +:link-type: ref + +Card body +::: +""" + + +@pytest.mark.parametrize("fmt", ["rst", MYST_PARAM]) +def test_card_link_without_new_tab(fmt, sphinx_builder): + """Without ``link-new-tab``, card links keep opening in the same tab.""" + builder = _build(sphinx_builder, fmt, NO_NEW_TAB_RST, NO_NEW_TAB_MYST) + html = (builder.out_path / "index.html").read_text(encoding="utf8") + assert _stretched_link_hrefs(html) == ["https://example.com", "#my-section"] + for tag in _stretched_link_tags(html): + assert "target=" not in tag, tag + assert "rel=" not in tag, tag diff --git a/tests/test_snippets/snippet_post_card-link.xml b/tests/test_snippets/snippet_post_card-link.xml index 59ec5e4..93f7911 100644 --- a/tests/test_snippets/snippet_post_card-link.xml +++ b/tests/test_snippets/snippet_post_card-link.xml @@ -42,6 +42,20 @@ example.com + + + + + Clickable Card (external, new tab) + + The entire card can be clicked to open + + https://example.com + in a new tab. + + + + example.com (opens in a new tab) diff --git a/tests/test_snippets/snippet_pre_card-link.xml b/tests/test_snippets/snippet_pre_card-link.xml index 2f7b35b..ab70413 100644 --- a/tests/test_snippets/snippet_pre_card-link.xml +++ b/tests/test_snippets/snippet_pre_card-link.xml @@ -42,6 +42,20 @@ example.com + + + + + Clickable Card (external, new tab) + + The entire card can be clicked to open + + https://example.com + in a new tab. + + + + example.com (opens in a new tab)