Live-Layoutwechsel
Layouts sind bei der Erstellung nicht festgelegt – rufen Sie jederzeit simulation.changeLayout(...) auf, und das Diagramm wird in die neue Anordnung umgewandelt. Diese Demo durchläuft einen vertikalen Baum, einen horizontalen Baum, einen radialen Baum und das Force-Layout auf einem Timer.
changeLayout gibt ein Versprechen zurück, das erst aufgelöst wird, wenn sich das neue Layout beruhigt und neu zentriert hat, sodass die Verkettung von Übergängen nur await ist. Der Timer wird in onLoadedCallback gestartet und in onUnmountedCallback gelöscht, sodass er nie ausgelöst werden kann, nachdem die Grafik verschwunden ist.
Aktuelles Layout: Vertikaler Baum
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' }
]
}