From 136d51550427989f91b6704171d589f34c0b789c Mon Sep 17 00:00:00 2001 From: Severiano Badajoz Date: Tue, 26 May 2020 16:00:47 -0700 Subject: [PATCH] create Truncate component --- client/src/components/util/truncate.js | 59 ++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 client/src/components/util/truncate.js diff --git a/client/src/components/util/truncate.js b/client/src/components/util/truncate.js new file mode 100644 index 00000000..91d5dbdf --- /dev/null +++ b/client/src/components/util/truncate.js @@ -0,0 +1,59 @@ +import React, { Component } from "react"; +import { Tooltip, Position } from "@blueprintjs/core"; +import pixelWidth from "string-pixel-width"; + +import { widthsMap, tooltipHoverOpenDelayQuick } from "../../globals"; + +export default class Truncate extends Component { + maybeTruncateString = (str, maxSize, activeFont, fontSize) => { + let truncatedString = null; + const renderedSize = pixelWidth(str, { + font: activeFont, + size: fontSize, + map: widthsMap, + }); + if (renderedSize > maxSize) { + const percentage = renderedSize / maxSize; + const newLength = str.length / percentage; + truncatedString = `${str.slice(0, newLength / 2)}…${str.slice( + -newLength / 2 + )}`; + } + + return truncatedString; + }; + + render() { + const { + children, + size, + fontSize, + "data-testid": testID, + "data-testclass": testClass, + style, + } = this.props; + const truncatedString = this.maybeTruncateString( + children, + size, + "Roboto Condensed", + fontSize + ); + return ( + + + {truncatedString || children} + + + ); + } +}