To do so, you have to listen to new event for example:
lizMap.mainLizmap.state.layerTree.addListener((evt) => {
// it is a group do nothing
if (evt.target.type == 'group') return;
// the layer is visible, expand the legend
if (evt.target.visibility) evt.target.expanded = true;
},'layer.visibility.changed')
Another elegant solution is to use QGIS map themes. This allows you to control the display of the legend/layer group individually for each theme and then for each layer/layer group.
with the most recent version 3.9.4 QGIS map themes respect now checked state (even if the layer is in an unchecked parent group) and expanded state. small bugfixes are on the way, so with 3.9.5 by latest, it should be fully and flawlessly supported. maybe this is an approach whcih works for you, @pierreflorin
for autoexpaneding the legend of a layer when activating it, you still would need to refrain to custom JS - this behaviour is not QGIS default, so it is also not really “desired” by design in lizmap imho