+
-
-
+
);
}
}
diff --git a/assets/src/helpers.js b/assets/src/helpers.js
index be1d3572cd9..da5f0cf88d3 100644
--- a/assets/src/helpers.js
+++ b/assets/src/helpers.js
@@ -14,7 +14,13 @@ import { _x } from '@wordpress/i18n';
/**
* Internal dependencies
*/
-import { ALLOWED_CHILD_BLOCKS, ALLOWED_TOP_LEVEL_BLOCKS, BLOCK_TAG_MAPPING } from './constants';
+import {
+ ALLOWED_CHILD_BLOCKS,
+ ALLOWED_TOP_LEVEL_BLOCKS,
+ BLOCK_TAG_MAPPING,
+ STORY_PAGE_INNER_WIDTH,
+ STORY_PAGE_INNER_HEIGHT,
+} from './constants';
export const maybeEnqueueFontStyle = ( name ) => {
if ( ! name || 'undefined' === typeof ampStoriesFonts ) {
@@ -275,3 +281,49 @@ export const getTagName = ( attributes, canUseH1 ) => {
return 'p';
};
+
+/**
+ * Calculates font size that fits to the text element based on the element's size.
+ * Replicates amp-fit-text's logic in the editor.
+ *
+ * @see https://github.com/ampproject/amphtml/blob/e7a1b3ff97645ec0ec482192205134bd0735943c/extensions/amp-fit-text/0.1/amp-fit-text.js
+ *
+ * @param {Object} measurer HTML element.
+ * @param {number} expectedHeight Maximum height.
+ * @param {number} expectedWidth Maximum width.
+ * @param {number} maxFontSize Maximum font size.
+ * @param {number} minFontSize Minimum font size.
+ * @return {number} Calculated font size.
+ */
+export const calculateFontSize = ( measurer, expectedHeight, expectedWidth, maxFontSize, minFontSize ) => {
+ maxFontSize++;
+ // Binomial search for the best font size.
+ while ( maxFontSize - minFontSize > 1 ) {
+ const mid = Math.floor( ( minFontSize + maxFontSize ) / 2 );
+ measurer.style.fontSize = mid + 'px';
+ const currentHeight = measurer.offsetHeight;
+ const currentWidth = measurer.offsetWidth;
+ if ( currentHeight > expectedHeight || currentWidth > expectedWidth ) {
+ maxFontSize = mid;
+ } else {
+ minFontSize = mid;
+ }
+ }
+ return minFontSize;
+};
+
+/**
+ * Get percentage of a distance compared to the full width / height of the page.
+ *
+ * @param {string} axis X or Y axis.
+ * @param {number} pixelValue Value in pixels.
+ * @return {number} Value in percentage.
+ */
+export const getPercentageFromPixels = ( axis, pixelValue ) => {
+ if ( 'x' === axis ) {
+ return Math.round( ( pixelValue / STORY_PAGE_INNER_WIDTH ) * 100 );
+ } else if ( 'y' === axis ) {
+ return Math.round( ( pixelValue / STORY_PAGE_INNER_HEIGHT ) * 100 );
+ }
+ return 0;
+};