Audit complet de mise en forme — Image (2e élément du tableau)

Implémente toutes les options manquantes identifiées pour l'élément
Image : dimensionnement/ratio/object-fit, filtres CSS, upload de
fichier (en plus de l'URL), lien/plein écran au clic, chargement
différé, légende, et tous les attributs de boîte partagés déjà créés
pour Titre/Paragraphe (padding/margin/fond/bordure/ombre/opacité/
position du bloc).

Système de pages : un support peut désormais avoir 0 page (un nouveau
support démarre vide), suppression de toutes les pages en un clic, et
la pagination automatique insère intelligemment la nouvelle page juste
après celle qui déborde plutôt qu'en toute fin de liste.

Bugs réels trouvés et corrigés en cours de route : le style de bloc
(dont align-self) ciblait l'élément interne au lieu de son enveloppe
(légende/lien) ; une image à sa taille native pouvait déclencher une
pagination infinie ; upload/mise à jour d'attribut ne déclenchaient
jamais le contrôle de débordement.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
william
2026-09-26 12:06:44 +02:00
co-authored by Claude Sonnet 5
parent 6c7675fad0
commit 9ad50c58b8
27 changed files with 1299 additions and 174 deletions
+45 -48
View File
@@ -27,6 +27,8 @@ BOX_DEFAULTS = {
"background_color": "",
"border_radius": "",
"align_self": "stretch",
"width": "",
"max_width": "",
"height": "",
"min_height": "",
"max_height": "",
@@ -36,58 +38,39 @@ BOX_DEFAULTS = {
}
def render_box_style(a: dict[str, Any]) -> str:
"""Construit les déclarations CSS inline communes à plusieurs kinds à
partir des attributs `padding`/`margin`/`background_color`/
`border_radius`/`height`/`min_height`/`max_height`/`min_width`/
`box_shadow`/`opacity`/`border`/`align_self` de `a` — chaîne vide pour
tout attribut absent ou à sa valeur par défaut (aucun style ajouté,
comportement historique inchangé). `border` est un dict à 4 clés
(`BORDER_SIDES`), chacune `{"style", "width", "color"}` — un côté à
`style="none"` (ou absent) ne produit aucune déclaration pour ce
côté, jamais un `border-top:none` explicite.
- **Retour** : les déclarations CSS (`"propriete:valeur; ..."`),
jamais vide ni `None`.
- **Exceptions** : aucune."""
parts: list[str] = []
# (clé d'attribut, propriété CSS) — chaque paire suit exactement le même
# patron (lire/nettoyer/ajouter si non vide) ; une simple table de
# correspondance ici évite un enchaînement de blocs `if` identiques
# (complexité cognitive réduite, voir _render_simple_properties).
_SIMPLE_PROPERTIES = (
("padding", "padding"),
("margin", "margin"),
("background_color", "background-color"),
("border_radius", "border-radius"),
("width", "width"),
("max_width", "max-width"),
("height", "height"),
("min_height", "min-height"),
("max_height", "max-height"),
("min_width", "min-width"),
("box_shadow", "box-shadow"),
("opacity", "opacity"),
)
padding = str(a.get("padding", "")).strip()
if padding:
parts.append(f"padding:{html_lib.escape(padding)};")
margin = str(a.get("margin", "")).strip()
if margin:
parts.append(f"margin:{html_lib.escape(margin)};")
def _render_simple_properties(a: dict[str, Any]) -> list[str]:
parts = []
for attr_key, css_prop in _SIMPLE_PROPERTIES:
value = str(a.get(attr_key, "")).strip()
if value:
parts.append(f"{css_prop}:{html_lib.escape(value)};")
return parts
background_color = str(a.get("background_color", "")).strip()
if background_color:
parts.append(f"background-color:{html_lib.escape(background_color)};")
border_radius = str(a.get("border_radius", "")).strip()
if border_radius:
parts.append(f"border-radius:{html_lib.escape(border_radius)};")
height = str(a.get("height", "")).strip()
if height:
parts.append(f"height:{html_lib.escape(height)};")
min_height = str(a.get("min_height", "")).strip()
if min_height:
parts.append(f"min-height:{html_lib.escape(min_height)};")
max_height = str(a.get("max_height", "")).strip()
if max_height:
parts.append(f"max-height:{html_lib.escape(max_height)};")
min_width = str(a.get("min_width", "")).strip()
if min_width:
parts.append(f"min-width:{html_lib.escape(min_width)};")
box_shadow = str(a.get("box_shadow", "")).strip()
if box_shadow:
parts.append(f"box-shadow:{html_lib.escape(box_shadow)};")
opacity = str(a.get("opacity", "")).strip()
if opacity:
parts.append(f"opacity:{html_lib.escape(opacity)};")
def _render_border(a: dict[str, Any]) -> list[str]:
"""Un côté à `style="none"` (ou absent) ne produit aucune déclaration
pour ce côté, jamais un `border-top:none` explicite."""
parts = []
border = a.get("border") or {}
for side in BORDER_SIDES:
side_border = border.get(side) or {}
@@ -96,6 +79,20 @@ def render_box_style(a: dict[str, Any]) -> str:
width = html_lib.escape(str(side_border.get("width", "1px")))
color = html_lib.escape(str(side_border.get("color", "var(--doc-border)")))
parts.append(f"border-{side}:{width} {html_lib.escape(style)} {color};")
return parts
def render_box_style(a: dict[str, Any]) -> str:
"""Construit les déclarations CSS inline communes à plusieurs kinds à
partir des attributs listés dans `_SIMPLE_PROPERTIES` + `border`/
`align_self` de `a` — chaîne vide pour tout attribut absent ou à sa
valeur par défaut (aucun style ajouté, comportement historique
inchangé). `border` est un dict à 4 clés (`BORDER_SIDES`), chacune
`{"style", "width", "color"}`.
- **Retour** : les déclarations CSS (`"propriete:valeur; ..."`),
jamais vide ni `None`.
- **Exceptions** : aucune."""
parts = _render_simple_properties(a) + _render_border(a)
# align-self ne fait quoi que ce soit d'utile QUE si l'élément a par
# ailleurs une taille bornée (max_width/width) — voir la note dans
@@ -94,15 +94,11 @@ def _render_text(el: dict[str, Any], _children_by_parent: dict[int | None, list[
if text_shadow:
style += f" text-shadow:{html_lib.escape(text_shadow)};"
# max_width optionnel (ex. "60ch", "480px") — vide par défaut (pleine
# largeur de .docPageContent, comportement inchangé). Retour
# utilisateur du 24/09/2026 : un paragraphe doit pouvoir rester plus
# étroit que la page, comme un sous-titre sous un grand titre, sans
# dépendre d'une rangée (qui partagerait la largeur avec un frère).
max_width = str(a.get("max_width", "")).strip()
if max_width:
style += f" max-width:{html_lib.escape(max_width)};"
# max_width (ex. "60ch", "480px" — retour utilisateur du 24/09/2026 :
# un paragraphe doit pouvoir rester plus étroit que la page, sans
# dépendre d'une rangée qui en partagerait la largeur avec un frère)
# fait maintenant partie des attributs de boîte partagés
# (render_box_style), jamais géré ici en double.
box_style = render_box_style(a)
if box_style:
style += f" {box_style}"
@@ -110,8 +106,53 @@ def _render_text(el: dict[str, Any], _children_by_parent: dict[int | None, list[
return f'<div class="docText" data-element-id="{el["id"]}" data-kind="{el["kind"]}" style="{style}">{content}</div>'
_IMAGE_OBJECT_FITS = ("cover", "contain", "fill")
_IMAGE_FILTERS = {
"grayscale": "grayscale(1)",
"sepia": "sepia(0.8)",
"blur": "blur(3px)",
}
def _image_extra_style(a: dict[str, Any]) -> str:
"""Déclarations CSS spécifiques à l'image (`object-fit`/`aspect-ratio`/
`filter`) — jamais dans `box_style.py` (partagé), qui ne connaît que
des attributs communs à plusieurs kinds."""
parts = []
object_fit = str(a.get("object_fit", ""))
if object_fit in _IMAGE_OBJECT_FITS:
parts.append(f"object-fit:{object_fit};")
aspect_ratio = str(a.get("aspect_ratio", "")).strip()
if aspect_ratio:
parts.append(f"aspect-ratio:{html_lib.escape(aspect_ratio)};")
filter_value = _IMAGE_FILTERS.get(str(a.get("filter_preset", "")))
if filter_value:
parts.append(f"filter:{filter_value};")
return " ".join(parts)
def _render_image(el: dict[str, Any], _children_by_parent: dict[int | None, list[dict[str, Any]]]) -> str:
a = el["attributes"]
click_behavior = str(a.get("click_behavior", ""))
link_url = str(a.get("link_url", "")).strip()
caption = str(a.get("caption", "")).strip()
# render_box_style (padding/margin/fond/bordure/largeur/position du
# bloc, dont align-self) doit se poser sur l'élément RÉELLEMENT
# top-niveau — celui qui est l'enfant direct du flex-column de la
# page (voir .docPageContent, static/document/document-editor.css) —
# jamais sur l'<img>/<div> interne dès qu'une légende ou un
# comportement au clic l'enveloppe : un align-self posé sur un
# DESCENDANT du flex-item n'a strictement aucun effet côté CSS (bug
# réel constaté le 26/09/2026 : "la position de bloc ne fonctionne
# pas sur l'image"). has_wrapper détermine qui, de l'image elle-même
# ou de son enveloppe, est ce top-niveau.
has_wrapper = bool(caption) or (click_behavior == "link" and link_url) or click_behavior == "lightbox"
box_style = render_box_style(a)
media_style = " ".join(p for p in (_image_extra_style(a), "" if has_wrapper else box_style) if p)
media_style_attr = f' style="{media_style}"' if media_style else ""
loading_attr = ' loading="lazy"' if a.get("lazy_load") else ""
svg_markup = str(a.get("svg_markup", "")).strip()
if svg_markup:
# Contenu vectoriel dessiné/collé par le créateur plutôt qu'un
@@ -120,15 +161,51 @@ def _render_image(el: dict[str, Any], _children_by_parent: dict[int | None, list
# CHAQUE rendu (jamais seulement à l'écriture) par sanitize_svg_markup,
# même défense en profondeur que html.escape sur les autres kinds.
sanitized = sanitize_svg_markup(svg_markup)
return f'<div class="docImage" data-element-id="{el["id"]}" data-kind="image">{sanitized}</div>'
src = html_lib.escape(str(a.get("src", "")))
alt = html_lib.escape(str(a.get("alt", "")))
if not src:
return (
f'<div class="docImage docImagePlaceholder" data-element-id="{el["id"]}" data-kind="image">'
f"Image — aucun fichier choisi</div>"
media = (
f'<div class="docImage" data-element-id="{el["id"]}" data-kind="image"{media_style_attr}>{sanitized}</div>'
)
return f'<img class="docImage" data-element-id="{el["id"]}" data-kind="image" src="{src}" alt="{alt}">'
else:
src = html_lib.escape(str(a.get("src", "")))
alt = html_lib.escape(str(a.get("alt", "")))
if not src:
media = (
f'<div class="docImage docImagePlaceholder" data-element-id="{el["id"]}" '
f'data-kind="image"{media_style_attr}>Image — aucun fichier choisi</div>'
)
else:
media = (
f'<img class="docImage" data-element-id="{el["id"]}" data-kind="image" '
f'src="{src}" alt="{alt}"{media_style_attr}{loading_attr}>'
)
# Comportement au clic (mutuellement exclusif, voir panneau
# Propriétés) — "lien" ouvre une URL externe dans un nouvel onglet
# (jamais dans l'éditeur lui-même), "plein écran" ouvre un aperçu
# agrandi géré côté client (voir static/document/js/
# document-editor.js::forgeDocOpenImageLightbox), tous deux
# UNIQUEMENT actifs en Mode Aperçu (même principe que les mini-jeux
# et la pièce jointe d'un bouton). Reçoit le style de bloc UNIQUEMENT
# s'il n'y a pas de légende par-dessus (sinon c'est elle, plus
# englobante encore, qui le reçoit juste plus bas).
if click_behavior == "link" and link_url:
href = html_lib.escape(link_url)
wrapper_style_attr = f' style="{box_style}"' if (box_style and not caption) else ""
media = (
f'<a class="docImageLink" href="{href}" target="_blank" '
f'rel="noopener noreferrer"{wrapper_style_attr}>{media}</a>'
)
elif click_behavior == "lightbox":
wrapper_style_attr = f' style="{box_style}"' if (box_style and not caption) else ""
media = f'<div class="docImageLightboxTrigger"{wrapper_style_attr}>{media}</div>'
if caption:
figure_style_attr = f' style="{box_style}"' if box_style else ""
media = (
f'<figure class="docImageFigure"{figure_style_attr}>{media}'
f'<figcaption class="docImageCaption">{html_lib.escape(caption)}</figcaption></figure>'
)
return media
def _render_list(el: dict[str, Any], _children_by_parent: dict[int | None, list[dict[str, Any]]]) -> str:
+29 -10
View File
@@ -52,7 +52,21 @@ regroupement à chaque appel.
`<div>` portant directement ce fragment SVG nettoyé par
`sanitize_svg_markup` (voir `sanitize_svg_markup.py` ci-dessous) : un
contenu vectoriel dessiné/collé par le créateur plutôt qu'un fichier
hébergé, sans aucun style qui lui soit propre.
hébergé. Style inline : `object_fit` (`"cover"`/`"contain"`/`"fill"`,
toute autre valeur ignorée), `aspect_ratio` (valeur CSS libre, ex.
`"16 / 9"`), `filter_preset` (`"grayscale"`/`"sepia"`/`"blur"`, mappé
vers une vraie valeur `filter` CSS fixe — jamais une valeur de filtre
libre) + les attributs de boîte partagés (`render_box_style`, voir
`box_style.py`). `lazy_load` (`True`) ajoute `loading="lazy"` sur
l'`<img>` uniquement (comportement, pas du style). `click_behavior`
(`""`/`"link"`/`"lightbox"`) enveloppe le tout dans un `<a target="_blank"
rel="noopener noreferrer">` (si `link_url` est aussi renseigné) ou un
`<div class="docImageLightboxTrigger">` — les deux ne deviennent
réellement cliquables qu'en Mode Aperçu (voir static/document/js/
document-editor.js::forgeDocBindCanvasInteractions/
forgeDocOpenImageLightbox), même principe que les mini-jeux et la
pièce jointe d'un bouton. `caption` (non vide) enveloppe le tout dans
un `<figure><figcaption>` échappée.
- **Bouton** : `<button>` avec son `label`, un `data-target` optionnel
(navigation) et un `data-attachment-filename` optionnel — marqueur
mécanique posé quand un fichier a été joint (voir
@@ -213,17 +227,22 @@ Un dict à 4 clés (`BORDER_SIDES`), chacune `{"style": "none", "width":
### `BOX_DEFAULTS: dict[str, Any]`
`{"padding": "", "margin": "", "background_color": "", "border_radius":
"", "align_self": "stretch", "height": "", "min_height": "",
"max_height": "", "min_width": "", "box_shadow": "", "opacity": ""}` —
`border` n'y figure PAS (voir `default_border()`, à ajouter séparément
par chaque appelant pour éviter le partage par référence).
"", "align_self": "stretch", "width": "", "max_width": "", "height": "",
"min_height": "", "max_height": "", "min_width": "", "box_shadow": "",
"opacity": ""}` — `border` n'y figure PAS (voir `default_border()`, à
ajouter séparément par chaque appelant pour éviter le partage par
référence).
### `render_box_style(a: dict[str, Any]) -> str`
Construit les déclarations CSS inline pour `padding`/`margin`/
`background_color`/`border_radius`/`height`/`min_height`/`max_height`/
`min_width`/`box_shadow`/`opacity`/`border`/`align_self` de `a` — un
attribut absent ou à sa valeur par défaut ne produit AUCUNE déclaration
(comportement historique inchangé). `border` est un dict à 4 clés
Construit les déclarations CSS inline pour chaque attribut listé dans
`BOX_DEFAULTS` (padding/margin/background_color/border_radius/width/
max_width/height/min_height/max_height/min_width/box_shadow/opacity) +
`border`/`align_self` de `a`, via une table de correspondance
(clé d'attribut, propriété CSS) plutôt qu'un bloc `if` par attribut
(complexité cognitive — voir `_render_simple_properties`/`_render_border`,
privées) — un attribut absent ou à sa valeur par défaut ne produit
AUCUNE déclaration (comportement historique inchangé). `border` est un
dict à 4 clés
(`BORDER_SIDES`), chacune `{"style", "width", "color"}` — un côté à
`style="none"` (ou absent) ne produit rien pour ce côté, jamais un
`border-top:none` explicite. `align-self` n'est ajouté que si différent