Files
Forge-Engine/screens/rendering/render_jauge.py
T
william c9d3069f47 Fix Jauge always reading the object's most recent row
A Jauge could only target a whole object, not a specific record —
three gauges pointing at the same "value" field (e.g. Réputation/
Trésorerie/Confiance in one "jauge" object) all silently showed the
most recent row's value, with no way to tell them apart.

Add "Enregistrement (ligne) à suivre" (row_id) so a Jauge targets one
specific row, and "Champ contenant le nom" (champ_nom) to show a
label above the bar — both as dropdowns populated from the object's
actual fields/rows (previously "Champ numérique à afficher" was free
text the user had to type correctly by hand). No regression: without
row_id the widget still falls back to the latest row, exactly as
before.

Extract data_definition_options() (rows+fields for a definition) out
of routes/screens/screen_edit.py so controls_with_values.py can reuse
it server-side for the initial render; a small client-side handler
(bindJaugeDefinitionSelect) repopulates the same selects live when
the tracked object is changed without leaving the panel.

Verified live with Playwright: picking "jauge" then "Confiance" then
"value"/"name" in the panel renders an 80%-filled, green-leaning bar
labelled "Confiance" on /play — not the 20%/50% of the other rows.
2026-08-23 18:02:02 +02:00

126 lines
5.5 KiB
Python

import html as html_lib
import db
from .style_string import _style_string
from .auto_id import _auto_id
def _hex_to_rgb(hex_color):
hex_color = (hex_color or "#5b8cff").lstrip("#")
if len(hex_color) != 6:
hex_color = "5b8cff"
return tuple(int(hex_color[i:i + 2], 16) for i in (0, 2, 4))
def _interpolate_color(low_hex, high_hex, ratio):
"""Dégradé linéaire simple entre deux couleurs (rouge en bas, vert en
haut par défaut, comme demandé dans le document d'interface de Boîte
Mail) — ratio est déjà borné entre 0 et 1 par l'appelant."""
lo, hi = _hex_to_rgb(low_hex), _hex_to_rgb(high_hex)
mixed = tuple(round(lo[i] + (hi[i] - lo[i]) * ratio) for i in range(3))
return "#{:02x}{:02x}{:02x}".format(*mixed)
def _read_field_value(slug, definition_id, row_id, field_name):
"""Lit la valeur du champ demandé sur l'enregistrement visé (row_id) de
l'objet suivi — quand un objet contient plusieurs enregistrements (ex:
Réputation/Trésorerie/Confiance dans un même objet "jauge"), row_id est
ce qui distingue lequel suivre. Repli sur la ligne la PLUS RÉCENTE si
row_id est absent ou introuvable (jauges créées avant ce réglage, ou
ligne supprimée depuis) — comportement historique, jamais de régression
pour un objet à une seule ligne."""
if not definition_id or not field_name or not slug:
return None
definition = db.get_definition(slug, int(definition_id))
if not definition:
return None
rows = db.list_rows(slug, definition)
if not rows:
return None
row = None
if row_id:
row = next((r for r in rows if str(r["id"]) == str(row_id)), None)
if row is None:
row = rows[0]
col = db.slugify(field_name).replace("-", "_")
return row.get(col)
def _render_jauge(el, meta, slug, children_map=None, ctx=None, parent_flex_direction=None):
"""Jauge/barre dont le remplissage (largeur en %) et la couleur (dégradé
bas -> haut) se recalculent automatiquement à partir d'un champ
numérique d'un objet de données — voir 2.1 dans la doc de cadrage Forge
Engine ("binding live d'une donnée vers un style"). Recalculée à chaque
régénération du HTML du jeu (chargement de /play, et après toute action
"Modifier une donnée"), donc toujours à jour sans action supplémentaire
à poser dans le graphe de logique."""
attrs = el.get("attributes") or {}
# display:flex column : le nom (optionnel) empile AU-DESSUS de la barre
# plutôt que de se superposer dedans — voir name_html plus bas. Le fond/
# bordure/overflow vivent maintenant sur le wrapper de la barre
# (bar_wrap_style), pas ici, pour que le nom reste en dehors de la zone
# rognée par "overflow:hidden".
style = _style_string(el, " display:flex; flex-direction:column; gap:4px;", parent_flex_direction)
definition_id = attrs.get("_definition_id")
row_id = attrs.get("_row_id")
field_name = (attrs.get("_champ") or "").strip()
field_name_nom = (attrs.get("_champ_nom") or "").strip()
try:
min_v = float(attrs.get("_min", "0") or 0)
except (TypeError, ValueError):
min_v = 0.0
try:
max_v = float(attrs.get("_max", "100") or 100)
except (TypeError, ValueError):
max_v = 100.0
couleur_basse = attrs.get("_couleur_basse") or "#e05252"
couleur_haute = attrs.get("_couleur_haute") or "#4caf50"
afficher_valeur = attrs.get("_afficher_valeur") == "1"
raw_value = _read_field_value(slug, definition_id, row_id, field_name) if field_name else None
try:
value = float(raw_value)
except (TypeError, ValueError):
value = min_v
span = (max_v - min_v) or 1
ratio = max(0.0, min(1.0, (value - min_v) / span))
percent = round(ratio * 100, 1)
fill_color = _interpolate_color(couleur_basse, couleur_haute, ratio)
label_html = ""
if afficher_valeur:
label_html = (
f'<div style="position:absolute; inset:0; display:flex; align-items:center; '
f'justify-content:center; font-family:system-ui,sans-serif; font-size:12px; '
f'color:#e8eaf0; text-shadow:0 1px 2px rgba(0,0,0,.6);">{html_lib.escape(str(raw_value if raw_value is not None else "—"))}</div>'
)
name_html = ""
if field_name_nom:
nom_value = _read_field_value(slug, definition_id, row_id, field_name_nom)
if nom_value not in (None, ""):
name_html = (
f'<div style="flex:0 0 auto; font-family:system-ui,sans-serif; font-size:12px; '
f'color:#e8eaf0; text-align:center;">{html_lib.escape(str(nom_value))}</div>'
)
# La classe "jaugeBar" est repérée côté client (play.html, refreshRuntimeData)
# pour savoir que ce wrapper doit être régénéré après toute action
# "Modifier une donnée" — sinon la jauge resterait figée sur sa valeur
# de départ après un changement, exactement comme il fallait déjà
# repérer "repeaterItem" pour les Répéteurs (voir 1.1/1.2).
bar = (
f'<div class="jaugeBar" style="position:absolute; left:0; top:0; bottom:0; width:{percent}%; '
f'background-color:{fill_color}; transition:width .3s ease, background-color .3s ease;"></div>'
)
bar_wrap = (
f'<div style="position:relative; overflow:hidden; background:#1c2130; border-radius:6px; '
f'flex:1 1 auto; min-height:0;">{bar}{label_html}</div>'
)
return (
f'<div id="{_auto_id(el)}" data-element-id="{el["id"]}" style="{html_lib.escape(style)}">'
f'{name_html}{bar_wrap}</div>'
)