Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/presentation-subscriber-reentry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/charts': patch
---

Keep presentation subscribers and animation completion on the newest scene when a subscriber renders another scene.
134 changes: 134 additions & 0 deletions packages/charts-core/src/motion.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,140 @@ const rows = [
{ id: 'b', category: 'B', value: 80 },
]

describe('presentation subscriber re-entry', () => {
it('defers notifications while a motion callback nests a render', () => {
const frames = installManagedFrames()
const container = document.createElement('div')
const surface = motion<{ x: number; y: number }>({ initial: false }).mount(
container,
() => {},
)
let armed = false
let insideCallback = false
const observedInside: boolean[] = []
const makeScene = (value: number) =>
createChartScene(
defineChart({
marks: [
dot([{ x: 1, y: value }], {
x: 'x',
y: 'y',
motion: () => {
if (armed) {
armed = false
insideCallback = true
surface.render(makeScene(3), { ariaLabel: 'three' })
insideCallback = false
}
return { transition: { type: 'tween', duration: 100 } }
},
}),
],
scales: {
x: { scale: scaleLinear().domain([0, 2]) },
y: { scale: scaleLinear().domain([0, 4]) },
},
guides: false,
}),
{ width: 400, height: 200 },
)
try {
surface.render(makeScene(1), { ariaLabel: 'one' })
surface.subscribePresentationPoints?.(() =>
observedInside.push(insideCallback),
)
armed = true
surface.render(makeScene(2), { ariaLabel: 'two' })
expect(observedInside).not.toContain(true)
frames.run(0)
frames.run(100)
expect(container.querySelector('svg')?.getAttribute('aria-label')).toBe(
'three',
)
expect(
Number(container.querySelector('circle')?.getAttribute('cy')),
).toBeCloseTo(makeScene(3).points[0]!.y)
} finally {
surface.destroy()
frames.restore()
}
})
it.each(['snap', 'initial', 'mid', 'finish', 'cancel'])(
'keeps the newest render after %s notification re-entry',
(phase) => {
const frames = installManagedFrames()
const makeScene = (revision: number) =>
createChartScene(
defineChart({
marks: [dot([{ x: 1, y: revision, revision }], { x: 'x', y: 'y' })],
scales: {
x: { scale: scaleLinear().domain([0, 2]) },
y: { scale: scaleLinear().domain([0, 4]) },
},
guides: false,
}),
{ width: 400, height: 200 },
)
const container = document.createElement('div')
const surface = motion<{ x: number; y: number; revision: number }>({
initial: false,
transition: {
type: 'tween',
duration: phase === 'snap' ? 0 : 100,
easing: 'linear',
},
}).mount(container, () => {})
const third = makeScene(3)
let armed = phase === 'snap' || phase === 'initial'
let reentered = false
const observations: number[] = []
try {
surface.render(makeScene(1), { ariaLabel: 'one' })
surface.subscribePresentationPoints?.((points) => {
if (armed && !reentered && points[0]?.datum.revision === 2) {
reentered = true
surface.render(third, { ariaLabel: 'three' })
}
})
surface.subscribePresentationPoints?.((points) => {
observations.push(points[0]!.datum.revision)
})
surface.render(makeScene(2), { ariaLabel: 'two' })
if (phase === 'cancel') {
armed = true
surface.render(makeScene(4), { ariaLabel: 'four' })
}
if (phase !== 'snap') {
frames.run(0)
if (phase === 'mid') armed = true
frames.run(50)
armed = true
frames.run(100)
if (frames.pending()) frames.run(200)
if (frames.pending()) frames.run(400)
}
const expected = phase === 'cancel' ? 4 : 3
expect(reentered).toBe(phase !== 'cancel')
expect(observations).toContain(expected)
expect(
observations.slice(observations.indexOf(expected)),
).not.toContain(2)
expect(container.querySelector('svg')?.getAttribute('aria-label')).toBe(
phase === 'cancel' ? 'four' : 'three',
)
expect(surface.getPresentationPoints?.()).toBeUndefined()
expect(
Number(container.querySelector('circle')?.getAttribute('cy')),
).toBeCloseTo(makeScene(expected).points[0]!.y)
} finally {
surface.destroy()
expect(frames.pending()).toBe(0)
frames.restore()
}
},
)
})

describe('motion resize policy', () => {
it.each([false, true])(
'handles a resize during entrance with resize: %s',
Expand Down
209 changes: 116 additions & 93 deletions packages/charts-core/src/motion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -828,6 +828,7 @@ function createMotionSvgChartRenderer<
let stateTransitions:
Readonly<Record<string, ChartMarkStateTransition>> | undefined
let stateScene: ChartScene<TDatum, TXValue, TYValue> | undefined
let rendering = 0
let dataMotionRevision = 0
let dataMotionActive = false
let stateFlushQueued = false
Expand Down Expand Up @@ -861,7 +862,12 @@ function createMotionSvgChartRenderer<
points: readonly ChartPoint<TDatum, TXValue, TYValue>[],
) => {
presentationPoints = points
for (const listener of presentationListeners) listener(points)
if (rendering) return
const revision = dataMotionRevision
for (const listener of presentationListeners) {
if (revision !== dataMotionRevision) break
listener(points)
}
}
const queuePendingStateFocus = () => {
if (stateFlushQueued || !pendingStateFocus) return
Expand Down Expand Up @@ -953,105 +959,120 @@ function createMotionSvgChartRenderer<
})
return presented.scene
}
function renderScene(
nextScene: ChartScene<TDatum, TXValue, TYValue>,
options: ChartSurfaceRenderOptions,
) {
const previousScene = scene
const initial = previousScene === undefined
const resized = Boolean(
previousScene &&
(previousScene.width !== nextScene.width ||
previousScene.height !== nextScene.height),
)
const reduced =
motion.respectReducedMotion &&
(container.ownerDocument.defaultView?.matchMedia?.(
'(prefers-reduced-motion: reduce)',
).matches ??
false)
const animate =
!reduced &&
(initial
? motion.initial && (!adoptedRoot || motion.initial === 'always')
: motion.resize || !resized)
const viewportMoved = Boolean(
previousScene && viewportTranslationChanged(previousScene, nextScene),
)
const markup = renderSvg(nextScene, options)
cancelAnimation()
const previousPresentation =
presentationPoints ?? previousScene?.points ?? []
cancelFocusAnimation()
cancelFocusAnimation = () => {}
const retainsFocusGuideLayers = Boolean(
previousScene?.focusGuides?.length,
)
const focusGuideLayers = retainsFocusGuideLayers
? detachSvgFocusGuideLayers(svgElement())
: {}
for (const placement of visibleFocusGuides) {
if (
!nextScene.focusGuides?.some(
(guide) => guide.placement === placement,
)
) {
visibleFocusGuides.delete(placement)
}
}
const revision = ++dataMotionRevision
stateScene = undefined
stateTransition = undefined
scene = nextScene
renderOptions = options
dataMotionActive = animate && !viewportMoved
pendingStateFocus = dataMotionActive ? desiredStateFocus : undefined
if (animate && !viewportMoved) {
if (initial) reconcileChartSvg(container, markup)
const cancel = motion.animateSvg({
container,
scene: nextScene as ChartScene<TDatum>,
previousScene: previousScene as ChartScene<TDatum> | undefined,
presentationPoints:
previousPresentation as readonly ChartPoint<TDatum>[],
markup,
phase: initial ? 'initial' : 'update',
setPresentationPoints(points) {
if (revision !== dataMotionRevision) return
publishPresentationPoints(
points as readonly ChartPoint<TDatum, TXValue, TYValue>[],
)
if (
points === nextScene.points &&
revision === dataMotionRevision
) {
dataMotionActive = false
queuePendingStateFocus()
}
},
})
if (revision === dataMotionRevision) cancelAnimation = cancel
else cancel()
} else {
reconcileChartSvg(container, markup)
publishPresentationPoints(nextScene.points)
dataMotionActive = false
}
if (retainsFocusGuideLayers) {
restoreSvgFocusGuideLayers(
svgElement(),
focusGuideLayers,
(placement) =>
scene?.focusGuides?.some(
(guide) => guide.placement === placement,
) === true,
)
}
if (revision !== dataMotionRevision) return
scene = nextScene
stateScene = undefined
renderOptions = options
stateTransition = undefined
stateTransitions = undefined
}
const surface: ChartSurface<TDatum, TXValue, TYValue> = {
renderer: ownerRenderer ?? renderer,
get element() {
return svgElement()
},
render(nextScene, options) {
const previousScene = scene
const initial = previousScene === undefined
const resized = Boolean(
previousScene &&
(previousScene.width !== nextScene.width ||
previousScene.height !== nextScene.height),
)
const reduced =
motion.respectReducedMotion &&
(container.ownerDocument.defaultView?.matchMedia?.(
'(prefers-reduced-motion: reduce)',
).matches ??
false)
const animate =
!reduced &&
(initial
? motion.initial && (!adoptedRoot || motion.initial === 'always')
: motion.resize || !resized)
const viewportMoved = Boolean(
previousScene &&
viewportTranslationChanged(previousScene, nextScene),
)
const markup = renderSvg(nextScene, options)
cancelAnimation()
const previousPresentation =
presentationPoints ?? previousScene?.points ?? []
cancelFocusAnimation()
cancelFocusAnimation = () => {}
const retainsFocusGuideLayers = Boolean(
previousScene?.focusGuides?.length,
)
const focusGuideLayers = retainsFocusGuideLayers
? detachSvgFocusGuideLayers(svgElement())
: {}
for (const placement of visibleFocusGuides) {
if (
!nextScene.focusGuides?.some(
(guide) => guide.placement === placement,
)
) {
visibleFocusGuides.delete(placement)
}
}
const revision = ++dataMotionRevision
stateScene = undefined
stateTransition = undefined
scene = nextScene
renderOptions = options
dataMotionActive = animate && !viewportMoved
pendingStateFocus = dataMotionActive ? desiredStateFocus : undefined
if (animate && !viewportMoved) {
if (initial) reconcileChartSvg(container, markup)
cancelAnimation = motion.animateSvg({
container,
scene: nextScene as ChartScene<TDatum>,
previousScene: previousScene as ChartScene<TDatum> | undefined,
presentationPoints:
previousPresentation as readonly ChartPoint<TDatum>[],
markup,
phase: initial ? 'initial' : 'update',
setPresentationPoints(points) {
publishPresentationPoints(
points as readonly ChartPoint<TDatum, TXValue, TYValue>[],
)
if (
revision === dataMotionRevision &&
points === nextScene.points
) {
dataMotionActive = false
queuePendingStateFocus()
}
},
})
} else {
reconcileChartSvg(container, markup)
publishPresentationPoints(nextScene.points)
dataMotionActive = false
}
if (retainsFocusGuideLayers) {
restoreSvgFocusGuideLayers(
svgElement(),
focusGuideLayers,
(placement) =>
nextScene.focusGuides?.some(
(guide) => guide.placement === placement,
) === true,
)
rendering += 1
try {
renderScene(nextScene, options)
} finally {
rendering -= 1
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
scene = nextScene
stateScene = undefined
renderOptions = options
stateTransition = undefined
stateTransitions = undefined
if (presentationPoints) publishPresentationPoints(presentationPoints)
},
clientToScene(currentScene, clientX, clientY) {
return svgClientToScene(svgElement(), currentScene, clientX, clientY)
Expand Down Expand Up @@ -3994,6 +4015,7 @@ function runTracks(
}
}
lifecycle.publish?.()
if (cancelled) return
root.dataset.tsMotionProgress = String(finished.size / activeTracks.length)
if (finished.size < activeTracks.length && elapsed < safetyLimit) {
frame = view.requestAnimationFrame(tick)
Expand All @@ -4003,6 +4025,7 @@ function runTracks(
if (!finished.has(track)) completeMotionTrack(track)
}
lifecycle.finish?.()
if (cancelled) return
root.dataset.tsMotionState = 'finished'
root.dataset.tsMotionProgress = '1'
}
Expand Down
Loading
Loading