Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions docs/badges_buttons.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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

Expand Down
19 changes: 19 additions & 0 deletions docs/cards.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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`.

Expand Down
8 changes: 8 additions & 0 deletions docs/snippets/myst/card-link.txt
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ The entire card can be clicked to navigate to <https://example.com>.
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
Expand Down
7 changes: 7 additions & 0 deletions docs/snippets/rst/card-link.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 7 additions & 1 deletion sphinx_design/badges_buttons.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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

Expand Down
82 changes: 49 additions & 33 deletions sphinx_design/cards.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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."""
Expand Down Expand Up @@ -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.
Expand Down
27 changes: 27 additions & 0 deletions sphinx_design/extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand All @@ -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":
Expand Down
2 changes: 2 additions & 0 deletions sphinx_design/grids.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -274,6 +275,7 @@ def run_with_defaults(self) -> list[nodes.Node]:
"link",
"link-type",
"link-alt",
"link-new-tab",
"shadow",
"header",
"footer",
Expand Down
1 change: 1 addition & 0 deletions sphinx_design/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"opened",
"refexplicit",
"refwarn",
"sd_new_tab",
"selected",
"translatable",
"translated",
Expand Down
Loading
Loading