Skip to content

Commit bbd9e60

Browse files
committed
add(feature): use Mkdocs hook to take icon into account for social cards
1 parent a3746a2 commit bbd9e60

File tree

2 files changed

+153
-0
lines changed

2 files changed

+153
-0
lines changed
Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
#! python3 # noqa: E265
2+
3+
"""Script joué au chargement du contenu markdown de chaque page (hook).
4+
5+
Contexte :
6+
7+
Le thème Material for Mkdocs intègre un plugin (social) qui permet de générer
8+
automatiquement une image pour chaque page en croisant différents éléments
9+
(métadonnées de la page et éléments graphiques de base).
10+
Mais le fonctionnement est très générique (normal) et entre en conflit avec la gestion
11+
des en-têtes du site Geotribu.
12+
13+
Objectifs :
14+
15+
- quand une image n'est pas définie sur une page, patcher l'en-tête pour
16+
y insérer la configuration du plugin social de sorte qu'il génère une image
17+
et qu'on la référence
18+
- quand une image est définie manuellement, patcher l'en-tête pour
19+
y insérer la configuration du plugin social de sorte qu'il utilise l'image sans rien toucher
20+
21+
"""
22+
23+
# ############################################################################
24+
# ########## Libraries #############
25+
# ##################################
26+
27+
# standard library
28+
import logging
29+
from pathlib import Path
30+
from typing import Optional
31+
32+
# Mkdocs
33+
from material import __version__ as material_version
34+
from material.plugins.social.plugin import SocialPlugin
35+
from mkdocs.config.defaults import MkDocsConfig
36+
from mkdocs.plugins import event_priority
37+
from mkdocs.structure.files import Files
38+
from mkdocs.structure.pages import Page
39+
40+
# ###########################################################################
41+
# ########## Global ################
42+
# ##################################
43+
44+
logger = logging.getLogger("mkdocs")
45+
hook_name = Path(__file__).stem
46+
47+
# check si c'est la version Insiders (payante) ou la version Communauté (gratuite) du thème
48+
is_insiders = "insiders" in material_version
49+
50+
# ###########################################################################
51+
# ########## Functions #############
52+
# ##################################
53+
54+
55+
@event_priority(50)
56+
def on_page_markdown(
57+
markdown: str, *, page: Page, config: MkDocsConfig, files: Files
58+
) -> Optional[str]:
59+
"""
60+
The `page_markdown` event is called after the page's markdown is loaded
61+
from file and can be used to alter the Markdown source text. The meta-
62+
data has been stripped off and is available as `page.meta` at this point.
63+
64+
Parameters:
65+
markdown: Markdown source text of page as string
66+
page: `mkdocs.structure.pages.Page` instance
67+
config: global configuration object
68+
files: global files collection
69+
70+
Returns:
71+
Markdown source text of page as string
72+
"""
73+
# vérifie que le plugin social est bien installé et configuré
74+
if not config.plugins.get("material/social"):
75+
logger.warning(
76+
f"[{hook_name}] Le plugin social du thème Material n'est pas présent. "
77+
"Ce hook est donc inutile."
78+
)
79+
return
80+
81+
social_plugin: SocialPlugin = config.plugins.get("material/social")
82+
83+
# vérifie que le plugin est activé
84+
if not social_plugin.config.enabled or not social_plugin.config.cards:
85+
logger.debug(
86+
f"[{hook_name}] Le plugin social du thème Material est présent mais "
87+
"désactivé. Ce hook est donc inutile."
88+
)
89+
return
90+
91+
# Cas de figure où une image n'est pas définie
92+
if page.meta.get("image") is None or page.meta.get("image") == "":
93+
if not page.is_index:
94+
social_card_url = (
95+
f"{config.site_url}assets/images/social{page.abs_url[:-1]}.png"
96+
)
97+
else:
98+
social_card_url = (
99+
f"{config.site_url}assets/images/social{page.abs_url[:-1]}/index.png"
100+
)
101+
102+
logger.debug(
103+
f"{page.file.abs_src_path} n'a pas d'image. Une 'social card' sera "
104+
f"automatiquement générée : {social_card_url}"
105+
)
106+
107+
# si la page a une icône, on adapte le template de l'image (disponible que pour Insiders)
108+
# ref : https://squidfunk.github.io/mkdocs-material/reference#setting-the-page-icon
109+
if page.meta.get("icon") and is_insiders:
110+
cards_layout = "default/variant"
111+
logger.info(
112+
f"[{hook_name}] La page {page.abs_url} a une icône définie "
113+
f"({page.meta.get('icon')}). Dans ce cas, le modèle de social "
114+
f"card est : {cards_layout}"
115+
)
116+
elif is_insiders:
117+
cards_layout = social_plugin.config.cards_layout
118+
119+
# définit les paramètres pour les social cards au niveau de la page
120+
if is_insiders:
121+
page.meta["social"] = {
122+
"cards": True,
123+
"cards_layout": cards_layout,
124+
"cards_layout_options": social_plugin.config.cards_layout_options,
125+
}
126+
# else:
127+
# page.meta["social"] = {
128+
# "cards": True,
129+
# "cards_layout_options": {
130+
# "background_color": social_plugin.config.cards_layout_options.get(
131+
# "background_color"
132+
# ),
133+
# "color": social_plugin.config.cards_layout_options.get("color"),
134+
# "font_family": social_plugin.config.cards_layout_options.get(
135+
# "font_family"
136+
# ),
137+
# },
138+
# }
139+
else:
140+
logger.debug(
141+
f"[{hook_name}] {page.abs_url} a une image paramétrée. "
142+
"Désactivation du plugin social sur la page."
143+
)
144+
page.meta["social"] = {
145+
"cards": False,
146+
# TODO: les lignes suivantes pourront être réactivées quand le plugin
147+
# social gèrera les images distantes
148+
# "cards_layout": "default/only/image",
149+
# "cards_layout_options": {
150+
# "background_image": page.meta.get("image"),
151+
# },
152+
}

mkdocs.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ site_dir: !ENV [MKDOCS_OUTPUT_DIR, "./build/mkdocs/site"]
2020

2121
# Mkdocs hooks
2222
hooks:
23+
- hooks/mkdocs/G003_social_cards_adapter.py
2324
- hooks/mkdocs/G007_social_share_buttons.py
2425

2526
# Plugins

0 commit comments

Comments
 (0)