Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 1 addition & 2 deletions great_docs/_website/assembly.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,6 @@ def assemble(
brand.register_release(quarto_config, config, facts)
quarto_defaults.register_extensions(quarto_config)

# Quarto renders page titles and translation metadata from this partial.
metadata_partial.write(quarto_config, config, layout, report=report)
nav_label.register(quarto_config, config)
i18n.register(quarto_config, config)

Expand All @@ -203,6 +201,7 @@ def assemble(
# and footer above. Later build steps, such as reference sidebar pruning and sidebar
# sharing, then work on the merged navigation.
website_overlay.apply(quarto_config, config, layout, pages, report=report)
metadata_partial.write(quarto_config, config, layout, report=report)

if config.has_versions:
version_selector.register(quarto_config, config)
Expand Down
11 changes: 10 additions & 1 deletion great_docs/_website/metadata_partial.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from pathlib import Path
from typing import TYPE_CHECKING, Any, cast

from . import i18n, page_dates, social_cards
from . import i18n, page_dates, quarto_yml, social_cards
from .seo import title as seo_title

if TYPE_CHECKING:
Expand All @@ -30,6 +30,7 @@
"""

_BUNDLED = Path(__file__).parents[1] / "assets" / FILENAME
_SITE_NAME = "gd-seo-site-name"


def title_element(template: object) -> str | None:
Expand Down Expand Up @@ -110,6 +111,14 @@ def write(
# Use a callable replacement so backslashes and `$` remain literal.
partial = re.sub(r"<title>.*</title>", lambda _match: title_line, partial)

site_name = quarto_config.get("website", {}).get("title")
if isinstance(site_name, str) and seo_title.has_site_name_markup(site_name):
quarto_config[_SITE_NAME] = site_name
quarto_yml.entries(html_config, "filters").append("gd-site-title")
partial = partial.replace(
"$title-prefix$", f"$if({_SITE_NAME})$${_SITE_NAME}$$else$$title-prefix$$endif$"
)

meta_tag = i18n.meta_tag(config)
if meta_tag is not None:
# Pandoc templates require `$$` to render a literal `$`.
Expand Down
10 changes: 10 additions & 0 deletions great_docs/_website/seo/title.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,16 @@
_KEYS = re.compile(r"(\{page_title\}|\{site_name\})")


_SITE_NAME_MARKUP = re.compile(r"[<*`\[\~^]|(?<!\w)_|&(?:#\w+|\w+);")


def has_site_name_markup(site_name: str) -> bool:
"""
Recognise site names that can contain Markdown, HTML or shortcodes
"""
return _SITE_NAME_MARKUP.search(site_name) is not None


def is_valid(template: object) -> TypeGuard[str]:
"""
Check whether a configured title template can be applied
Expand Down
9 changes: 5 additions & 4 deletions great_docs/_website/social_cards.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,14 +201,15 @@ def page_title(title: str | None, site_name: str | None, config: Config) -> str
"""
if title is None or not site_name:
return None
site_title = (
site_name if seo_title.has_site_name_markup(site_name) else metadata.as_metadata(site_name)
)
if not title.strip():
return metadata.as_metadata(site_name)
return site_title
template = seo_title.template(config)
if template is None:
return None
return seo_title.apply(
template, title, metadata.as_metadata(site_name), escape=metadata.as_metadata
)
return seo_title.apply(template, title, site_title, escape=metadata.as_metadata)


def page_entries(
Expand Down
8 changes: 8 additions & 0 deletions great_docs/assets/_extensions/gd-site-title/_extension.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
title: Site Title
author: Great Docs
version: 1.0.0
quarto-required: ">=1.5.0"
contributes:
filters:
- path: gd-site-title.lua
at: post-quarto
21 changes: 21 additions & 0 deletions great_docs/assets/_extensions/gd-site-title/gd-site-title.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
--- Extract the visible text after Quarto expands shortcodes
local function plain_title(value)
local inlines = quarto.utils.as_inlines(value)
local fragment = pandoc.Pandoc({pandoc.Plain(inlines)})
-- Reading the rendered fragment includes the text inside raw HTML tags.
local rendered = pandoc.read(pandoc.write(fragment, "html"), "html")
local text = pandoc.utils.stringify(rendered):gsub("%s+", " "):match("^%s*(.-)%s*$")
return pandoc.MetaString(text)
end

function Meta(meta)
if meta["gd-seo-site-name"] == nil then
return
end

meta["gd-seo-site-name"] = plain_title(meta["gd-seo-site-name"])
if meta.pagetitle ~= nil then
meta.pagetitle = plain_title(meta.pagetitle)
end
return meta
end
62 changes: 62 additions & 0 deletions tests/test_social_cards_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,22 @@
Social card metadata rendered from site and page options
"""

import io
import re
import shutil
import subprocess
from pathlib import Path

import pytest
from bs4 import BeautifulSoup
from yaml12 import format_yaml

import great_docs
from great_docs._build import pipeline, quarto
from great_docs._build.log import BuildLog
from great_docs._website import page_metadata, social_cards
from great_docs.config import Config
from tests.support import StubRemote, write_config

pytestmark = pytest.mark.skipif(shutil.which("quarto") is None, reason="Quarto is not installed")

Expand Down Expand Up @@ -129,3 +134,60 @@ def test_pages_with_their_own_tags_keep_them_alone(tmp_path):
assert plain["og:type"] == ["website"]
assert plain["og:url"] == ["https://docs.example.com/pkg/plain.html"]
assert plain["og:title"] == ["Plain | Pkg"]


@pytest.mark.parametrize(("seo", "separator"), [(True, "|"), (False, "–")])
def test_formatted_site_name_has_plain_browser_and_card_titles(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, seo: bool, separator: str
) -> None:
site_title = "Posit SDK <small>{{< env PROJECT_VERSION >}}</small> & *Tools*"
write_config(
tmp_path,
{
"reference": False,
"seo": {"enabled": seo},
"site_root": {"pages": ["quickstart.qmd", "custom.qmd"]},
"quarto": {"website": {"title": site_title, "navbar": {"left": ["quickstart.qmd"]}}},
},
)
(tmp_path / "index.qmd").write_text('---\ntitle: ""\n---\n\nWelcome.\n')
(tmp_path / "quickstart.qmd").write_text(
'---\ntitle: "Quick *Start* & Work"\n---\n\nQuick start guide.\n'
)
(tmp_path / "custom.qmd").write_text(
"---\ntitle: Custom\n"
"open-graph: {title: Curated card}\n"
"twitter-card: {title: Custom social card}\n"
"---\n\nCustom metadata.\n"
)
monkeypatch.setenv("PROJECT_VERSION", "0.17.0")
docs = great_docs.GreatDocs(project_path=str(tmp_path))
config = docs._config
pipeline.prepare_for_freeze(
config, docs.layout, BuildLog(stream=io.StringIO()), remote=StubRemote()
)
subprocess.run(
["quarto", "render"],
cwd=docs.layout.build_dir,
env=quarto.environment(config),
check=True,
capture_output=True,
timeout=60,
)
output = docs.layout.build_dir / "_site"
plain_site_name = "Posit SDK 0.17.0 & Tools"
start = BeautifulSoup((output / "quickstart.html").read_text(), "html.parser")
expected = f"Quick Start & Work {separator} {plain_site_name}"
assert start.title.get_text() == expected
assert start.find("meta", property="og:title")["content"] == expected
assert start.find("meta", attrs={"name": "twitter:title"})["content"] == expected
assert start.select_one(".navbar-title small").get_text() == "0.17.0"
assert start.select_one(".navbar-title em").get_text() == "Tools"

index = BeautifulSoup((output / "index.html").read_text(), "html.parser")
assert index.title.get_text() == plain_site_name
assert index.find("meta", property="og:title")["content"] == plain_site_name

custom = BeautifulSoup((output / "custom.html").read_text(), "html.parser")
assert custom.find("meta", property="og:title")["content"] == "Curated card"
assert custom.find("meta", attrs={"name": "twitter:title"})["content"] == "Custom social card"
Loading