Skip to content

Commit d78b198

Browse files
committed
Factor out social_card_for_page()
1 parent 26cfaf4 commit d78b198

File tree

2 files changed

+79
-43
lines changed

2 files changed

+79
-43
lines changed

sphinxext/opengraph/__init__.py

Lines changed: 65 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
from typing import Any
1616

1717
from sphinx.application import Sphinx
18+
from sphinx.config import Config
19+
from sphinx.environment import BuildEnvironment
1820
from sphinx.util.typing import ExtensionMetadata
1921

2022
try:
@@ -165,34 +167,16 @@ def get_tags(
165167
and config_social.get("enable") is not False
166168
and create_social_card is not None
167169
):
168-
# Description
169-
description_max_length = config_social.get(
170-
"description_max_length", DEFAULT_DESCRIPTION_LENGTH_SOCIAL_CARDS - 3
171-
)
172-
if len(description) > description_max_length:
173-
description = description[:description_max_length].strip() + "..."
174-
175-
# Page title
176-
pagetitle = title
177-
if len(pagetitle) > DEFAULT_PAGE_LENGTH_SOCIAL_CARDS:
178-
pagetitle = pagetitle[:DEFAULT_PAGE_LENGTH_SOCIAL_CARDS] + "..."
179-
180-
# Site URL
181-
site_url = config_social.get("site_url", True)
182-
if site_url is True:
183-
url_text = app.config.ogp_site_url.split("://")[-1]
184-
elif isinstance(site_url, str):
185-
url_text = site_url
186-
187-
# Plot an image with the given metadata to the output path
188-
image_path = create_social_card(
189-
app,
190-
config_social,
191-
site_name,
192-
pagetitle,
193-
description,
194-
url_text,
195-
context["pagename"],
170+
image_url = social_card_for_page(
171+
config_social=config_social,
172+
site_name=site_name,
173+
title=title,
174+
description=description,
175+
pagename=context["pagename"],
176+
srcdir=app.srcdir,
177+
outdir=app.outdir,
178+
config=app.config,
179+
env=app.env,
196180
)
197181
ogp_use_first_image = False
198182

@@ -202,12 +186,6 @@ def get_tags(
202186
else:
203187
ogp_image_alt = description
204188

205-
# Link the image in our page metadata
206-
# We use os.path.sep to standardize behavior acros *nix and Windows
207-
url = app.config.ogp_site_url.strip("/")
208-
image_path = str(image_path).replace(os.path.sep, "/").strip("/")
209-
image_url = f"{url}/{image_path}"
210-
211189
# If the social card objects have been added we add special metadata for them
212190
# These are the dimensions *in pixels* of the card
213191
# They were chosen by looking at the image pixel dimensions on disk
@@ -267,6 +245,59 @@ def get_tags(
267245
)
268246

269247

248+
def social_card_for_page(
249+
config_social: dict[str, bool | str],
250+
site_name: str,
251+
title: str,
252+
description: str,
253+
pagename: str,
254+
*,
255+
srcdir: str | Path,
256+
outdir: str | Path,
257+
config: Config,
258+
env: BuildEnvironment,
259+
):
260+
# Description
261+
description_max_length = config_social.get(
262+
"description_max_length", DEFAULT_DESCRIPTION_LENGTH_SOCIAL_CARDS - 3
263+
)
264+
if len(description) > description_max_length:
265+
description = description[:description_max_length].strip() + "..."
266+
267+
# Page title
268+
pagetitle = title
269+
if len(pagetitle) > DEFAULT_PAGE_LENGTH_SOCIAL_CARDS:
270+
pagetitle = pagetitle[:DEFAULT_PAGE_LENGTH_SOCIAL_CARDS] + "..."
271+
272+
# Site URL
273+
site_url = config_social.get("site_url", True)
274+
if site_url is True:
275+
url_text = config.ogp_site_url.split("://")[-1]
276+
elif isinstance(site_url, str):
277+
url_text = site_url
278+
279+
# Plot an image with the given metadata to the output path
280+
image_path = create_social_card(
281+
config_social,
282+
site_name,
283+
pagetitle,
284+
description,
285+
url_text,
286+
pagename,
287+
srcdir=srcdir,
288+
outdir=outdir,
289+
config=config,
290+
env=env,
291+
)
292+
293+
# Link the image in our page metadata
294+
# We use os.path.sep to standardize behavior acros *nix and Windows
295+
url = config.ogp_site_url.strip("/")
296+
image_path = str(image_path).replace(os.path.sep, "/").strip("/")
297+
image_url = f"{url}/{image_path}"
298+
return image_url
299+
300+
270301
def html_page_context(
271302
app: Sphinx,
272303
pagename: str,

sphinxext/opengraph/socialcards.py

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@
1717

1818
from matplotlib.figure import Figure
1919
from matplotlib.text import Text
20-
from sphinx.application import Sphinx
20+
from sphinx.config import Config
21+
from sphinx.environment import BuildEnvironment
2122

2223
PltObjects: TypeAlias = tuple[Figure, Text, Text, Text, Text]
2324

@@ -58,13 +59,17 @@ def _set_description_line_width() -> int:
5859

5960

6061
def create_social_card(
61-
app: Sphinx,
6262
config_social: dict[str, bool | str],
6363
site_name: str,
6464
page_title: str,
6565
description: str,
6666
url_text: str,
6767
page_path: str,
68+
*,
69+
srcdir: str | Path,
70+
outdir: str | Path,
71+
config: Config,
72+
env: BuildEnvironment,
6873
) -> Path:
6974
"""Create a social preview card according to page metadata.
7075
@@ -84,7 +89,7 @@ def create_social_card(
8489
filename_image = f"summary_{page_path.replace('/', '_')}_{hash}.png"
8590

8691
# Absolute path used to save the image
87-
path_images_absolute = Path(app.builder.outdir) / path_images_relative
92+
path_images_absolute = Path(outdir) / path_images_relative
8893
path_images_absolute.mkdir(exist_ok=True, parents=True)
8994
path_image = path_images_absolute / filename_image
9095

@@ -99,13 +104,13 @@ def create_social_card(
99104

100105
# Large image to the top right
101106
if cs_image := config_social.get("image"):
102-
kwargs_fig["image"] = Path(app.builder.srcdir) / cs_image
103-
elif app.config.html_logo:
104-
kwargs_fig["image"] = Path(app.builder.srcdir) / app.config.html_logo
107+
kwargs_fig["image"] = Path(srcdir) / cs_image
108+
elif config.html_logo:
109+
kwargs_fig["image"] = Path(srcdir) / config.html_logo
105110

106111
# Mini image to the bottom right
107112
if cs_image_mini := config_social.get("image_mini"):
108-
kwargs_fig["image_mini"] = Path(app.builder.srcdir) / cs_image_mini
113+
kwargs_fig["image_mini"] = Path(srcdir) / cs_image_mini
109114
else:
110115
kwargs_fig["image_mini"] = (
111116
Path(__file__).parent / "_static/sphinx-logo-shadow.png"
@@ -135,7 +140,7 @@ def create_social_card(
135140

136141
# Generate the image and store the matplotlib objects so that we can re-use them
137142
try:
138-
plt_objects = app.env.ogp_social_card_plt_objects
143+
plt_objects = env.ogp_social_card_plt_objects
139144
except AttributeError:
140145
# If objects is None it means this is the first time plotting.
141146
# Create the figure objects and return them so that we re-use them later.
@@ -148,7 +153,7 @@ def create_social_card(
148153
url_text,
149154
plt_objects,
150155
)
151-
app.env.ogp_social_card_plt_objects = plt_objects
156+
env.ogp_social_card_plt_objects = plt_objects
152157

153158
# Path relative to build folder will be what we use for linking the URL
154159
path_relative_to_build = path_images_relative / filename_image

0 commit comments

Comments
 (0)