Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[6.7] Zoom out: maintain scroll position (#61465) #66343

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
120 changes: 120 additions & 0 deletions packages/block-editor/src/components/iframe/bezier-easing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/**
* https://github.com/gre/bezier-easing
* BezierEasing - use bezier curve for transition easing function
* by Gaëtan Renaudeau 2014 - 2015 – MIT License
*/

const NEWTON_ITERATIONS = 4;
const NEWTON_MIN_SLOPE = 0.001;
const SUBDIVISION_PRECISION = 0.0000001;
const SUBDIVISION_MAX_ITERATIONS = 10;

const kSplineTableSize = 11;
const kSampleStepSize = 1.0 / ( kSplineTableSize - 1.0 );

function A( aA1, aA2 ) {
return 1.0 - 3.0 * aA2 + 3.0 * aA1;
}
function B( aA1, aA2 ) {
return 3.0 * aA2 - 6.0 * aA1;
}
function C( aA1 ) {
return 3.0 * aA1;
}

// Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2.
function calcBezier( aT, aA1, aA2 ) {
return ( ( A( aA1, aA2 ) * aT + B( aA1, aA2 ) ) * aT + C( aA1 ) ) * aT;
}

// Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2.
function getSlope( aT, aA1, aA2 ) {
return 3.0 * A( aA1, aA2 ) * aT * aT + 2.0 * B( aA1, aA2 ) * aT + C( aA1 );
}

function binarySubdivide( aX, aA, aB, mX1, mX2 ) {
let currentX,
currentT,
i = 0;
do {
currentT = aA + ( aB - aA ) / 2.0;
currentX = calcBezier( currentT, mX1, mX2 ) - aX;
if ( currentX > 0.0 ) {
aB = currentT;
} else {
aA = currentT;
}
} while (
Math.abs( currentX ) > SUBDIVISION_PRECISION &&
++i < SUBDIVISION_MAX_ITERATIONS
);
return currentT;
}

function newtonRaphsonIterate( aX, aGuessT, mX1, mX2 ) {
for ( let i = 0; i < NEWTON_ITERATIONS; ++i ) {
const currentSlope = getSlope( aGuessT, mX1, mX2 );
if ( currentSlope === 0.0 ) {
return aGuessT;
}
const currentX = calcBezier( aGuessT, mX1, mX2 ) - aX;
aGuessT -= currentX / currentSlope;
}
return aGuessT;
}

export default function cubicBezier( mX1, mY1, mX2, mY2 ) {
if ( mX1 === mY1 && mX2 === mY2 ) {
return function linearEasing( x ) {
return x;
};
}

const sampleValues = new Float32Array( kSplineTableSize );
for ( let i = 0; i < kSplineTableSize; ++i ) {
sampleValues[ i ] = calcBezier( i * kSampleStepSize, mX1, mX2 );
}

function getTForX( aX ) {
let intervalStart = 0.0;
let currentSample = 1;
const lastSample = kSplineTableSize - 1;

for (
;
currentSample !== lastSample && sampleValues[ currentSample ] <= aX;
++currentSample
) {
intervalStart += kSampleStepSize;
}
--currentSample;

const dist =
( aX - sampleValues[ currentSample ] ) /
( sampleValues[ currentSample + 1 ] -
sampleValues[ currentSample ] );

const guessForT = intervalStart + dist * kSampleStepSize;

const initialSlope = getSlope( guessForT, mX1, mX2 );
if ( initialSlope >= NEWTON_MIN_SLOPE ) {
return newtonRaphsonIterate( aX, guessForT, mX1, mX2 );
} else if ( initialSlope === 0.0 ) {
return guessForT;
}
return binarySubdivide(
aX,
intervalStart,
intervalStart + kSampleStepSize,
mX1,
mX2
);
}

return function bezierEasing( x ) {
if ( x === 0 || x === 1 ) {
return x;
}
return calcBezier( getTForX( x ), mY1, mY2 );
};
}
170 changes: 161 additions & 9 deletions packages/block-editor/src/components/iframe/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
forwardRef,
useMemo,
useEffect,
useLayoutEffect,
useRef,
} from '@wordpress/element';
import { __ } from '@wordpress/i18n';
Expand All @@ -31,6 +32,13 @@ import { useBlockSelectionClearer } from '../block-selection-clearer';
import { useWritingFlow } from '../writing-flow';
import { getCompatibilityStyles } from './get-compatibility-styles';
import { store as blockEditorStore } from '../../store';
import cubicBezier from './bezier-easing';

// Easing function from the CSS editor-canvas-resize-animation.
// const scrollEasing = cubicBezier( 0.46, 0.03, 0.52, 0.96 );

// Complementary easing function to the CSS editor-canvas-resize-animation.
const scrollEasing = cubicBezier( 1 - 0.52, 1 - 0.96, 1 - 0.46, 1 - 0.03 );

function bubbleEvent( event, Constructor, frame ) {
const init = {};
Expand Down Expand Up @@ -121,15 +129,18 @@ function Iframe( {
};
}, [] );
const { styles = '', scripts = '' } = resolvedAssets;
/** @type {[Document, React.Dispatch<React.SetStateAction<Document>>]} */
const [ iframeDocument, setIframeDocument ] = useState();
const initialContainerWidth = useRef( 0 );
const [ bodyClasses, setBodyClasses ] = useState( [] );
const clearerRef = useBlockSelectionClearer();
const [ before, writingFlowRef, after ] = useWritingFlow();
const [ contentResizeListener, { height: contentHeight } ] =
useResizeObserver();
const [ containerResizeListener, { width: containerWidth } ] =
useResizeObserver();
const [
containerResizeListener,
{ width: containerWidth, height: containerHeight },
] = useResizeObserver();

const setRef = useRefEffect( ( node ) => {
node._load = () => {
Expand Down Expand Up @@ -252,6 +263,15 @@ function Iframe( {
containerWidth
);

const frameSizeValue = parseInt( frameSize );

const maxWidth = 750;
const scaleValue =
scale === 'default'
? ( Math.min( containerWidth, maxWidth ) - frameSizeValue * 2 ) /
scaleContainerWidth
: scale;

const disabledRef = useDisabled( { isDisabled: ! readonly } );
const bodyRef = useMergeRefs( [
useBubbleEvents( iframeDocument ),
Expand Down Expand Up @@ -343,7 +363,6 @@ function Iframe( {
return;
}

const maxWidth = 750;
// Note: When we initialize the zoom out when the canvas is smaller (sidebars open),
// initialContainerWidth will be smaller than the full page, and reflow will happen
// when the canvas area becomes larger due to sidebars closing. This is a known but
Expand All @@ -354,11 +373,7 @@ function Iframe( {
// but calc( 100px / 2px ) is not.
iframeDocument.documentElement.style.setProperty(
'--wp-block-editor-iframe-zoom-out-scale',
scale === 'default'
? ( Math.min( containerWidth, maxWidth ) -
parseInt( frameSize ) * 2 ) /
scaleContainerWidth
: scale
scaleValue
);

// frameSize has to be a px value for the scaling and frame size to be computed correctly.
Expand Down Expand Up @@ -404,7 +419,7 @@ function Iframe( {
);
};
}, [
scale,
scaleValue,
frameSize,
iframeDocument,
iframeWindowInnerHeight,
Expand All @@ -419,6 +434,143 @@ function Iframe( {
// mode. They're only needed to capture focus in edit mode.
const shouldRenderFocusCaptureElements = tabIndex >= 0 && ! isPreviewMode;

const prevScaleRef = useRef( scaleValue );
const prevFrameSizeRef = useRef( frameSizeValue );
const prevContainerHeightRef = useRef( containerHeight );

// Scroll based on the new scale
useEffect( () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should/could this happen within the same useEffect as the useEffect that runs when toggling zoom out (that adds the animation classnames with handleZoomOutAnimationClassname)?

if ( ! iframeDocument ) {
return;
}

const scaleValuePrev = prevScaleRef.current;
const frameSizeValuePrev = prevFrameSizeRef.current;
const containerHeightPrev = prevContainerHeightRef.current;

if ( containerHeightPrev === containerHeight ) {
return;
}

// TODO: Scroll top is sometimes wrong by containerHeight sometimes in Firefox.

const { documentElement, defaultView } = iframeDocument;
const { scrollTop } = documentElement;
const { scrollY } = defaultView;

// Convert previous values to the zoomed in scale.
// Use Math.round to avoid subpixel scrolling which would effectively result in a Math.floor.
const scrollTopOriginal = Math.round(
( scrollTop + containerHeightPrev / 2 - frameSizeValuePrev ) /
scaleValuePrev -
containerHeightPrev / 2
);

// Convert the zoomed in value to the new scale.
// Use Math.round to avoid subpixel scrolling which would effectively result in a Math.floor.
const scrollTopNext = Math.round(
( scrollTopOriginal + containerHeight / 2 ) * scaleValue +
frameSizeValue -
containerHeight / 2
);

// Convert previous values to the zoomed in scale.
const scrollYOriginal =
( scrollY + containerHeightPrev / 2 - frameSizeValuePrev ) /
scaleValuePrev -
containerHeightPrev / 2;

// Convert the zoomed in value to the new scale.
const scrollYNext =
( scrollYOriginal + containerHeight / 2 ) * scaleValue +
frameSizeValue -
containerHeight / 2;

console.log( {
scaleValue,
scaleValuePrev,
} );
console.log( {
frameSizeValue,
frameSizeValuePrev,
} );
console.log( {
containerHeight,
containerHeightPrev,
} );
console.log( {
scrollTop,
scrollTopOriginal,
scrollTopNext,
} );
console.log( {
scrollY,
scrollYOriginal,
scrollYNext,
} );

documentElement.scrollTop = scrollTopNext;

// defaultView.scroll( {
// top: scrollY + ( frameSizeValue - frameSizeValuePrev ),
// behavior: 'auto',
// } );

// let raf = requestAnimationFrame( ( start ) => {
// const duration = 400; // Should match the CSS transition duration.
// console.log( documentElement.scrollTop, '0.000', '0.000' );
// const step = ( timestamp ) => {
// const progress = Math.min(
// ( timestamp - start ) / duration,
// 1
// );
// const easing = scrollEasing( progress );
// documentElement.scrollTop = Math.floor(
// scrollTop + ( scrollTopNext - scrollTop ) * easing
// );
// console.log(
// documentElement.scrollTop,
// progress.toFixed( 3 ),
// easing.toFixed( 3 )
// );
// if ( progress < 1 ) {
// raf = requestAnimationFrame( step );
// }
// };
// raf = requestAnimationFrame( step );
// } );

// const timers = Array.from( { length: 20 }, ( _, i ) => {
// const delay = i * 100;
// // eslint-disable-next-line @wordpress/react-no-unsafe-timeout
// return setTimeout( () => {
// if ( i === 10 ) {
// documentElement.scrollTop = scrollTopNext;
// }
// console.log( delay, documentElement.scrollTop );
// }, delay );
// } );

console.log();
if ( scaleValuePrev !== scaleValue ) {
console.log( 'scaleValue changed' );
prevScaleRef.current = scaleValue;
}
if ( frameSizeValuePrev !== frameSizeValue ) {
console.log( 'frameSizeValue changed' );
prevFrameSizeRef.current = frameSizeValue;
}
if ( containerHeightPrev !== containerHeight ) {
console.log( 'containerHeight changed' );
prevContainerHeightRef.current = containerHeight;
}

return () => {
// cancelAnimationFrame( raf );
// timers.forEach( clearTimeout );
};
}, [ iframeDocument, scaleValue, frameSizeValue, containerHeight ] );

const iframe = (
<>
{ shouldRenderFocusCaptureElements && before }
Expand Down
Loading