PluginProbe
Gutenberg / 22.4.3
Gutenberg v22.4.3
24.0.0 23.9.1 23.9.0 23.8.0 23.7.2 23.7.1 23.7.0 23.6.1 23.6.2 23.6.0 23.5.3 23.5.2 23.5.1 23.5.0 23.4.0 23.3.2 23.3.1 23.3.0 23.2.0 23.2.1 23.2.2 23.1.1 23.1.0 23.0.1 12.6.0 All 403 releases
gutenberg / build / modules / block-editor / utils / fit-text-frontend.js

fit-text-frontend.js in Gutenberg 22.4.3, at build/modules/block-editor/utils/fit-text-frontend.js

72 lines 2.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 // packages/block-editor/build-module/utils/fit-text-frontend.mjs
2 import { store, getElement, getContext } from "@wordpress/interactivity";
3
4 // packages/block-editor/build-module/utils/fit-text-utils.mjs
5 function findOptimalFontSize(textElement, applyFontSize) {
6 const alreadyHasScrollableHeight = textElement.scrollHeight > textElement.clientHeight;
7 let minSize = 0;
8 let maxSize = 2400;
9 let bestSize = minSize;
10 const computedStyle = window.getComputedStyle(textElement);
11 const paddingLeft = parseFloat(computedStyle.paddingLeft) || 0;
12 const paddingRight = parseFloat(computedStyle.paddingRight) || 0;
13 const range = document.createRange();
14 range.selectNodeContents(textElement);
15 while (minSize <= maxSize) {
16 const midSize = Math.floor((minSize + maxSize) / 2);
17 applyFontSize(midSize);
18 const rect = range.getBoundingClientRect();
19 const textWidth = rect.width;
20 const fitsWidth = textElement.scrollWidth <= textElement.clientWidth && textWidth <= textElement.clientWidth - paddingLeft - paddingRight;
21 const fitsHeight = alreadyHasScrollableHeight || textElement.scrollHeight <= textElement.clientHeight;
22 if (fitsWidth && fitsHeight) {
23 bestSize = midSize;
24 minSize = midSize + 1;
25 } else {
26 maxSize = midSize - 1;
27 }
28 }
29 range.detach();
30 return bestSize;
31 }
32 function optimizeFitText(textElement, applyFontSize) {
33 if (!textElement) {
34 return;
35 }
36 applyFontSize(0);
37 const optimalSize = findOptimalFontSize(textElement, applyFontSize);
38 applyFontSize(optimalSize);
39 return optimalSize;
40 }
41
42 // packages/block-editor/build-module/utils/fit-text-frontend.mjs
43 store("core/fit-text", {
44 callbacks: {
45 init() {
46 const context = getContext();
47 const { ref } = getElement();
48 const applyFontSize = (fontSize) => {
49 if (fontSize === 0) {
50 ref.style.fontSize = "";
51 } else {
52 ref.style.fontSize = `${fontSize}px`;
53 }
54 };
55 context.fontSize = optimizeFitText(ref, applyFontSize);
56 if (window.ResizeObserver && ref.parentElement) {
57 const resizeObserver = new window.ResizeObserver(() => {
58 context.fontSize = optimizeFitText(ref, applyFontSize);
59 });
60 resizeObserver.observe(ref.parentElement);
61 resizeObserver.observe(ref);
62 return () => {
63 if (resizeObserver) {
64 resizeObserver.disconnect();
65 }
66 };
67 }
68 }
69 }
70 });
71 //# sourceMappingURL=fit-text-frontend.js.map
72