Skip to content

Commit

Permalink
Fonctionnalité : active les cartes de partage automatiques pour les c…
Browse files Browse the repository at this point in the history
…ontenus sans image (#921)

L'objectif est d'activer le plugin `social` intégré au thème Material
qui permet de générer une image automatiquement à partir des métadonnées
de la page et de quelques éléments graphiques de base (logo, image de
fond...).

- doc du plugin intégré au thème :
https://squidfunk.github.io/mkdocs-material/setup/setting-up-social-cards/
- ticket pour demander des évolutions sur le plugin social :
squidfunk/mkdocs-material#5567
  • Loading branch information
Guts authored Jul 27, 2023
2 parents 4544dfb + e4b3297 commit d28ed3e
Show file tree
Hide file tree
Showing 13 changed files with 197 additions and 24 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ jobs:

- name: Build static website
run: |
python scripts/mkdocs_populate_latest.py
python scripts/mkdocs_config_merger.py -c mkdocs.yml
python scripts/050_mkdocs_populate_latest.py
python scripts/100_mkdocs_config_merger.py -c mkdocs.yml
mkdocs build --clean --config-file mkdocs.yml --verbose --strict
env:
MKDOCS_ENABLE_PLUGIN_GIT_AUTHORS: true
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/links_checker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ jobs:
- name: Build static website
run: |
python scripts/mkdocs_populate_latest.py
python scripts/mkdocs_config_merger.py -c mkdocs.yml
python scripts/050_mkdocs_populate_latest.py
python scripts/100_mkdocs_config_merger.py -c mkdocs.yml
mkdocs build --clean --config-file mkdocs.yml --quiet --strict
env:
MKDOCS_ENABLE_PLUGIN_RSS: true
Expand Down
11 changes: 3 additions & 8 deletions .github/workflows/pr_checker_build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -69,18 +69,13 @@ jobs:
MKDOCS_SITE_NAME: "Geotribu PREVIEW - PR ${{ github.event.pull_request.number }}"
MKDOCS_SITE_COPYRIGHT: '<a href="https://www.netlify.com/"><img alt="Deploys by Netlify" src="https://www.netlify.com/img/global/badges/netlify-color-accent.svg" style="float: right;"></a>'
run: |
echo $PR_NUMBER
echo $GITHUB_HEAD_REF
echo $MKDOCS_EDIT_URI
echo $MKDOCS_SITE_NAME
# store custom env vars that need resolution
export MKDOCS_EDIT_URI="edit/${GITHUB_HEAD_REF}/content"
echo $MKDOCS_EDIT_URI
MKDOCS_SITE_URL="https://${NETLIFY_SITE_PREFIX}--${NETLIFY_SITE_NAME}.netlify.app/"
export MKDOCS_SITE_URL="https://${NETLIFY_SITE_PREFIX}--${NETLIFY_SITE_NAME}.netlify.app/"
# merge different configs
python scripts/mkdocs_populate_latest.py
python scripts/mkdocs_config_merger.py -c ${{ env.MKDOCS_CONFIG_FILENAME }}
python scripts/050_mkdocs_populate_latest.py
python scripts/100_mkdocs_config_merger.py -c ${{ env.MKDOCS_CONFIG_FILENAME }}
# build
mkdocs build --config-file ${{ env.MKDOCS_CONFIG_FILENAME }} --strict
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -228,3 +228,4 @@ authors.json
md_linter_report.txt
config/extra_latest.yml
linkchecker_report.html
!content/theme/assets/images/geotribu/background_geotribu.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 0 additions & 2 deletions content/theme/main.html
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@

{# OpenGraph #}
<meta property="og:description" content="{{ description }}">
<meta property="og:image" content="{{ image }}">
<meta property="og:locale" content="fr_FR" />
<meta property="og:title" content="{{ title }}">
<meta property="og:type" content="{{ type }}">
Expand All @@ -76,7 +75,6 @@
<meta name="twitter:creator" content="@geojulien" />
<meta name="twitter:description" content="{{ description }}">
<meta name="twitter:dnt" content="on">
<meta name="twitter:image" content="{{ image }}">
<meta name="twitter:site" content="@geotribu" />
<meta name="twitter:title" content="{{ title }}">
<meta name="twitter:widgets:align" content="center">
Expand Down
2 changes: 1 addition & 1 deletion content/theme/partials/license.html
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
<a href="https://fr.wikipedia.org/wiki/Beerware" target="_blank" rel="license noopener noreferrer"
title="Licence très permissive qui confère à l'utilisateur final le droit d'utiliser le contenu, sans conditions sauf paternité. Si l'utilisateur rencontre l'auteur, il est encouragé à lui offrir une bière ou autre en retour.">Beerware
<img src="https://cdn.geotribu.fr/img/internal/licences/BeerWare.svg" class=img-license-picto
alt="Pictogramme BeerWare" longdesc="Kita59, CC BY-SA 3.0, via Wikimedia Commons" title="Beerware" />
alt="Pictogramme BeerWare" title="Beerware - Kita59, CC BY-SA 3.0, via Wikimedia Commons" />
</a>
</p>
</small>
Expand Down
140 changes: 140 additions & 0 deletions hooks/mkdocs/G003_social_cards_adapter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
#! python3 # noqa: E265

"""Script joué au chargement du contenu markdown de chaque page (hook).
Contexte :
Le thème Material for Mkdocs intègre un plugin (social) qui permet de générer
automatiquement une image pour chaque page en croisant différents éléments
(métadonnées de la page et éléments graphiques de base).
Mais le fonctionnement est très générique (normal) et entre en conflit avec la gestion
des en-têtes du site Geotribu.
Objectifs :
- quand une image n'est pas définie sur une page, patcher l'en-tête pour
y insérer la configuration du plugin social de sorte qu'il génère une image
et qu'on la référence
- quand une image est définie manuellement, patcher l'en-tête pour
y insérer la configuration du plugin social de sorte qu'il utilise l'image sans rien toucher
"""

# ############################################################################
# ########## Libraries #############
# ##################################

# standard library
import logging
from pathlib import Path
from typing import Optional

# Mkdocs
from material.plugins.social.plugin import SocialPlugin
from mkdocs.config.defaults import MkDocsConfig
from mkdocs.plugins import event_priority
from mkdocs.structure.files import Files
from mkdocs.structure.pages import Page

# ###########################################################################
# ########## Global ################
# ##################################

logger = logging.getLogger("mkdocs")
hook_name = Path(__file__).stem

# ###########################################################################
# ########## Functions #############
# ##################################


@event_priority(50)
def on_page_markdown(
markdown: str, *, page: Page, config: MkDocsConfig, files: Files
) -> Optional[str]:
"""
The `page_markdown` event is called after the page's markdown is loaded
from file and can be used to alter the Markdown source text. The meta-
data has been stripped off and is available as `page.meta` at this point.
Parameters:
markdown: Markdown source text of page as string
page: `mkdocs.structure.pages.Page` instance
config: global configuration object
files: global files collection
Returns:
Markdown source text of page as string
"""
# exclude homepage
if page.is_homepage:
return

# vérifie que le plugin social est bien installé et configuré
if not config.plugins.get("material/social"):
logger.warning(
f"[{hook_name}] Le plugin social du thème Material n'est pas présent. Ce hook est donc inutile."
)
return

social_plugin: SocialPlugin = config.plugins.get("material/social")

# vérifie que le plugin est activé
if not social_plugin.config.enabled or not social_plugin.config.cards:
logger.debug(
f"[{hook_name}] Le plugin social du thème Material est présent mais désactivé. Ce hook est donc inutile."
)
return

# Cas de figure où une image n'est pas définie
if page.meta.get("image") is None or page.meta.get("image") == "":
social_card_url = (
f"{config.site_url}assets/images/social{page.abs_url[:-1]}.png"
)
logger.debug(
f"{page.abs_url} n'a pas d'image. Une 'social card' sera automatiquement générée : {social_card_url}"
)

# si la page a une icône, on adapte le template de l'image
# ref : https://squidfunk.github.io/mkdocs-material/reference#setting-the-page-icon
if page.meta.get("icon"):
cards_layout = "default/variant"
logger.info(
f"[{hook_name}] La page {page.abs_url} a une icône définie "
f"({page.meta.get('icon')}). Dans ce cas, le modèle de social "
f"card est : {cards_layout}"
)
else:
cards_layout = social_plugin.config.cards_layout

#
page.meta["image"] = social_card_url
page.meta["social"] = {
"cards": True,
"cards_layout": cards_layout,
"cards_layout_options": {
"background_color": social_plugin.config.cards_layout_options.get(
"background_color"
),
"background_image": social_plugin.config.cards_layout_options.get(
"background_image",
"content/theme/assets/images/geotribu/background_geotribu.png",
),
"color": social_plugin.config.cards_layout_options.get("color"),
"font_family": social_plugin.config.cards_layout_options.get(
"font_family"
),
},
}
else:
logger.debug(
f"[{hook_name}] {page.abs_url} a une image paramétrée. Désactivation du plugin social sur la page."
)
page.meta["social"] = {
"cards": False,
# TODO: les lignes suivantes pourront être réactivées quand le plugin social gèrera les images distantes
# "cards_layout": "default/only/image",
# "cards_layout_options": {
# "background_image": page.meta.get("image"),
# },
}
16 changes: 14 additions & 2 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ site_dir: !ENV [MKDOCS_OUTPUT_DIR, "./build/mkdocs/site"]
hooks:
- hooks/mkdocs/G001_check_hyperlinks_internal.py
# - hooks/mkdocs/G002_check_images_size.py
- hooks/mkdocs/G003_social_cards_adapter.py

# Plugins
plugins:
Expand Down Expand Up @@ -138,12 +139,23 @@ plugins:
- boundlessgeo.com/*
- i3.codeplex.com/*
- drfhlmcehrc34.cloudfront.net/*
- social:
enabled: !ENV [MKDOCS_ENABLE_PLUGIN_SOCIAL, true]
cards: !ENV [MKDOCS_ENABLE_PLUGIN_SOCIAL_CARDS, true]
cards_exclude:
- index.md
- toc_nav_ignored/*.md
cards_layout_options:
background_color: "#00000000"
background_image: content/theme/assets/images/geotribu/background_geotribu.png
color: "#3e93a7"
font_family: Ubuntu

# Theme
theme:
name: "material"
custom_dir: "./content/theme/"
favicon: "https://cdn.geotribu.fr/img/internal/charte/geotribu_logo_64x64.png"
favicon: theme/assets/images/geotribu/logo_geotribu.png

# Don't include MkDocs' JavaScript
include_search_page: false
Expand All @@ -166,7 +178,7 @@ theme:
- toc.follow
font: false
language: fr
logo: "https://cdn.geotribu.fr/img/internal/charte/geotribu_logo_64x64.png"
logo: theme/assets/images/geotribu/logo_geotribu.png
palette:
# Palette toggle for automatic mode
- media: "(prefers-color-scheme)"
Expand Down
2 changes: 1 addition & 1 deletion requirements-insiders.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Insiders
# --------

git+https://${GH_TOKEN_MATERIAL_INSIDERS}@github.com/squidfunk/[email protected].16-insiders-4.36.0#egg=mkdocs-material
git+https://${GH_TOKEN_MATERIAL_INSIDERS}@github.com/squidfunk/[email protected].18-insiders-4.37.0#egg=mkdocs-material
# git+https://${GH_TOKEN_MATERIAL_INSIDERS}@github.com/squidfunk/mkdocs-material-insiders.git

mkdocs-git-committers-plugin-2>=1,<2
Expand Down
4 changes: 4 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,7 @@ mkdocs-macros-plugin>=0.5,<1.1
mkdocs-minify-plugin<0.7
mkdocs-redirects<1.3
mkdocs-rss-plugin>=1.4,<1.8

# social plugin requirements
CairoSVG>=2.5,<3
Pillow>=9.4,<9.6
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# 3rd party
import yaml
from mkdocs.structure.pages import Page
from mkdocs.utils import yaml_load
from mkdocs.utils.meta import get_data

# ###########################################################################
Expand All @@ -21,12 +22,17 @@

logger = logging.getLogger("mkdocs")


# ###########################################################################
# ########## Functions #############
# ##################################


def get_latest_content(content_type: Literal["articles", "rdp"], count: int = 10):
def get_latest_content(
content_type: Literal["articles", "rdp"],
count: int = 10,
social_card_image_base: str = "https://static.geotribu.fr/assets/images/social/",
):
output_contents_list: list[Page] = []

if content_type == "articles":
Expand All @@ -39,18 +45,35 @@ def get_latest_content(content_type: Literal["articles", "rdp"], count: int = 10
)[:count]:
with content.open(encoding="utf-8-sig", errors="strict") as f:
source = f.read()
# markdown, meta = get_data(source)
output_contents_list.append(
get_data(source)[1] | {"url_rel": str(content.relative_to("content/"))[:-3]}
)

page_meta = get_data(source)[1]

page_rel = str(content.relative_to("content/"))[:-3]

if page_meta.get("image") is None or page_meta.get("image") == "":
social_card_url = f"{social_card_image_base}{page_rel}.png"
output_contents_list.append(
get_data(source)[1] | {"url_rel": page_rel} | {"image": social_card_url}
)
else:
output_contents_list.append(get_data(source)[1] | {"url_rel": page_rel})

return output_contents_list


# charge la configuration
with Path("mkdocs.yml").open(mode="r", encoding="UTF8") as in_yaml:
mkdocs_config = yaml_load(in_yaml)

output_dict = {"latest": {"articles": [], "rdp": []}}

# print(get_latest_content(content_type="articles"))

for k in output_dict.get("latest"):
output_dict["latest"][k] = get_latest_content(content_type=k)
output_dict["latest"][k] = get_latest_content(
content_type=k,
social_card_image_base=f"{mkdocs_config.get('site_url')}assets/images/social/",
)

with Path("config/extra_latest.yml").open("w", encoding="UTF-8") as out_file:
yaml.safe_dump(
Expand Down
File renamed without changes.

0 comments on commit d28ed3e

Please sign in to comment.