redash/client/app/lib/calculateTextWidth.ts
Rafael Wendel 12f71925c2
Multiselect dropdown slowness (fix) (#5221)
* created util to estimate reasonable width for dropdown

* removed unused import

* improved calculation of item percentile

* added getItemOfPercentileLength to relevant spots

* added getItemOfPercentileLength to relevant spots

* Added missing import

* created custom select element

* added check for property path

* removed uses of percentile util

* gave up on getting element reference

* finished testing Select component

* removed unused imports

* removed older uses of Option component

* added canvas calculation

* removed minWidth from Select

* improved calculation

* added fallbacks

* added estimated offset

* removed leftovers 😅

* replaced to percentiles to max value

* switched to memo and renamed component

* proper useMemo syntax

* Update client/app/components/Select.tsx

Co-authored-by: Gabriel Dutra <nesk.frz@gmail.com>

* created custom restrictive types

* added quick const

* fixed style

* fixed generics

* added pos absolute to fix percy

* removed custom select from ParameterMappingInput

* applied prettier

* Revert "added pos absolute to fix percy"

This reverts commit 4daf1d4bef9edf93cd9bb1f404bd022472ff17a2.

* Pin Percy version to 0.24.3

* Update client/app/components/ParameterMappingInput.jsx

Co-authored-by: Gabriel Dutra <nesk.frz@gmail.com>

* renamed Select.jsx to SelectWithVirtualScroll

Co-authored-by: Gabriel Dutra <nesk.frz@gmail.com>
2020-11-03 21:50:39 +02:00

21 lines
731 B
TypeScript

const canvas = document.createElement("canvas");
canvas.style.display = "none";
document.body.appendChild(canvas);
export function calculateTextWidth(text: string, container = document.body) {
const ctx = canvas.getContext("2d");
if (ctx) {
const containerStyle = window.getComputedStyle(container);
ctx.font = `${containerStyle.fontSize} ${containerStyle.fontFamily}`;
const textMetrics = ctx.measureText(text);
let actualWidth = textMetrics.width;
if ("actualBoundingBoxLeft" in textMetrics) {
// only available on evergreen browsers
actualWidth = Math.abs(textMetrics.actualBoundingBoxLeft) + Math.abs(textMetrics.actualBoundingBoxRight);
}
return actualWidth;
}
return null;
}