Live layout switching
Layouts aren't fixed at construction — call simulation.changeLayout(...) any time and the graph morphs into the new arrangement. This demo cycles through a vertical tree, a horizontal tree, a radial tree, and the force layout on a timer.
changeLayout returns a promise that resolves only once the new layout has settled and re-centered, so chaining transitions is just await. The timer is started in onLoadedCallback and cleared in onUnmountedCallback so it can never fire after the graph is gone.
Current layout: Vertical tree
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' }
]
}