smooth panel animations

This commit is contained in:
eli-w-king
2026-02-09 12:51:04 -08:00
parent 9899b0a9e2
commit 849d97e1bc
9 changed files with 465 additions and 39 deletions

View File

@@ -6,7 +6,7 @@
import { IBoundarySashes, Orientation } from '../sash/sash.js';
import { equals, tail } from '../../../common/arrays.js';
import { Event } from '../../../common/event.js';
import { Disposable } from '../../../common/lifecycle.js';
import { Disposable, IDisposable } from '../../../common/lifecycle.js';
import './gridview.css';
import { Box, GridView, IGridViewOptions, IGridViewStyles, IView as IGridViewView, IViewSize, orthogonal, Sizing as GridViewSizing, GridLocation } from './gridview.js';
import type { SplitView, AutoSizing as SplitViewAutoSizing } from '../splitview/splitview.js';
@@ -655,6 +655,20 @@ export class Grid<T extends IView = IView> extends Disposable {
this.gridview.setViewVisible(location, visible);
}
/**
* Set the visibility state of a {@link IView view} with a smooth animation.
*
* @param view The {@link IView view}.
* @param visible Whether the view should be visible.
* @param duration The transition duration in milliseconds.
* @param easing The CSS easing function string.
* @returns A disposable that cancels the animation.
*/
setViewVisibleAnimated(view: T, visible: boolean, duration: number, easing: string, onComplete?: () => void): IDisposable {
const location = this.getViewLocation(view);
return this.gridview.setViewVisibleAnimated(location, visible, duration, easing, onComplete);
}
/**
* Returns a descriptor for the entire grid.
*/

View File

@@ -633,6 +633,24 @@ class BranchNode implements ISplitView<ILayoutContext>, IDisposable {
}
}
setChildVisibleAnimated(index: number, visible: boolean, duration: number, easing: string, onComplete?: () => void): IDisposable {
index = validateIndex(index, this.children.length);
if (this.splitview.isViewVisible(index) === visible) {
return { dispose: () => { } };
}
const wereAllChildrenHidden = this.splitview.contentSize === 0;
const disposable = this.splitview.setViewVisibleAnimated(index, visible, duration, easing, onComplete);
const areAllChildrenHidden = this.splitview.contentSize === 0;
if ((visible && wereAllChildrenHidden) || (!visible && areAllChildrenHidden)) {
this._onDidVisibilityChange.fire(visible);
}
return disposable;
}
getChildCachedVisibleSize(index: number): number | undefined {
index = validateIndex(index, this.children.length);
@@ -1677,6 +1695,31 @@ export class GridView implements IDisposable {
parent.setChildVisible(index, visible);
}
/**
* Set the visibility state of a {@link IView view} with a smooth animation.
*
* @param location The {@link GridLocation location} of the view.
* @param visible Whether the view should be visible.
* @param duration The transition duration in milliseconds.
* @param easing The CSS easing function string.
* @returns A disposable that cancels the animation.
*/
setViewVisibleAnimated(location: GridLocation, visible: boolean, duration: number, easing: string, onComplete?: () => void): IDisposable {
if (this.hasMaximizedView()) {
this.exitMaximizedView();
return { dispose: () => { } };
}
const [rest, index] = tail(location);
const [, parent] = this.getNode(rest);
if (!(parent instanceof BranchNode)) {
throw new Error('Invalid from location');
}
return parent.setChildVisibleAnimated(index, visible, duration, easing, onComplete);
}
/**
* Returns a descriptor for the entire grid.
*/

View File

@@ -0,0 +1,9 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/* Utility class applied during panel animations to prevent content overflow */
.monaco-split-view2 > .split-view-container > .split-view-view.motion-animating {
overflow: hidden;
}

View File

@@ -0,0 +1,125 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import './motion.css';
//#region Duration Constants
/**
* Duration in milliseconds for panel open (entrance) animations.
* Per Fluent 2 Enter/Exit pattern - entrance should feel smooth but not sluggish.
*/
export const PANEL_OPEN_DURATION = 300;
/**
* Duration in milliseconds for panel close (exit) animations.
* Exits are faster than entrances - feels snappy and responsive.
*/
export const PANEL_CLOSE_DURATION = 200;
/**
* Duration in milliseconds for quick input open (entrance) animations.
*/
export const QUICK_INPUT_OPEN_DURATION = 250;
/**
* Duration in milliseconds for quick input close (exit) animations.
*/
export const QUICK_INPUT_CLOSE_DURATION = 150;
//#endregion
//#region Easing Curves
/**
* Fluent 2 ease-out curve - default for entrances and expansions.
* Starts fast and decelerates to a stop.
*/
export const EASE_OUT = 'cubic-bezier(0.1, 0.9, 0.2, 1)';
/**
* Fluent 2 ease-in curve - for exits and collapses.
* Starts slow and accelerates out.
*/
export const EASE_IN = 'cubic-bezier(0.9, 0.1, 1, 0.2)';
//#endregion
//#region Cubic Bezier Evaluation
/**
* Parses a CSS `cubic-bezier(x1, y1, x2, y2)` string into its four control
* point values. Returns `[0, 0, 1, 1]` (linear) on parse failure.
*/
export function parseCubicBezier(css: string): [number, number, number, number] {
const match = css.match(/cubic-bezier\(\s*([-\d.]+)\s*,\s*([-\d.]+)\s*,\s*([-\d.]+)\s*,\s*([-\d.]+)\s*\)/);
if (!match) {
return [0, 0, 1, 1];
}
return [parseFloat(match[1]), parseFloat(match[2]), parseFloat(match[3]), parseFloat(match[4])];
}
/**
* Evaluates a cubic bezier curve at time `t` (0-1).
*
* Given control points `(x1, y1)` and `(x2, y2)` (the CSS `cubic-bezier`
* parameters), this finds the bezier parameter `u` such that `Bx(u) = t`
* using Newton's method, then returns `By(u)`.
*/
export function solveCubicBezier(x1: number, y1: number, x2: number, y2: number, t: number): number {
if (t <= 0) {
return 0;
}
if (t >= 1) {
return 1;
}
// Newton's method to find u where Bx(u) = t
let u = t; // initial guess
for (let i = 0; i < 8; i++) {
const currentX = bezierComponent(u, x1, x2);
const error = currentX - t;
if (Math.abs(error) < 1e-6) {
break;
}
const dx = bezierComponentDerivative(u, x1, x2);
if (Math.abs(dx) < 1e-6) {
break;
}
u -= error / dx;
}
u = Math.max(0, Math.min(1, u));
return bezierComponent(u, y1, y2);
}
/** Evaluates one component of a cubic bezier: B(u) with control points p1, p2, endpoints 0 and 1. */
function bezierComponent(u: number, p1: number, p2: number): number {
// B(u) = 3(1-u)^2*u*p1 + 3(1-u)*u^2*p2 + u^3
const oneMinusU = 1 - u;
return 3 * oneMinusU * oneMinusU * u * p1 + 3 * oneMinusU * u * u * p2 + u * u * u;
}
/** First derivative of a bezier component: B'(u). */
function bezierComponentDerivative(u: number, p1: number, p2: number): number {
// B'(u) = 3(1-u)^2*p1 + 6(1-u)*u*(p2-p1) + 3*u^2*(1-p2)
const oneMinusU = 1 - u;
return 3 * oneMinusU * oneMinusU * p1 + 6 * oneMinusU * u * (p2 - p1) + 3 * u * u * (1 - p2);
}
//#endregion
//#region Utility Functions
/**
* Checks whether motion is reduced by looking for the `monaco-reduce-motion`
* class on an ancestor element. This integrates with VS Code's existing
* accessibility infrastructure in {@link AccessibilityService}.
*/
export function isMotionReduced(element: HTMLElement): boolean {
return element.closest('.monaco-reduce-motion') !== null;
}
//#endregion

View File

@@ -14,6 +14,7 @@ import { combinedDisposable, Disposable, dispose, IDisposable, toDisposable } fr
import { clamp } from '../../../common/numbers.js';
import { Scrollable, ScrollbarVisibility, ScrollEvent } from '../../../common/scrollable.js';
import * as types from '../../../common/types.js';
import { isMotionReduced, parseCubicBezier, solveCubicBezier } from '../motion/motion.js';
import './splitview.css';
export { Orientation } from '../sash/sash.js';
@@ -818,6 +819,155 @@ export class SplitView<TLayoutContext = undefined, TView extends IView<TLayoutCo
this.saveProportions();
}
/**
* Set a {@link IView view}'s visibility with a smooth animation.
*
* Uses `requestAnimationFrame` to interpolate all view sizes on each frame,
* which naturally cascades layout changes through nested splitviews in the
* grid hierarchy (e.g., the bottom panel resizing when the sidebar animates).
*
* If motion is reduced (via accessibility settings), falls back to instant
* {@link setViewVisible}.
*
* @param index The {@link IView view} index.
* @param visible Whether the {@link IView view} should be visible.
* @param duration The transition duration in milliseconds.
* @param easing The CSS `cubic-bezier(...)` easing function string.
* @param onComplete Optional callback invoked when the animation finishes.
* NOT called if the animation is canceled via {@link IDisposable.dispose}.
* @returns A disposable that cancels the animation if disposed before completion.
*/
setViewVisibleAnimated(index: number, visible: boolean, duration: number, easing: string, onComplete?: () => void): IDisposable {
if (index < 0 || index >= this.viewItems.length) {
throw new Error('Index out of bounds');
}
// Cancel any in-flight animation
this._cleanupMotion?.();
this._cleanupMotion = undefined;
const viewItem = this.viewItems[index];
// If motion is reduced or already in target state, use instant path
if (viewItem.visible === visible || isMotionReduced(this.el)) {
this.setViewVisible(index, visible);
return toDisposable(() => { });
}
const container = this.viewContainer.children[index] as HTMLElement;
const window = getWindow(this.el);
let disposed = false;
let rafId: number | undefined;
// 1. Snapshot sizes BEFORE the visibility change (the animation start state)
const startSizes = this.viewItems.map(v => v.size);
// 2. Apply the target visibility to the model instantly.
// This computes final sizes, fires events, updates sashes, etc.
this.setViewVisible(index, visible);
// 3. Snapshot sizes AFTER the visibility change (the animation end state)
const finalSizes = this.viewItems.map(v => v.size);
// 4. Restore start sizes so we can animate FROM them
for (let i = 0; i < this.viewItems.length; i++) {
this.viewItems[i].size = startSizes[i];
}
// 5. For hiding: the target container lost .visible class (→ display:none).
// Restore it so content stays visible during the animation.
if (!visible) {
container.classList.add('visible');
}
// 6. Clip overflow on the target container while it shrinks.
// Only apply for HIDE animations - for SHOW, we leave overflow alone
// so that box-shadow / visual effects on the child Part are not clipped
// by the parent container during the animation.
if (!visible) {
container.style.overflow = 'hidden';
}
// 7. Render the start state
this.layoutViews();
// 8. Parse easing for JS evaluation
const [x1, y1, x2, y2] = parseCubicBezier(easing);
// Helper: snap all sizes to final state and clean up
const applyFinalState = () => {
for (let i = 0; i < this.viewItems.length; i++) {
this.viewItems[i].size = finalSizes[i];
}
if (!visible) {
container.classList.remove('visible');
container.style.overflow = '';
}
this.layoutViews();
this.saveProportions();
};
const cleanup = (completed: boolean) => {
if (disposed) {
return;
}
disposed = true;
if (rafId !== undefined) {
window.cancelAnimationFrame(rafId);
rafId = undefined;
}
applyFinalState();
this._cleanupMotion = undefined;
if (completed) {
onComplete?.();
}
};
this._cleanupMotion = () => cleanup(false);
// 9. Animate via requestAnimationFrame
const startTime = performance.now();
const totalSize = this.size;
const animate = () => {
if (disposed) {
return;
}
const elapsed = performance.now() - startTime;
const t = Math.min(elapsed / duration, 1);
const easedT = solveCubicBezier(x1, y1, x2, y2, t);
// Interpolate all view sizes
let runningTotal = 0;
for (let i = 0; i < this.viewItems.length; i++) {
if (i === this.viewItems.length - 1) {
// Last item absorbs rounding errors to maintain total = this.size
this.viewItems[i].size = totalSize - runningTotal;
} else {
const size = Math.round(
startSizes[i] + (finalSizes[i] - startSizes[i]) * easedT
);
this.viewItems[i].size = size;
runningTotal += size;
}
}
this.layoutViews();
if (t < 1) {
rafId = window.requestAnimationFrame(animate);
} else {
cleanup(true);
}
};
rafId = window.requestAnimationFrame(animate);
return toDisposable(() => cleanup(false));
}
private _cleanupMotion: (() => void) | undefined;
/**
* Returns the {@link IView view}'s size previously to being hidden.
*