aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/nodes/LabelBigText.js
blob: 290152cd0bd98174ac76c5addcbaec4106e8c85d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
/*
Brorlandi/big-text.js v1.0.0, 2017
Adapted from DanielHoffmann/jquery-bigtext, v1.3.0, May 2014
And from Jetroid/bigtext.js v1.0.0, September 2016

Usage:
BigText("#myElement",{
    rotateText: {Number}, (null)
    fontSizeFactor: {Number}, (0.8)
    maximumFontSize: {Number}, (null)
    limitingDimension: {String}, ("both")
    horizontalAlign: {String}, ("center")
    verticalAlign: {String}, ("center")
    textAlign: {String}, ("center")
    whiteSpace: {String}, ("nowrap")
});


Original Projects: 
https://github.com/DanielHoffmann/jquery-bigtext
https://github.com/Jetroid/bigtext.js

Options:

rotateText: Rotates the text inside the element by X degrees.

fontSizeFactor: This option is used to give some vertical spacing for letters that overflow the line-height (like 'g', 'Á' and most other accentuated uppercase letters). This does not affect the font-size if the limiting factor is the width of the parent div. The default is 0.8

maximumFontSize: maximum font size to use.

minimumFontSize: minimum font size to use.  if font is calculated smaller than this, text will be rendered at this size and wrapped

limitingDimension: In which dimension the font size should be limited. Possible values: "width", "height" or "both". Defaults to both. Using this option with values different than "both" overwrites the element parent width or height.

horizontalAlign: Where to align the text horizontally. Possible values: "left", "center", "right". Defaults to "center".

verticalAlign: Where to align the text vertically. Possible values: "top", "center", "bottom". Defaults to "center".

textAlign: Sets the text align of the element. Possible values: "left", "center", "right". Defaults to "center". This option is only useful if there are linebreaks (<br> tags) inside the text.

whiteSpace: Sets whitespace handling. Possible values: "nowrap", "pre". Defaults to "nowrap". (Can also be set to enable wrapping but this doesn't work well.)

Bruno Orlandi - 2017

Copyright (C) 2013 Daniel Hoffmann Bernardes, Ícaro Technologies
Copyright (C) 2016 Jet Holt

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

function _calculateInnerDimensions(computedStyle) {
    //Calculate the inner width and height
    var innerWidth;
    var innerHeight;

    var width = parseInt(computedStyle.getPropertyValue("width"));
    var height = parseInt(computedStyle.getPropertyValue("height"));
    var paddingLeft = parseInt(computedStyle.getPropertyValue("padding-left"));
    var paddingRight = parseInt(computedStyle.getPropertyValue("padding-right"));
    var paddingTop = parseInt(computedStyle.getPropertyValue("padding-top"));
    var paddingBottom = parseInt(computedStyle.getPropertyValue("padding-bottom"));
    var borderLeft = parseInt(computedStyle.getPropertyValue("border-left-width"));
    var borderRight = parseInt(computedStyle.getPropertyValue("border-right-width"));
    var borderTop = parseInt(computedStyle.getPropertyValue("border-top-width"));
    var borderBottom = parseInt(computedStyle.getPropertyValue("border-bottom-width"));

    //If box-sizing is border-box, we need to subtract padding and border.
    var parentBoxSizing = computedStyle.getPropertyValue("box-sizing");
    if (parentBoxSizing == "border-box") {
        innerWidth = width - (paddingLeft + paddingRight + borderLeft + borderRight);
        innerHeight = height - (paddingTop + paddingBottom + borderTop + borderBottom);
    } else {
        innerWidth = width;
        innerHeight = height;
    }
    var obj = {};
    obj["width"] = innerWidth;
    obj["height"] = innerHeight;
    return obj;
}

export default function BigText(element, options) {

    if (typeof element === 'string') {
        element = document.querySelector(element);
    } else if (element.length) {
        // Support for array based queries (such as jQuery)
        element = element[0];
    }

    var defaultOptions = {
        rotateText: null,
        fontSizeFactor: 0.8,
        maximumFontSize: null,
        limitingDimension: "both",
        horizontalAlign: "center",
        verticalAlign: "center",
        textAlign: "center",
        whiteSpace: "nowrap",
        singleLine: true
    };

    //Merge provided options and default options
    options = options || {};
    for (var opt in defaultOptions)
        if (defaultOptions.hasOwnProperty(opt) && !options.hasOwnProperty(opt))
            options[opt] = defaultOptions[opt];

    //Get variables which we will reference frequently
    var style = element.style;
    var parent = element.parentNode;
    var parentStyle = parent.style;
    var parentComputedStyle = document.defaultView.getComputedStyle(parent);

    //hides the element to prevent "flashing"
    style.visibility = "hidden";
    //Set some properties
    style.display = "inline-block";
    style.clear = "both";
    style.float = "left";
    var fontSize = options.maximumFontSize;
    if (options.singleLine) {
        style.fontSize = (fontSize * options.fontSizeFactor) + "px";
        style.lineHeight = fontSize + "px";
    } else {
        for (; fontSize > options.minimumFontSize; fontSize = fontSize - Math.min(fontSize / 2, Math.max(0, fontSize - 48) + 2)) {
            style.fontSize = (fontSize * options.fontSizeFactor) + "px";
            style.lineHeight = "1";
            if (element.offsetHeight <= +parentComputedStyle.height.replace("px", "")) {
                break;
            }
        }
    }
    style.whiteSpace = options.whiteSpace;
    style.textAlign = options.textAlign;
    style.position = "relative";
    style.padding = 0;
    style.margin = 0;
    style.left = "50%";
    style.top = "50%";
    var computedStyle = document.defaultView.getComputedStyle(element);

    //Get properties of parent to allow easier referencing later.
    var parentPadding = {
        top: parseInt(parentComputedStyle.getPropertyValue("padding-top")),
        right: parseInt(parentComputedStyle.getPropertyValue("padding-right")),
        bottom: parseInt(parentComputedStyle.getPropertyValue("padding-bottom")),
        left: parseInt(parentComputedStyle.getPropertyValue("padding-left")),
    };
    var parentBorder = {
        top: parseInt(parentComputedStyle.getPropertyValue("border-top")),
        right: parseInt(parentComputedStyle.getPropertyValue("border-right")),
        bottom: parseInt(parentComputedStyle.getPropertyValue("border-bottom")),
        left: parseInt(parentComputedStyle.getPropertyValue("border-left")),
    };

    //Calculate the parent inner width and height
    var parentInnerDimensions = _calculateInnerDimensions(parentComputedStyle);
    var parentInnerWidth = parentInnerDimensions["width"];
    var parentInnerHeight = parentInnerDimensions["height"];

    var box = {
        width: element.offsetWidth, //Note: This is slightly larger than the jQuery version
        height: element.offsetHeight,
    };
    if (!box.width || !box.height) return element;


    if (options.rotateText !== null) {
        if (typeof options.rotateText !== "number")
            throw "bigText error: rotateText value must be a number";
        var rotate = "rotate(" + options.rotateText + "deg)";
        style.webkitTransform = rotate;
        style.msTransform = rotate;
        style.MozTransform = rotate;
        style.OTransform = rotate;
        style.transform = rotate;
        //calculating bounding box of the rotated element
        var sine = Math.abs(Math.sin(options.rotateText * Math.PI / 180));
        var cosine = Math.abs(Math.cos(options.rotateText * Math.PI / 180));
        box.width = element.offsetWidth * cosine + element.offsetHeight * sine;
        box.height = element.offsetWidth * sine + element.offsetHeight * cosine;
    }

    var parentWidth = (parentInnerWidth - parentPadding.left - parentPadding.right);
    var parentHeight = (parentInnerHeight - parentPadding.top - parentPadding.bottom);
    var widthFactor = parentWidth / box.width;
    var heightFactor = parentHeight / box.height;
    var lineHeight;

    if (options.limitingDimension.toLowerCase() === "width") {
        lineHeight = Math.floor(widthFactor * fontSize);
    } else if (options.limitingDimension.toLowerCase() === "height") {
        lineHeight = Math.floor(heightFactor * fontSize);
    } else if (widthFactor < heightFactor)
        lineHeight = Math.floor(widthFactor * fontSize);
    else if (widthFactor >= heightFactor)
        lineHeight = Math.floor(heightFactor * fontSize);

    var fontSize = lineHeight * options.fontSizeFactor;
    if (fontSize < options.minimumFontSize) {
        parentStyle.display = "flex";
        parentStyle.alignItems = "center";
        style.textAlign = "center";
        style.visibility = "";
        style.fontSize = options.minimumFontSize + "px";
        style.lineHeight = "";
        style.overflow = "hidden";
        style.textOverflow = "ellipsis";
        style.top = "";
        style.left = "";
        style.margin = "";
        return element;
    }
    if (options.maximumFontSize && fontSize > options.maximumFontSize) {
        fontSize = options.maximumFontSize;
        lineHeight = fontSize / options.fontSizeFactor;
    }

    style.fontSize = Math.floor(fontSize) + "px";
    style.lineHeight = Math.ceil(lineHeight) + "px";
    style.marginBottom = "0px";
    style.marginRight = "0px";

    // if (options.limitingDimension.toLowerCase() === "height") {
    //     //this option needs the font-size to be set already so computedStyle.getPropertyValue("width") returns the right size
    //     //this +4 is to compensate the rounding erros that can occur due to the calls to Math.floor in the centering code
    //     parentStyle.width = (parseInt(computedStyle.getPropertyValue("width")) + 4) + "px";
    // }

    //Calculate the inner width and height
    var innerDimensions = _calculateInnerDimensions(computedStyle);
    var innerWidth = innerDimensions["width"];
    var innerHeight = innerDimensions["height"];

    switch (options.verticalAlign.toLowerCase()) {
        case "top":
            style.top = "0%";
            break;
        case "bottom":
            style.top = "100%";
            style.marginTop = Math.floor(-innerHeight) + "px";
            break;
        default:
            style.marginTop = Math.ceil((-innerHeight / 2)) + "px";
            break;
    }

    switch (options.horizontalAlign.toLowerCase()) {
        case "left":
            style.left = "0%";
            break;
        case "right":
            style.left = "100%";
            style.marginLeft = Math.floor(-innerWidth) + "px";
            break;
        default:
            style.marginLeft = Math.ceil((-innerWidth / 2)) + "px";
            break;
    }

    //shows the element after the work is done
    style.visibility = "visible";

    return element;
}