Changement de mise en page en direct
Les mises en page ne sont pas fixées lors de la construction : appelez simulation.changeLayout(...) à tout moment et le graphique se transforme en la nouvelle disposition. Cette démo passe par un arbre vertical, un arbre horizontal, un arbre radial et la disposition des forces sur une minuterie.
changeLayout renvoie une promesse qui ne se résout qu'une fois que la nouvelle mise en page s'est installée et recentrée, donc l'enchaînement des transitions n'est que await. La minuterie est démarrée en onLoadedCallback et effacée en onUnmountedCallback afin qu'elle ne puisse jamais se déclencher une fois le graphique disparu.
Disposition actuelle : Arbre vertical
js
// The layouts to rotate through. The initial render is already STATES[0].
const STATES = [
{ label: 'Vertical tree', type: 'tree', options: { layout: { rootId: 'ceo', horizontal: false, radial: false } } },
{ label: 'Horizontal tree', type: 'tree', options: { layout: { rootId: 'ceo', horizontal: true, radial: false } } },
{ label: 'Radial tree', type: 'tree', options: { layout: { rootId: 'ceo', radial: true } } },
{ label: 'Force', type: 'force', options: {} }
]
let timer = null
let stopped = false
// Switch layouts on a timer. `changeLayout` resolves only once the new layout
// has settled and re-centered, so we await it, then pause before the next.
function startCycling(graph, onState) {
stopped = false
let i = 0
const step = async () => {
if (stopped) return
i = (i + 1) % STATES.length
const state = STATES[i]
onState?.(state.label)
await graph.simulation.changeLayout(state.type, state.options)
if (stopped) return
timer = setTimeout(step, 1800)
}
timer = setTimeout(step, 2400)
}
// Cleared from the demo's onUnmountedCallback so the timer can't outlive the graph.
function stopCycling() {
stopped = true
if (timer) clearTimeout(timer)
timer = null
}js
// Start on a vertical tree; the cycle below switches it at runtime.
const options = {
layout: { type: 'tree', rootId: 'ceo' }
}js
const data = {
nodes: [
{ id: 'ceo' },
{ id: 'cto' },
{ id: 'cfo' },
{ id: 'coo' },
{ id: 'eng' },
{ id: 'platform' },
{ id: 'infra' },
{ id: 'data' },
{ id: 'finance' },
{ id: 'billing' },
{ id: 'ops' },
{ id: 'support' },
{ id: 'qa' }
],
edges: [
{ from: 'ceo', to: 'cto' },
{ from: 'ceo', to: 'cfo' },
{ from: 'ceo', to: 'coo' },
{ from: 'cto', to: 'eng' },
{ from: 'cto', to: 'platform' },
{ from: 'platform', to: 'infra' },
{ from: 'platform', to: 'data' },
{ from: 'eng', to: 'qa' },
{ from: 'cfo', to: 'finance' },
{ from: 'cfo', to: 'billing' },
{ from: 'coo', to: 'ops' },
{ from: 'coo', to: 'support' }
]
}