Live lay-out wisselen
De lay-outs liggen niet vast tijdens de bouw. Bel simulation.changeLayout(...) any tijd en de grafiek verandert in de nieuwe opstelling. Deze demo doorloopt een verticale boom, een horizontale boom, een radiale boom en de krachtindeling op een timer.
changeLayout retourneert een belofte die pas wordt uitgevoerd zodra de nieuwe lay-out is doorgevoerd gesetteld en opnieuw gecentreerd, dus het koppelen van overgangen is slechts await. De timer is begonnen in onLoadedCallback en gewist in onUnmountedCallback zodat het kan vuur nooit nadat de grafiek verdwenen is.
Huidige lay-out: Verticale boom
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' }
]
}