leshed_svg_export : générateur d'animation de titres (morphing entre tirages)

Page outil /admin/leshed/titre-anime (permission « export leshed typography ») :
texte libre, N tirages graisse/italique selon les règles du site (copie de
titles.js dans js/title-animation/draw.js), chaque lettre changeant de groupe
ou de style d'un tirage au suivant. Modes boucle / vague / bouillonnement,
morphing de la graisse, fondu pour l'italique, texte qui respire.

Exports : SVG animé (SMIL), MP4/WebM (WebCodecs via mediabunny), GIF (gifenc).
Dépendances Composer : npm-asset/mediabunny, npm-asset/gifenc.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 13:03:07 +01:00
co-authored by Claude Opus 5.5
parent b3877c84d4
commit 4871d88842
12 changed files with 1505 additions and 24 deletions
+2
View File
@@ -38,7 +38,9 @@
"drupal/structure_sync": "^2.0",
"drupal/views_entity_form_field": "^1.2",
"league/commonmark": "^2.8",
"npm-asset/gifenc": "^1.0",
"npm-asset/harfbuzzjs": "^1.6",
"npm-asset/mediabunny": "^1.66",
"oomphinc/composer-installers-extender": "^2.0",
"wikimedia/composer-merge-plugin": "^2.1"
},
Generated
+60 -1
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "5a12e49291d6e176f5a1629f98f1b16f",
"content-hash": "e071b03e241cbbad2aad8eaf0d22c0d0",
"packages": [
{
"name": "asm89/stack-cors",
@@ -9035,6 +9035,19 @@
},
"time": "2026-09-13T18:51:52+00:00"
},
{
"name": "npm-asset/gifenc",
"version": "1.0.3",
"dist": {
"type": "tar",
"url": "https://registry.npmjs.org/gifenc/-/gifenc-1.0.3.tgz",
"shasum": "3a1a97fa5ab70ebefd000350b9aac8313b30b3aa"
},
"type": "npm-asset",
"license": [
"MIT"
]
},
{
"name": "npm-asset/harfbuzzjs",
"version": "1.6.4",
@@ -9048,6 +9061,52 @@
"MIT"
]
},
{
"name": "npm-asset/mediabunny",
"version": "1.66.4",
"dist": {
"type": "tar",
"url": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.66.4.tgz",
"shasum": "47e1de354ea07066a688ba30c6783d8c71da0bd7"
},
"require": {
"npm-asset/types--dom-mediacapture-transform": ">=0.1.11,<0.2.0",
"npm-asset/types--dom-webcodecs": "0.1.13"
},
"type": "npm-asset",
"license": [
"MPL-2.0"
]
},
{
"name": "npm-asset/types--dom-mediacapture-transform",
"version": "0.1.12",
"dist": {
"type": "tar",
"url": "https://registry.npmjs.org/@types/dom-mediacapture-transform/-/dom-mediacapture-transform-0.1.12.tgz",
"shasum": "82fdc7aa2eb97a7a73e2df774080068bef2e599b"
},
"require": {
"npm-asset/types--dom-webcodecs": "*"
},
"type": "npm-asset",
"license": [
"MIT"
]
},
{
"name": "npm-asset/types--dom-webcodecs",
"version": "0.1.13",
"dist": {
"type": "tar",
"url": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.13.tgz",
"shasum": "d8be5da4f01b20721307b08ad2cca903ccf4f47f"
},
"type": "npm-asset",
"license": [
"MIT"
]
},
{
"name": "oomphinc/composer-installers-extender",
"version": "2.0.1",
@@ -219,3 +219,72 @@ puisque le CSS de Gin n'est pas chargé sur les pages front.
métriques de police (ascender/unitsPerEm) plutôt que sur une mesure
exacte de ligne de base — fidèle en pratique mais pas garanti au pixel
près sur toutes les combinaisons police/navigateur.
## Générateur d'animation de titres (`/admin/leshed/titre-anime`)
Page outil (permission `export leshed typography`, lien dans
Configuration › Médias) qui anime un texte libre par **morphing entre N
tirages** de graisses/italiques, et l'exporte en **SVG animé**, **MP4**,
**WebM** ou **GIF**. Tout se fait côté client.
### Fichiers
- `src/Controller/TitleAnimationController.php` : conteneur + URL des
moteurs et de la police (`drupalSettings.leshedTitleAnimation`).
- `js/title-animation.js` (module ES) : interface, aperçu, exports.
- `js/title-animation/draw.js` : **copie** des règles de tirage de
`themes/custom/leshed/assets/js/titles.js` (`TITLE_STYLE`,
`spreadPositions()`, `styleWordChars()`). Choix délibéré de ne pas
refactorer `titles.js` : **toute modification des règles côté thème doit
être reportée dans ce fichier.**
- `js/title-animation/engine.js` : texte → tirages → timeline → mise en
page → rendu canvas.
- `js/title-animation/exporters.js` : SVG (SMIL), vidéo (mediabunny), GIF
(gifenc).
### Principe
- **Police** : les deux fichiers variables Epilogue du thème
(`assets/dist/fonts/`, romain et italique), lus par HarfBuzz. Pas de
résolution par `@font-face` ici : la page est rendue dans le thème
d'administration, qui ne charge pas la police du site.
- **Chaque lettre change à chaque tirage** (règle propre au générateur) :
d'un tirage au suivant, et du dernier au premier, chaque lettre change de
groupe (fine / medium / grasse) ou bascule romain ↔ italique. Les règles du
site sont conservées (positions des groupes, ≥ 1 italique par mot, ≤ 2
italiques consécutives) ; quand elles rendent le changement impossible
(mot d'une lettre, toujours fin et italique sur le site ; cycles impairs
sur des mots courts), la lettre change de groupe hors proportions du site.
L'aperçu indique combien de lettres sont dans ce cas.
- **Graisse** : interpolée en continu entre deux tirages (axe `wght`).
- **Italique** : fichier séparé, donc non interpolable ; fondu enchaîné
(opacité romain `1 − k`, italique `k`), l'avance de la lettre suivant le
même mélange.
- **Le texte respire** : chaque lettre prend son avance réelle à chaque
image, `letter-spacing: -0.1em` et interligne 1 comme sur le site,
minuscules (`text-transform: lowercase`). La taille du texte est fixe sur
toute la boucle (calée sur la ligne la plus large atteinte) pour que rien
ne « pompe ».
- **Modes** (boucle parfaite dans les trois cas) :
- *Boucle* : pause sur chaque tirage, puis morphing vers le suivant ;
- *Vague* : idem, décalé de gauche à droite (`Décalage`) ;
- *Bouillonnement* : pas de pause, décalage aléatoire par lettre.
- Retours à la ligne : uniquement ceux saisis (pas de césure automatique).
### Exports
| Format | Fond | Moteur |
|---|---|---|
| SVG animé | transparent | SMIL : `d` des tracés interpolé entre tirages (`keySplines` = courbe choisie), opacité pour l'italique, positions échantillonnées à 25 i/s |
| WebM | transparent si le navigateur encode VP9 + alpha, sinon blanc | WebCodecs via mediabunny |
| MP4 | blanc (H.264 sans alpha) | WebCodecs via mediabunny |
| GIF | blanc | gifenc, palette fixe de 256 gris (pas de tramage) |
Vidéo et GIF sont encodés image par image (pas en temps réel). Si le
navigateur ne sait pas encoder un codec (WebCodecs), un message l'indique.
### Dépendances (Composer, asset-packagist)
`npm-asset/mediabunny` (MPL-2.0) et `npm-asset/gifenc` (MIT), installés
dans `web/libraries/` comme `harfbuzzjs`. Le prérequis nginx sur `.mjs`
(voir plus haut) s'applique aussi à `mediabunny.min.mjs`.
@@ -0,0 +1,135 @@
/*
* Page outil « Titre animé » — s'appuie sur les styles de formulaire de Gin,
* en version condensée : une ligne par réglage (libellé | tirette | valeur).
* Sélecteurs préfixés par l'id pour passer devant les marges de Gin/Claro.
*/
#leshed-title-animation .lta {
display: grid;
grid-template-columns: minmax(20rem, 24rem) 1fr;
gap: 1.5rem;
align-items: start;
}
@media (max-width: 60rem) {
#leshed-title-animation .lta { grid-template-columns: 1fr; }
}
#leshed-title-animation [hidden] { display: none !important; }
/* Groupes */
#leshed-title-animation .lta__group {
margin: 0 0 0.75rem;
padding: 0 0 0.75rem;
border: 0;
border-bottom: 1px solid var(--gin-border-color, #ddd);
}
#leshed-title-animation .lta__group:last-child { border-bottom: 0; }
#leshed-title-animation .lta__group legend {
margin: 0 0 0.35rem;
padding: 0;
font-size: 0.75rem;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
opacity: 0.7;
}
/* Une ligne par réglage : libellé à gauche, contrôle à droite. */
#leshed-title-animation .lta__row { display: block; }
#leshed-title-animation .form-item {
display: grid;
grid-template-columns: 7.5rem 1fr;
align-items: center;
gap: 0.5rem;
margin: 0 0 0.3rem;
padding: 0;
}
#leshed-title-animation .form-item__label {
margin: 0;
padding: 0;
font-size: 0.8125rem;
font-weight: 400;
line-height: 1.2;
}
#leshed-title-animation .form-element {
min-height: 0;
height: 1.9rem;
padding: 0.15rem 0.4rem;
font-size: 0.8125rem;
line-height: 1.2;
}
#leshed-title-animation .form-select { padding-inline-end: 1.75rem; background-position: right 0.4rem center; }
#leshed-title-animation .form-item select.form-element { width: 100%; }
/* Texte : libellé au-dessus, pleine largeur. */
#leshed-title-animation .form-item:has(textarea) { grid-template-columns: 1fr; gap: 0.2rem; }
#leshed-title-animation textarea.form-element { height: auto; padding: 0.3rem 0.4rem; }
/* Tirette + champ numérique (saisie précise). */
#leshed-title-animation .lta__range {
display: flex;
align-items: center;
gap: 0.4rem;
min-width: 0;
}
#leshed-title-animation .lta__slider { flex: 1; min-width: 3rem; margin: 0; accent-color: currentColor; }
#leshed-title-animation .lta__range .form-element { flex: 0 0 4.25rem; width: 4.25rem; min-width: 0; }
/* Boutons compacts */
#leshed-title-animation .button {
margin: 0;
padding: 0.3rem 0.7rem;
min-height: 0;
font-size: 0.8125rem;
line-height: 1.2;
}
#leshed-title-animation .lta__row > .button { margin: 0.1rem 0 0.3rem 8rem; }
#leshed-title-animation .lta__buttons {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
margin-top: 0.4rem;
}
#leshed-title-animation .lta__progress { width: 100%; margin-top: 0.5rem; }
#leshed-title-animation .lta__status { min-height: 1.2em; margin: 0.4rem 0 0; font-size: 0.8125rem; }
#leshed-title-animation .lta__status--error { color: #d72222; font-weight: 700; }
/* Aperçu */
#leshed-title-animation .lta__preview { position: sticky; top: 1rem; }
#leshed-title-animation .lta__stage {
display: flex;
justify-content: center;
align-items: center;
height: min(78vh, 920px);
padding: 1rem;
/* Hors cadre : gris neutre, pour que les limites du cadre sautent aux yeux. */
background: #6e6e6e;
border-radius: 4px;
}
#leshed-title-animation .lta__canvas {
max-width: 100%;
max-height: 100%;
/* Dans le cadre seulement : damier (montre la transparence du SVG/WebM). */
background-color: #fff;
background-image:
linear-gradient(45deg, #e6e6e6 25%, transparent 25%, transparent 75%, #e6e6e6 75%),
linear-gradient(45deg, #e6e6e6 25%, transparent 25%, transparent 75%, #e6e6e6 75%);
background-size: 20px 20px;
background-position: 0 0, 10px 10px;
/* Contour double (clair + sombre) : visible sur n'importe quel fond. */
outline: 2px dashed #111;
outline-offset: 0;
box-shadow: 0 0 0 2px #fff, 0 4px 18px rgba(0, 0, 0, 0.35);
}
#leshed-title-animation .lta__transport {
display: flex;
gap: 0.75rem;
align-items: center;
margin-top: 0.5rem;
}
#leshed-title-animation .lta__scrub { flex: 1; }
#leshed-title-animation .lta__time {
font-size: 0.8125rem;
font-variant-numeric: tabular-nums;
min-width: 8em;
text-align: right;
}
#leshed-title-animation .lta__info { margin: 0.35rem 0 0; font-size: 0.8125rem; opacity: 0.7; }
@@ -0,0 +1,440 @@
/**
* @file
* Page outil « Titre animé » (/admin/leshed/titre-anime) : saisie du texte,
* réglages, aperçu en boucle et exports SVG animé / MP4 / WebM / GIF.
*
* Chargé en module ES ; les moteurs (harfbuzzjs, mediabunny, gifenc) sont
* importés à la demande depuis les URL de drupalSettings.leshedTitleAnimation.
*/
import {
parseText, drawStates, loadFonts, buildTimeline, computeFit, renderFrame,
} from './title-animation/engine.js';
import { exportSvg, exportVideo, exportGif } from './title-animation/exporters.js';
const settings = (window.drupalSettings || {}).leshedTitleAnimation;
const root = document.getElementById('leshed-title-animation');
const PRESETS = {
square: { label: 'Carré 1080 × 1080', width: 1080, height: 1080 },
story: { label: 'Story 1080 × 1920', width: 1080, height: 1920 },
landscape: { label: 'Paysage 1920 × 1080', width: 1920, height: 1080 },
custom: { label: 'Taille libre', width: null, height: null },
};
const UI = `
<div class="lta">
<div class="lta__controls">
<fieldset class="lta__group">
<legend>Texte</legend>
<div class="form-item">
<label class="form-item__label" for="lta-text">Texte (un retour à la ligne = une ligne)</label>
<textarea id="lta-text" class="form-element form-textarea" rows="3"></textarea>
</div>
<div class="lta__row">
<div class="form-item">
<label class="form-item__label" for="lta-states">Tirages</label>
<input id="lta-states" class="form-element" type="number" min="2" max="12" step="1" value="4">
</div>
<button type="button" class="button" data-action="redraw">Nouveaux tirages</button>
</div>
</fieldset>
<fieldset class="lta__group">
<legend>Animation</legend>
<div class="form-item">
<label class="form-item__label" for="lta-mode">Mode</label>
<select id="lta-mode" class="form-element form-select">
<option value="loop">Boucle : toutes les lettres ensemble</option>
<option value="wave">Vague : de gauche à droite</option>
<option value="boil">Bouillonnement : chaque lettre à son rythme</option>
</select>
</div>
<div class="lta__row">
<div class="form-item" data-modes="loop wave">
<label class="form-item__label" for="lta-hold">Pause (s)</label>
<input id="lta-hold" class="form-element" type="number" min="0" max="10" step="0.1" value="0">
</div>
<div class="form-item">
<label class="form-item__label" for="lta-morph">Morphing (s)</label>
<input id="lta-morph" class="form-element" type="number" min="0.1" max="10" step="0.1" value="2">
</div>
<div class="form-item" data-modes="wave">
<label class="form-item__label" for="lta-stagger">Décalage (s)</label>
<input id="lta-stagger" class="form-element" type="number" min="0" max="10" step="0.1" value="0.8">
</div>
</div>
<div class="form-item">
<label class="form-item__label" for="lta-easing">Courbe</label>
<select id="lta-easing" class="form-element form-select">
<option value="ease-in-out">Douce (ease-in-out)</option>
<option value="sine">Sinus</option>
<option value="expo">Nerveuse (expo)</option>
<option value="linear">Linéaire</option>
</select>
</div>
</fieldset>
<fieldset class="lta__group">
<legend>Cadre</legend>
<div class="form-item">
<label class="form-item__label" for="lta-preset">Format</label>
<select id="lta-preset" class="form-element form-select"></select>
</div>
<div class="lta__row">
<div class="form-item">
<label class="form-item__label" for="lta-width">Largeur (px)</label>
<input id="lta-width" class="form-element" type="number" min="16" max="4096" step="2">
</div>
<div class="form-item">
<label class="form-item__label" for="lta-height">Hauteur (px)</label>
<input id="lta-height" class="form-element" type="number" min="16" max="4096" step="2">
</div>
</div>
<div class="lta__row">
<div class="form-item">
<label class="form-item__label" for="lta-margin">Marge (%)</label>
<input id="lta-margin" class="form-element" type="number" min="0" max="40" step="1" value="8">
</div>
<div class="form-item">
<label class="form-item__label" for="lta-align">Alignement</label>
<select id="lta-align" class="form-element form-select">
<option value="left">Gauche (comme le site)</option>
<option value="center">Centré</option>
<option value="right">Droite</option>
</select>
</div>
</div>
</fieldset>
<fieldset class="lta__group">
<legend>Export</legend>
<div class="lta__row">
<div class="form-item">
<label class="form-item__label" for="lta-fps">Vidéo : images/s</label>
<select id="lta-fps" class="form-element form-select">
<option>25</option><option selected>30</option><option>50</option><option>60</option>
</select>
</div>
<div class="form-item">
<label class="form-item__label" for="lta-loops">Vidéo : boucles</label>
<input id="lta-loops" class="form-element" type="number" min="1" max="20" step="1" value="2">
</div>
</div>
<div class="lta__row">
<div class="form-item">
<label class="form-item__label" for="lta-gif-fps">GIF : images/s</label>
<select id="lta-gif-fps" class="form-element form-select">
<option>10</option><option selected>20</option><option>25</option><option>50</option>
</select>
</div>
<div class="form-item">
<label class="form-item__label" for="lta-gif-scale">GIF : taille</label>
<select id="lta-gif-scale" class="form-element form-select">
<option value="1">100 %</option><option value="0.5" selected>50 %</option><option value="0.3333">33 %</option>
</select>
</div>
</div>
<div class="lta__buttons">
<button type="button" class="button button--primary" data-export="svg" title="Vectoriel, fond transparent">SVG animé</button>
<button type="button" class="button button--primary" data-export="mp4" title="H.264, fond blanc">MP4</button>
<button type="button" class="button button--primary" data-export="webm" title="VP9, fond transparent si le navigateur le permet">WebM</button>
<button type="button" class="button button--primary" data-export="gif" title="Fond blanc">GIF</button>
</div>
<progress class="lta__progress" max="1" value="0" hidden></progress>
<p class="lta__status" role="status"></p>
</fieldset>
</div>
<div class="lta__preview">
<div class="lta__stage"><canvas class="lta__canvas"></canvas></div>
<div class="lta__transport">
<button type="button" class="button button--small" data-action="play">Pause</button>
<input class="lta__scrub" type="range" min="0" max="1" step="0.001" value="0" aria-label="Position dans la boucle">
<span class="lta__time"></span>
</div>
<p class="lta__info"></p>
</div>
</div>`;
const $ = (sel) => root.querySelector(sel);
function slugify(text) {
return (text || '')
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 60) || 'leshed-titre';
}
function download(blob, filename) {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 2000);
}
/**
* Ajoute une tirette (curseur) à chaque champ numérique, synchronisée dans
* les deux sens. Le champ garde la saisie précise ; la tirette déclenche
* l'événement `change` du champ pendant le glissement (aperçu en direct).
*/
function addSliders(container) {
container.querySelectorAll('input[type="number"]').forEach((field) => {
const slider = document.createElement('input');
slider.type = 'range';
slider.className = 'lta__slider';
for (const attr of ['min', 'max', 'step']) slider.setAttribute(attr, field.getAttribute(attr));
slider.setAttribute('aria-label', field.labels[0] ? field.labels[0].textContent : field.id);
const wrap = document.createElement('div');
wrap.className = 'lta__range';
field.replaceWith(wrap);
wrap.append(slider, field);
const fromField = () => {
slider.value = field.value;
slider.disabled = field.disabled;
};
field.ltaSync = fromField;
slider.addEventListener('input', () => {
if (field.value === slider.value) return;
field.value = slider.value;
field.dispatchEvent(new Event('change'));
});
field.addEventListener('input', fromField);
field.addEventListener('change', fromField);
fromField();
});
}
function debounce(fn, ms) {
let id = null;
return (...args) => {
clearTimeout(id);
id = setTimeout(() => fn(...args), ms);
};
}
async function init() {
if (!root || !settings) return;
root.innerHTML = UI;
addSliders(root);
const presetSelect = $('#lta-preset');
for (const [key, p] of Object.entries(PRESETS)) {
presetSelect.add(new Option(p.label, key));
}
const params = new URLSearchParams(window.location.search);
$('#lta-text').value = params.get('texte') || 'le shed';
const status = $('.lta__status');
const setStatus = (msg, isError = false) => {
status.textContent = msg;
status.classList.toggle('lta__status--error', isError);
};
setStatus('Chargement de la police…');
let fonts;
try {
const hb = await import(settings.harfbuzzUrl);
fonts = await loadFonts(hb, settings.fonts);
}
catch (error) {
console.error('Le Shed titre animé :', error);
setStatus(`Impossible de charger le moteur typographique : ${error.message}`, true);
return;
}
setStatus('');
const canvas = $('.lta__canvas');
const ctx = canvas.getContext('2d');
const project = { fonts, model: null, states: [], timeline: null, frame: null, fit: null, align: 'left' };
const readNumber = (id, fallback, min, max) => {
const v = parseFloat($(id).value);
return Number.isFinite(v) ? Math.min(max, Math.max(min, v)) : fallback;
};
const even = (v) => Math.max(16, Math.round(v / 2) * 2);
function syncPresetInputs() {
const preset = PRESETS[presetSelect.value];
const custom = presetSelect.value === 'custom';
$('#lta-width').disabled = !custom;
$('#lta-height').disabled = !custom;
if (!custom) {
$('#lta-width').value = preset.width;
$('#lta-height').value = preset.height;
}
$('#lta-width').ltaSync();
$('#lta-height').ltaSync();
}
function syncModeFields() {
const mode = $('#lta-mode').value;
root.querySelectorAll('[data-modes]').forEach((el) => {
el.hidden = !el.dataset.modes.split(' ').includes(mode);
});
}
// Étapes de recalcul, de la plus coûteuse à la plus légère.
function rebuildText() {
project.model = parseText($('#lta-text').value);
redrawStates();
}
function redrawStates() {
const n = Math.round(readNumber('#lta-states', 4, 2, 12));
project.states = drawStates(project.model, n);
rebuildTimeline();
}
function rebuildTimeline() {
project.timeline = buildTimeline({
states: project.states,
mode: $('#lta-mode').value,
hold: readNumber('#lta-hold', 0, 0, 10),
morph: readNumber('#lta-morph', 2, 0.1, 10),
stagger: readNumber('#lta-stagger', 0.8, 0, 10),
easing: $('#lta-easing').value,
nChars: project.model.chars.length,
});
rebuildFrame();
}
function rebuildFrame() {
project.frame = {
width: even(readNumber('#lta-width', 1080, 16, 4096)),
height: even(readNumber('#lta-height', 1080, 16, 4096)),
margin: readNumber('#lta-margin', 8, 0, 40) / 100,
};
project.align = $('#lta-align').value;
canvas.width = project.frame.width;
canvas.height = project.frame.height;
if (project.model.chars.length) computeFit(project);
const tl = project.timeline;
$('.lta__info').textContent = project.model.chars.length
? `${project.states.length} tirages · boucle de ${tl.total.toFixed(2)} s · ${project.frame.width} × ${project.frame.height}`
+ (repairedCount() ? ` · ${repairedCount()} changement(s) de groupe hors règles du site (mots trop courts)` : '')
: 'Saisissez un texte.';
draw();
}
function repairedCount() {
return project.states.reduce((sum, st) => sum + st.filter((d) => d.repaired).length, 0);
}
// ─── Lecture ───
let playing = true;
let time = 0;
let last = null;
const scrub = $('.lta__scrub');
function draw() {
if (!project.model || !project.model.chars.length || !project.fit) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
return;
}
const T = project.timeline.total;
time %= T;
renderFrame(ctx, project, time, null);
scrub.value = String(time / T);
$('.lta__time').textContent = `${time.toFixed(2)} / ${T.toFixed(2)} s`;
}
function tick(now) {
if (playing && last !== null) time += (now - last) / 1000;
last = now;
if (playing) draw();
requestAnimationFrame(tick);
}
$('[data-action="play"]').addEventListener('click', (e) => {
playing = !playing;
e.currentTarget.textContent = playing ? 'Pause' : 'Lecture';
});
scrub.addEventListener('input', () => {
playing = false;
$('[data-action="play"]').textContent = 'Lecture';
if (project.timeline) time = parseFloat(scrub.value) * project.timeline.total;
draw();
});
// ─── Événements des réglages ───
const on = (sel, type, fn) => $(sel).addEventListener(type, fn);
on('#lta-text', 'input', debounce(rebuildText, 200));
on('#lta-states', 'change', redrawStates);
on('[data-action="redraw"]', 'click', redrawStates);
on('#lta-mode', 'change', () => {
syncModeFields();
rebuildTimeline();
});
['#lta-hold', '#lta-morph', '#lta-stagger'].forEach((s) => on(s, 'change', rebuildTimeline));
on('#lta-easing', 'change', rebuildTimeline);
on('#lta-preset', 'change', () => {
syncPresetInputs();
rebuildFrame();
});
['#lta-width', '#lta-height', '#lta-margin'].forEach((s) => on(s, 'change', rebuildFrame));
on('#lta-align', 'change', rebuildFrame);
// ─── Exports ───
const progress = $('.lta__progress');
const exportButtons = root.querySelectorAll('[data-export]');
async function runExport(format) {
if (!project.model.chars.length) return;
exportButtons.forEach((b) => { b.disabled = true; });
progress.hidden = false;
progress.value = 0;
setStatus(`Export ${format.toUpperCase()} en cours…`);
const onProgress = (v) => { progress.value = v; };
const base = `${slugify($('#lta-text').value)}-${project.timeline.mode}`;
try {
if (format === 'svg') {
const svg = exportSvg(project);
download(new Blob([svg], { type: 'image/svg+xml' }), `${base}.svg`);
setStatus(`SVG exporté (${Math.round(svg.length / 1024)} Ko).`);
}
else if (format === 'gif') {
const { blob } = await exportGif(project, {
fps: parseInt($('#lta-gif-fps').value, 10),
scale: parseFloat($('#lta-gif-scale').value),
gifencUrl: settings.gifencUrl,
onProgress,
});
download(blob, `${base}.gif`);
setStatus(`GIF exporté (${(blob.size / 1048576).toFixed(1)} Mo).`);
}
else {
const { blob, notes, codec } = await exportVideo(project, {
container: format,
fps: parseInt($('#lta-fps').value, 10),
loops: Math.round(readNumber('#lta-loops', 2, 1, 20)),
mediabunnyUrl: settings.mediabunnyUrl,
onProgress,
});
download(blob, `${base}.${format}`);
setStatus([`${format.toUpperCase()} exporté (${codec}, ${(blob.size / 1048576).toFixed(1)} Mo).`, ...notes].join(' '));
}
}
catch (error) {
console.error('Le Shed titre animé :', error);
setStatus(`Export impossible : ${error.message}`, true);
}
finally {
exportButtons.forEach((b) => { b.disabled = false; });
progress.hidden = true;
}
}
exportButtons.forEach((b) => b.addEventListener('click', () => runExport(b.dataset.export)));
syncPresetInputs();
syncModeFields();
rebuildText();
requestAnimationFrame(tick);
}
init();
@@ -7,6 +7,9 @@
* délibéré : titles.js n'est pas refactoré en module partagé, le générateur
* d'animation reproduit donc ses règles à l'identique. Toute modification
* des règles côté thème doit être reportée ici.
*
* Seul ajout propre au générateur : la contrainte de changement entre deux
* tirages successifs (drawWord(n, neighbors), plus bas).
*/
export const TITLE_STYLE = {
@@ -53,45 +56,63 @@ function spreadPositions(n, k, exclude = new Set()) {
return set;
}
/**
* Tirage d'un mot de `n` lettres : [{wght, ital}, ...].
* Même logique que styleWordChars() du thème, sans le DOM.
*/
export function drawWord(n) {
if (!n) return [];
const GROUPS = {
thin: { range: TITLE_STYLE.wghtThin, pItal: TITLE_STYLE.italicOnThin },
medium: { range: TITLE_STYLE.wghtMedium, pItal: TITLE_STYLE.italicOnMedium },
bold: { range: TITLE_STYLE.wghtBold, pItal: TITLE_STYLE.italicOnBold },
};
// ─── Spécifique au générateur d'animation (absent du site) ──────────────────
//
// Règle : d'un tirage au suivant (y compris du dernier au premier, qui ferme
// la boucle), CHAQUE lettre change visiblement — elle change de groupe de
// graisse (fine / medium / grasse) ou bascule romain ↔ italique. Une lettre
// qui reste dans son groupe et son style ne bougerait presque pas (ex. 125 →
// 150), d'où ce critère plutôt qu'un simple « valeur différente ».
//
// `neighbors` : tirages voisins du mot (le précédent, et le premier pour le
// dernier tirage), chacun [{group, ital}] aligné sur les lettres du mot.
const MAX_ATTEMPTS = 300;
const changes = (d, nb) => d.group !== nb.group || d.ital !== nb.ital;
/** Une tentative selon les règles du site, l'italique étant forcé là où le groupe ne change pas. */
function attemptWord(n, neighbors) {
// Positions des groupes : identique au site.
const bold = spreadPositions(n, Math.round(n * TITLE_STYLE.boldRatio));
const medium = spreadPositions(n, Math.round(n * TITLE_STYLE.mediumRatio), bold);
const decisions = [];
for (let i = 0; i < n; i++) {
let range;
let pItal;
if (bold.has(i)) {
range = TITLE_STYLE.wghtBold;
pItal = TITLE_STYLE.italicOnBold;
const group = bold.has(i) ? 'bold' : (medium.has(i) ? 'medium' : 'thin');
// Même groupe qu'un voisin → l'italique doit différer de ce voisin.
const allowed = new Set([true, false]);
for (const nb of neighbors) {
if (nb[i].group === group) allowed.delete(nb[i].ital);
}
else if (medium.has(i)) {
range = TITLE_STYLE.wghtMedium;
pItal = TITLE_STYLE.italicOnMedium;
}
else {
range = TITLE_STYLE.wghtThin;
pItal = TITLE_STYLE.italicOnThin;
}
decisions.push({ wght: randomWght(range), ital: Math.random() < pItal });
if (!allowed.size) return null;
const forced = allowed.size === 1;
const ital = forced ? [...allowed][0] : Math.random() < GROUPS[group].pItal;
decisions.push({ group, ital, forced });
}
// Au moins une italique par mot (site) — sur une lettre libre uniquement.
if (!decisions.some((d) => d.ital)) {
const accents = [...bold, ...medium];
const idx = accents.length ? accents[randomInt(0, accents.length)] : randomInt(0, n);
decisions[idx].ital = true;
const free = (set) => [...set].filter((i) => !decisions[i].forced);
let pool = free(new Set([...bold, ...medium]));
if (!pool.length) pool = free(new Set(decisions.keys()));
if (!pool.length) return null;
decisions[pool[randomInt(0, pool.length)]].ital = true;
}
// Pas plus de 2 italiques consécutives (site) — on ne casse qu'une lettre libre.
let run = 0;
for (const d of decisions) {
if (d.ital) {
run += 1;
if (run > 2) {
if (d.forced) return null;
d.ital = false;
run = 0;
}
@@ -102,3 +123,38 @@ export function drawWord(n) {
}
return decisions;
}
/**
* Tirage d'un mot de `n` lettres : [{wght, ital, group, repaired}, ...].
*
* Sans voisin : règles du site seules (= styleWordChars() du thème). Avec
* voisins : mêmes règles + changement obligatoire de chaque lettre. Si les
* règles du site rendent ce changement impossible (typiquement un mot d'une
* lettre : toujours fine et italique sur le site), on garde la dernière
* tentative et on fait changer de groupe les lettres en défaut
* (`repaired: true`) — l'écart aux proportions du site est alors assumé.
*/
export function drawWord(n, neighbors = []) {
if (!n) return [];
let decisions = null;
for (let a = 0; a < MAX_ATTEMPTS && !decisions; a++) {
decisions = attemptWord(n, neighbors);
}
if (!decisions) {
decisions = attemptWord(n, []);
decisions.forEach((d, i) => {
if (neighbors.every((nb) => changes(d, nb[i]))) return;
const options = Object.keys(GROUPS).filter((g) => neighbors.every((nb) => nb[i].group !== g));
d.group = options[randomInt(0, options.length)];
d.repaired = true;
});
}
return decisions.map((d) => ({
group: d.group,
ital: d.ital,
wght: randomWght(GROUPS[d.group].range),
repaired: !!d.repaired,
}));
}
@@ -0,0 +1,374 @@
/**
* @file
* Moteur du générateur d'animation de titres : texte → tirages → timeline →
* mise en page à l'instant t → rendu canvas.
*
* Unités : la mise en page est calculée en « em » (1 em = taille de police),
* puis convertie en pixels du cadre par `fit.s` (px par em). Les tracés de
* glyphes restent en unités de police (upem), mis à l'échelle au rendu.
*/
import { drawWord, SPACE_WGHT, LETTER_SPACING_EM } from './draw.js';
// ─── Texte ──────────────────────────────────────────────────────────────────
/**
* Découpe le texte saisi en lignes (retours à la ligne explicites), mots et
* lettres. Minuscules comme sur le site (`text-transform: lowercase`).
*
* @return {{lines: Array<Array<{type: 'char'|'space', ch: string, index?: number}>>,
* chars: string[], words: number[][]}}
*/
export function parseText(raw) {
const lines = [];
const chars = [];
const words = [];
const rawLines = (raw || '').toLocaleLowerCase('fr').split(/\r?\n/)
.map((l) => l.trim())
.filter((l) => l.length);
for (const rawLine of rawLines) {
const items = [];
const tokens = rawLine.split(/\s+/).filter(Boolean);
tokens.forEach((token, ti) => {
if (ti > 0) items.push({ type: 'space', ch: ' ' });
const word = [];
for (const ch of Array.from(token.normalize('NFC'))) {
const index = chars.length;
chars.push(ch);
word.push(index);
items.push({ type: 'char', ch, index });
}
words.push(word);
});
lines.push(items);
}
return { lines, chars, words };
}
/**
* Un tirage complet du texte : [{wght, ital (0|1), group, repaired}] indexé
* comme `model.chars`. `neighbors` : tirages complets dont chaque lettre doit
* se démarquer (voir drawWord()).
*/
export function drawState(model, neighbors = []) {
const state = new Array(model.chars.length);
for (const word of model.words) {
const nbs = neighbors.map((nb) => word.map((c) => ({ group: nb[c].group, ital: nb[c].ital === 1 })));
drawWord(word.length, nbs).forEach((d, i) => {
state[word[i]] = { wght: d.wght, ital: d.ital ? 1 : 0, group: d.group, repaired: d.repaired };
});
}
return state;
}
/**
* N tirages en boucle : chacun diffère, lettre par lettre, du précédent ; le
* dernier diffère aussi du premier (retour en début de boucle).
*/
export function drawStates(model, n) {
const states = [drawState(model)];
for (let i = 1; i < n; i++) {
const neighbors = [states[i - 1]];
if (i === n - 1) neighbors.push(states[0]);
states.push(drawState(model, neighbors));
}
return states;
}
// ─── Polices (HarfBuzz) ─────────────────────────────────────────────────────
/**
* Charge les deux fichiers variables (romain, italique) d'Epilogue.
*
* @return {Promise<{roman: object, italic: object}>}
*/
export async function loadFonts(hb, urls) {
const load = async (url) => {
const response = await fetch(url, { credentials: 'same-origin' });
if (!response.ok) throw new Error(`police introuvable (${url})`);
const face = new hb.Face(new hb.Blob(await response.arrayBuffer()));
const font = new hb.Font(face);
font.setScale(face.upem, face.upem);
return {
hb,
font,
upem: face.upem,
ascender: font.getMetricPositionWithFallback(hb.MetricsTag.HORIZONTAL_ASCENDER),
descender: font.getMetricPositionWithFallback(hb.MetricsTag.HORIZONTAL_DESCENDER),
cache: new Map(),
currentWght: null,
};
};
const [roman, italic] = await Promise.all([load(urls.roman), load(urls.italic)]);
return { roman, italic };
}
/**
* Tracé + avance d'un caractère à une graisse donnée (arrondie à l'entier :
* invisible à l'œil, et borne le cache à ~800 entrées par lettre et style).
*
* @return {{d: string, adv: number, path2d: Path2D|null}} unités de police.
*/
export function glyph(fontData, ch, wght) {
const w = Math.round(wght);
const key = `${ch}|${w}`;
let g = fontData.cache.get(key);
if (g) return g;
const { hb, font } = fontData;
if (fontData.currentWght !== w) {
font.setVariations([new hb.Variation('wght', w)]);
fontData.currentWght = w;
}
const buffer = new hb.Buffer();
buffer.addText(ch);
buffer.guessSegmentProperties();
hb.shape(font, buffer);
const infos = buffer.getGlyphInfos();
const positions = buffer.getGlyphPositions();
const d = infos.length ? font.glyphToPath(infos[0].codepoint) : '';
const adv = positions.reduce((sum, p) => sum + p.xAdvance, 0);
g = { d, adv, path2d: null };
fontData.cache.set(key, g);
return g;
}
function path2dOf(g) {
if (!g.path2d && g.d) g.path2d = new Path2D(g.d);
return g.path2d;
}
// ─── Timeline ───────────────────────────────────────────────────────────────
export const EASINGS = {
'ease-in-out': [0.42, 0, 0.58, 1],
sine: [0.37, 0, 0.63, 1],
expo: [0.87, 0, 0.13, 1],
linear: [0, 0, 1, 1],
};
/** cubic-bezier(x1, y1, x2, y2) → fonction p ∈ [0,1] → [0,1]. */
export function bezier([x1, y1, x2, y2]) {
if (x1 === y1 && x2 === y2) return (p) => p;
const cx = 3 * x1;
const bx = 3 * (x2 - x1) - cx;
const ax = 1 - cx - bx;
const cy = 3 * y1;
const by = 3 * (y2 - y1) - cy;
const ay = 1 - cy - by;
const sx = (u) => ((ax * u + bx) * u + cx) * u;
const sy = (u) => ((ay * u + by) * u + cy) * u;
const dsx = (u) => (3 * ax * u + 2 * bx) * u + cx;
return (p) => {
if (p <= 0) return 0;
if (p >= 1) return 1;
let u = p;
for (let i = 0; i < 8; i++) {
const err = sx(u) - p;
if (Math.abs(err) < 1e-6) break;
const slope = dsx(u);
if (Math.abs(slope) < 1e-6) break;
u -= err / slope;
}
// Repli par dichotomie si Newton est sorti de [0,1].
if (u < 0 || u > 1 || Math.abs(sx(u) - p) > 1e-4) {
let lo = 0;
let hi = 1;
u = p;
for (let i = 0; i < 30; i++) {
if (sx(u) < p) lo = u;
else hi = u;
u = (lo + hi) / 2;
}
}
return sy(u);
};
}
/**
* Construit la timeline d'une boucle parfaite à travers les N tirages.
*
* Chaque lettre suit la même partition (pause `hold`, puis morphing `morph`
* vers le tirage suivant, le dernier revenant au premier), décalée dans le
* temps de `offsets[c]` :
* - boucle : 0 pour toutes les lettres ;
* - vague : décalage croissant de gauche à droite, sur `stagger` secondes ;
* - bouillonnement : pas de pause, décalage aléatoire par lettre.
*/
export function buildTimeline({ states, mode, hold, morph, stagger, easing, nChars }) {
const effectiveHold = mode === 'boil' ? 0 : hold;
const segment = effectiveHold + morph;
const total = states.length * segment;
const offsets = new Array(nChars);
for (let c = 0; c < nChars; c++) {
if (mode === 'wave') offsets[c] = nChars > 1 ? (c / (nChars - 1)) * stagger : 0;
else if (mode === 'boil') offsets[c] = Math.random() * segment;
else offsets[c] = 0;
}
return {
states,
mode,
hold: effectiveHold,
morph,
segment,
total,
offsets,
easingName: easing,
ease: bezier(EASINGS[easing] || EASINGS['ease-in-out']),
};
}
/** Valeurs de la lettre `c` à l'instant global `t` : {wght, k (0 romain → 1 italique)}. */
export function evalChar(tl, c, t) {
const { states, hold, morph, segment, total } = tl;
let local = (t - tl.offsets[c]) % total;
if (local < 0) local += total;
const s = Math.min(states.length - 1, Math.floor(local / segment));
const u = local - s * segment;
const p = u < hold ? 0 : tl.ease(Math.min(1, (u - hold) / morph));
const a = states[s][c];
const b = states[(s + 1) % states.length][c];
return {
wght: a.wght + (b.wght - a.wght) * p,
k: a.ital + (b.ital - a.ital) * p,
};
}
// ─── Mise en page ───────────────────────────────────────────────────────────
/**
* Positions (em) de toutes les lettres à l'instant t, lignes alignées dans
* un bloc de largeur `blockW` (em). Le texte « respire » : chaque lettre
* prend son avance réelle à sa graisse/son style du moment.
*/
export function layoutAt(project, t, blockW = null) {
const { model, fonts, timeline } = project;
const upemR = fonts.roman.upem;
const upemI = fonts.italic.upem;
const lineMetrics = lineBox(fonts);
const out = [];
const lineWidths = [];
model.lines.forEach((items, li) => {
const placed = [];
let x = 0;
items.forEach((item, ii) => {
if (item.type === 'space') {
x += glyph(fonts.roman, ' ', SPACE_WGHT).adv / upemR;
return;
}
const { wght, k } = evalChar(timeline, item.index, t);
const gr = glyph(fonts.roman, item.ch, wght);
const gi = glyph(fonts.italic, item.ch, wght);
placed.push({ index: item.index, ch: item.ch, x, wght, k, gr, gi });
const adv = (1 - k) * (gr.adv / upemR) + k * (gi.adv / upemI);
// letter-spacing après chaque lettre ; la dernière de la ligne n'en
// tient pas compte pour la largeur (sinon l'encre déborde du bloc).
x += adv + (ii < items.length - 1 ? LETTER_SPACING_EM : 0);
});
lineWidths.push(x);
const baseline = li * lineMetrics.lineHeight + lineMetrics.baselineInLine;
placed.forEach((p) => {
p.lineWidth = x;
p.line = li;
p.y = baseline;
});
out.push(...placed);
});
if (blockW !== null) {
for (const p of out) {
if (project.align === 'center') p.x += (blockW - p.lineWidth) / 2;
else if (project.align === 'right') p.x += blockW - p.lineWidth;
}
}
return { glyphs: out, lineWidths };
}
/** Interligne 1 (comme `.variable-title { line-height: 1 }`) : ligne de base dans la boîte. */
function lineBox(fonts) {
const { ascender, descender, upem } = fonts.roman;
const asc = ascender / upem;
const desc = Math.abs(descender) / upem;
const lineHeight = 1;
const halfLeading = (lineHeight - (asc + desc)) / 2;
return { lineHeight, baselineInLine: halfLeading + asc };
}
/**
* Taille du texte dans le cadre : le bloc (largeur maximale atteinte sur
* toute la boucle × nombre de lignes) est ajusté dans le cadre moins les
* marges, puis centré. Fixe pour toute l'animation : le texte respire sans
* que la taille ne pompe.
*/
export function computeFit(project, samples = 120) {
const { timeline, frame, model } = project;
let blockW = 0;
for (let i = 0; i < samples; i++) {
const t = (i / samples) * timeline.total;
for (const w of layoutAt(project, t).lineWidths) blockW = Math.max(blockW, w);
}
// Les tirages eux-mêmes (instants de pause) sont des extrêmes probables.
blockW = Math.max(blockW, 0.01);
const blockH = Math.max(1, model.lines.length) * lineBox(project.fonts).lineHeight;
const margin = frame.margin * Math.min(frame.width, frame.height);
const s = Math.min(
(frame.width - 2 * margin) / blockW,
(frame.height - 2 * margin) / blockH,
);
project.fit = {
s,
blockW,
blockH,
ox: (frame.width - blockW * s) / 2,
oy: (frame.height - blockH * s) / 2,
};
return project.fit;
}
// ─── Rendu canvas ───────────────────────────────────────────────────────────
/**
* Dessine l'image de l'instant t. `background` : couleur CSS, ou null pour
* un fond transparent. Texte noir uniquement (comme l'export SVG/PNG).
*/
export function renderFrame(ctx, project, t, background = null) {
const { frame, fit, fonts } = project;
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.globalAlpha = 1;
if (background) {
ctx.fillStyle = background;
ctx.fillRect(0, 0, frame.width, frame.height);
}
else {
ctx.clearRect(0, 0, frame.width, frame.height);
}
ctx.fillStyle = '#000';
const { glyphs } = layoutAt(project, t, fit.blockW);
const fr = fit.s / fonts.roman.upem;
const fi = fit.s / fonts.italic.upem;
for (const g of glyphs) {
const x = fit.ox + g.x * fit.s;
const y = fit.oy + g.y * fit.s;
if (g.k < 0.999) {
const p = path2dOf(g.gr);
if (p) {
ctx.globalAlpha = 1 - g.k;
ctx.setTransform(fr, 0, 0, -fr, x, y);
ctx.fill(p);
}
}
if (g.k > 0.001) {
const p = path2dOf(g.gi);
if (p) {
ctx.globalAlpha = g.k;
ctx.setTransform(fi, 0, 0, -fi, x, y);
ctx.fill(p);
}
}
}
ctx.globalAlpha = 1;
ctx.setTransform(1, 0, 0, 1, 0, 0);
}
@@ -0,0 +1,256 @@
/**
* @file
* Exports de l'animation : SVG animé (SMIL), vidéo MP4/WebM (WebCodecs via
* mediabunny), GIF (gifenc). Encodeurs installés via Composer
* (npm-asset/mediabunny, npm-asset/gifenc → web/libraries/), chargés à la
* demande depuis les URL fournies par drupalSettings.
*/
import { glyph, layoutAt, renderFrame, evalChar, EASINGS } from './engine.js';
const nextTick = () => new Promise((resolve) => setTimeout(resolve, 0));
const num = (v, digits = 2) => Number(v.toFixed(digits)).toString();
// ─── SVG animé ──────────────────────────────────────────────────────────────
// Cadence d'échantillonnage des positions des lettres (le texte respire : la
// position d'une lettre dépend des avances de toutes celles qui la précèdent,
// donc n'est pas une simple interpolation entre tirages).
const SVG_POSITION_FPS = 25;
// Cadence de repli pour une lettre dont les tracés ne sont pas interpolables.
const SVG_FALLBACK_FPS = 25;
const commandSignature = (d) => d.replace(/[^A-Za-z]/g, '');
/**
* Images clés (en temps local de la lettre) : début de pause, début de
* morphing, …, fin de boucle — avec la courbe d'easing de chaque intervalle.
*/
function charKeyframes(tl, c) {
const keys = [];
const splines = [];
const easeSpline = (EASINGS[tl.easingName] || EASINGS['ease-in-out']).join(' ');
tl.states.forEach((state, s) => {
const start = s * tl.segment;
keys.push({ t: start, ...state[c] });
if (tl.hold > 0) {
keys.push({ t: start + tl.hold, ...state[c] });
splines.push('0 0 1 1');
}
splines.push(easeSpline);
});
keys.push({ t: tl.total, ...tl.states[0][c] });
return { keys, splines };
}
function animate(attr, values, keyTimes, splines, dur, begin) {
const timing = splines
? `calcMode="spline" keyTimes="${keyTimes}" keySplines="${splines}"`
: `calcMode="discrete" keyTimes="${keyTimes}"`;
return `<animate attributeName="${attr}" values="${values}" ${timing} dur="${dur}s" begin="${begin}s" repeatCount="indefinite"/>`;
}
/**
* SVG autonome, fond transparent, texte noir, boucle infinie. Le morphing
* de graisse interpole directement les tracés (`d`) : les contours d'une
* police variable ont la même structure à toutes les graisses. L'italique
* (fichier séparé) passe en fondu enchaîné par l'opacité.
*/
export function exportSvg(project) {
const { frame, fit, fonts, timeline: tl, model } = project;
const T = tl.total;
const dur = num(T, 4);
// Positions échantillonnées (temps global), une liste par lettre.
const nPos = Math.max(2, Math.round(T * SVG_POSITION_FPS));
const positions = new Map();
for (let i = 0; i <= nPos; i++) {
const t = (i / nPos) * T;
for (const g of layoutAt(project, t, fit.blockW).glyphs) {
if (!positions.has(g.index)) positions.set(g.index, []);
positions.get(g.index).push(`${num(fit.ox + g.x * fit.s)} ${num(fit.oy + g.y * fit.s)}`);
}
}
const parts = [];
model.chars.forEach((ch, c) => {
const pos = positions.get(c);
if (!pos) return;
// Décalage de la lettre (vague / bouillonnement) : begin négatif.
const begin = num(-((T - tl.offsets[c]) % T), 4);
const { keys, splines } = charKeyframes(tl, c);
const keyTimes = keys.map((k) => num(k.t / T, 6)).join(';');
const layers = [];
for (const style of ['roman', 'italic']) {
const fontData = fonts[style];
const opacityOf = (ital) => (style === 'roman' ? 1 - ital : ital);
if (!keys.some((k) => opacityOf(k.ital) > 0)) continue;
const ds = keys.map((k) => glyph(fontData, ch, k.wght).d);
if (!ds[0]) continue;
const fs = num(fit.s / fontData.upem, 6);
const opacities = keys.map((k) => opacityOf(k.ital));
const opacity0 = opacityOf(evalChar(tl, c, 0).k);
const d0 = glyph(fontData, ch, evalChar(tl, c, 0).wght).d;
let anims;
if (ds.every((d) => commandSignature(d) === commandSignature(ds[0]))) {
anims = animate('d', ds.join(';'), keyTimes, splines.join(';'), dur, begin)
+ (opacities.every((o) => o === opacities[0]) ? ''
: animate('opacity', opacities.join(';'), keyTimes, splines.join(';'), dur, begin));
}
else {
// Tracés non interpolables : échantillonnage discret.
const n = Math.max(2, Math.round(T * SVG_FALLBACK_FPS));
const sampleD = [];
const sampleO = [];
const times = [];
for (let i = 0; i < n; i++) {
const v = evalChar(tl, c, (i / n) * T + tl.offsets[c]);
sampleD.push(glyph(fontData, ch, v.wght).d);
sampleO.push(num(opacityOf(v.k), 3));
times.push(num(i / n, 6));
}
anims = animate('d', sampleD.join(';'), times.join(';'), null, dur, begin)
+ animate('opacity', sampleO.join(';'), times.join(';'), null, dur, begin);
}
layers.push(`<path transform="scale(${fs} -${fs})" opacity="${num(opacity0, 3)}" d="${d0}">${anims}</path>`);
}
if (!layers.length) return;
parts.push(
`<g transform="translate(${pos[0]})">`
+ `<animateTransform attributeName="transform" type="translate" values="${pos.join(';')}" calcMode="linear" dur="${dur}s" repeatCount="indefinite"/>`
+ layers.join('')
+ '</g>',
);
});
return [
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${frame.width} ${frame.height}" width="${frame.width}" height="${frame.height}">`,
'<g fill="#000000">',
...parts,
'</g>',
'</svg>',
].join('\n');
}
// ─── Vidéo (MP4 / WebM) ─────────────────────────────────────────────────────
/**
* Encode image par image (pas en temps réel) : rendu exact à la cadence
* demandée, quelle que soit la vitesse de la machine.
*
* MP4 : H.264, fond blanc (pas de transparence possible).
* WebM : VP9 avec couche alpha si le navigateur sait l'encoder, sinon fond
* blanc (signalé dans `notes`).
*/
export async function exportVideo(project, { container, fps, loops, mediabunnyUrl, onProgress }) {
const mb = await import(mediabunnyUrl);
const { width, height } = project.frame;
if (width % 2 || height % 2) throw new Error('largeur et hauteur doivent être paires pour la vidéo.');
const notes = [];
let codec = null;
let alpha = false;
const can = (c, extra = {}) => mb.canEncodeVideo(c, { width, height, frameRate: fps, ...extra });
if (container === 'webm') {
if (await can('vp9', { alpha: 'keep' })) {
codec = 'vp9';
alpha = true;
}
else if (await can('vp9')) codec = 'vp9';
else if (await can('vp8')) codec = 'vp8';
if (codec && !alpha) notes.push('Ce navigateur ne sait pas encoder la transparence en WebM : fond blanc.');
}
else {
if (await can('avc')) codec = 'avc';
else if (await can('hevc')) codec = 'hevc';
}
if (!codec) {
throw new Error(`ce navigateur ne sait pas encoder de vidéo ${container.toUpperCase()} (WebCodecs).`
+ (container === 'mp4' ? ' Essayez la WebM, ou Chromium.' : ''));
}
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d', { alpha });
const output = new mb.Output({
format: container === 'webm' ? new mb.WebMOutputFormat() : new mb.Mp4OutputFormat({ fastStart: 'in-memory' }),
target: new mb.BufferTarget(),
});
const source = new mb.CanvasSource(canvas, {
codec,
quality: mb.QUALITY_HIGH,
alpha: alpha ? 'keep' : 'discard',
});
output.addVideoTrack(source, { frameRate: fps });
await output.start();
const T = project.timeline.total;
const perLoop = Math.max(1, Math.round(T * fps));
const frames = perLoop * loops;
for (let i = 0; i < frames; i++) {
const t = ((i % perLoop) / perLoop) * T;
renderFrame(ctx, project, t, alpha ? null : '#ffffff');
await source.add(i / fps, 1 / fps);
if (onProgress && i % 5 === 0) {
onProgress(i / frames);
await nextTick();
}
}
await output.finalize();
onProgress && onProgress(1);
const mime = container === 'webm' ? 'video/webm' : 'video/mp4';
return { blob: new Blob([output.target.buffer], { type: mime }), notes, codec };
}
// ─── GIF ────────────────────────────────────────────────────────────────────
/**
* GIF en niveaux de gris sur fond blanc : le rendu (noir sur blanc,
* antialiasé) ne contient que des gris, donc une palette fixe de 256 gris
* le restitue sans quantification ni tramage.
*/
export async function exportGif(project, { fps, scale, gifencUrl, onProgress }) {
const { GIFEncoder } = await import(gifencUrl);
const width = Math.max(2, Math.round(project.frame.width * scale));
const height = Math.max(2, Math.round(project.frame.height * scale));
const k = width / project.frame.width;
const scaled = {
...project,
frame: { ...project.frame, width, height },
fit: { ...project.fit, s: project.fit.s * k, ox: project.fit.ox * k, oy: project.fit.oy * k },
};
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
const palette = Array.from({ length: 256 }, (_, i) => [i, i, i]);
const gif = GIFEncoder();
const T = project.timeline.total;
const frames = Math.max(1, Math.round(T * fps));
const delay = Math.round(1000 / fps);
const index = new Uint8Array(width * height);
for (let i = 0; i < frames; i++) {
renderFrame(ctx, scaled, (i / frames) * T, '#ffffff');
const { data } = ctx.getImageData(0, 0, width, height);
for (let p = 0, q = 0; p < index.length; p++, q += 4) index[p] = data[q];
gif.writeFrame(index, width, height, i === 0 ? { palette, delay, repeat: 0 } : { delay });
if (onProgress && i % 3 === 0) {
onProgress(i / frames);
await nextTick();
}
}
gif.finish();
onProgress && onProgress(1);
return { blob: new Blob([gif.bytes()], { type: 'image/gif' }) };
}
@@ -7,3 +7,13 @@ svg-export:
dependencies:
- core/once
- core/drupalSettings
title-animation:
js:
# Module ES (imports relatifs vers js/title-animation/) : hors agrégation.
js/title-animation.js: { attributes: { type: module }, preprocess: false }
css:
theme:
css/title-animation.css: {}
dependencies:
- core/drupalSettings
@@ -0,0 +1,5 @@
leshed_svg_export.title_animation:
title: 'Titre animé'
description: 'Générer une animation (SVG, MP4, WebM, GIF) des titres Le Shed : morphing entre plusieurs tirages de graisses et d''italiques.'
route_name: leshed_svg_export.title_animation
parent: system.admin_config_media
@@ -0,0 +1,9 @@
leshed_svg_export.title_animation:
path: '/admin/leshed/titre-anime'
defaults:
_controller: '\Drupal\leshed_svg_export\Controller\TitleAnimationController::page'
_title: 'Titre animé'
requirements:
_permission: 'export leshed typography'
options:
_admin_route: TRUE
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace Drupal\leshed_svg_export\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Extension\ExtensionPathResolver;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Page outil : générateur d'animation de titres (morphing entre tirages).
*
* Tout le travail se fait côté client (js/title-animation.js) ; cette page
* ne fournit que le conteneur et les URL des moteurs et de la police.
*/
final class TitleAnimationController extends ControllerBase {
/**
* Thème dont la police Epilogue est utilisée.
*/
private const FONT_THEME = 'leshed';
public function __construct(
private readonly ExtensionPathResolver $pathResolver,
) {}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container): static {
return new static($container->get('extension.path.resolver'));
}
/**
* Rend la page outil.
*/
public function page(): array {
$base = base_path();
$fonts = $base . $this->pathResolver->getPath('theme', self::FONT_THEME) . '/assets/dist/fonts/';
return [
'#type' => 'container',
'#attributes' => ['id' => 'leshed-title-animation'],
'noscript' => [
'#markup' => '<p>' . $this->t('Cet outil nécessite JavaScript.') . '</p>',
],
'#attached' => [
'library' => ['leshed_svg_export/title-animation'],
'drupalSettings' => [
'leshedTitleAnimation' => [
// Moteurs installés via Composer (npm-asset/*, voir composer.json).
'harfbuzzUrl' => $base . 'libraries/harfbuzzjs/dist/index.mjs',
'mediabunnyUrl' => $base . 'libraries/mediabunny/dist/bundles/mediabunny.min.mjs',
'gifencUrl' => $base . 'libraries/gifenc/dist/gifenc.esm.js',
'fonts' => [
'roman' => $fonts . 'Epilogue-VariableFont_wght.ttf',
'italic' => $fonts . 'Epilogue-Italic-VariableFont_wght.ttf',
],
],
],
],
];
}
}