/
index.js
executable file
·190 lines (160 loc) · 4.88 KB
/
index.js
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
import clamp from "clamp";
/**
* @typedef {object} Options
* @property {number} [step=0.5] The step used by the generator to calculate the width of the element.
* @property {number} [minFontSize=0] A minimum font size for the element (max would be the size defined in a stylesheet retrieved by `window.getComputedStyle(this.element)`).
* @property {number} [width="null"] A maximum width for the container.
*/
class AdaptableText {
/**
* Creates an instance of AdaptableText.
* @param {HTMLElement} element
* @param {Options} [options]
*/
constructor(element, options) {
this.element = element;
this.options = Object.assign(
{
width: null,
step: 0.5,
minFontSize: 0,
},
options,
);
// prettier-ignore
this.chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefhijklmnopqrstuvwxyz0123456789!?*()@£$%^&_-+=[]{}:;\'"\\|<>,./~`'.split('');
}
/**
* Initialise the adaptor.
*/
init() {
this.reset();
}
reset() {
// Get element styles
this.styles = window.getComputedStyle(this.element);
this.setWidth();
// Set initial font size
this.adaptedFontSize = parseFloat(
this.styles.getPropertyValue("font-size"),
);
this.initialFontsize = this.adaptedFontSize;
// Get max character width
this.maxCharWidth = 0;
this.calculateMaxCharWidth();
}
/**
* Set the desired width for adaptation from options.width or getBoundingClientRect().width
*/
setWidth() {
this.width =
this.options.width || this.element.getBoundingClientRect().width;
}
/**
* Adapt font size to a specified width.
* @param {boolean} [useBinarySearch]
*/
adapt(useBinarySearch) {
// Get element content and replace <br>
this.text = this.element.value || this.element.innerText;
// Update adapted font size
const previousFontSize = this.adaptedFontSize;
const textWidth = this.getTextWidth(this.text, previousFontSize);
this.calculateMaxCharWidth();
const availableWidth = this.width - this.maxCharWidth;
let newFontSize;
if (useBinarySearch) {
newFontSize = this.binarySearch(availableWidth);
} else {
let fontSizeGenerator;
if (
textWidth > availableWidth &&
previousFontSize > this.options.minFontSize
) {
fontSizeGenerator = this.reduceFontSize(previousFontSize);
} else {
fontSizeGenerator = this.augmentFontSize(previousFontSize);
}
if (fontSizeGenerator) {
newFontSize = fontSizeGenerator.next().value - this.options.step;
}
}
// Set font size if necessary
if (previousFontSize !== newFontSize) {
this.adaptedFontSize = clamp(
newFontSize,
this.options.minFontSize,
this.initialFontsize,
);
this.element.style.fontSize = `${this.adaptedFontSize}px`;
}
}
binarySearch(width) {
let low = this.options.minFontSize;
let high = this.initialFontsize;
let mid;
let fontSize = low;
while (low <= high) {
mid = (high + low) * 0.5;
if (this.getTextWidth(this.text, mid) <= width) {
low = mid + this.options.step;
fontSize = mid;
} else {
high = mid - this.options.step;
}
}
return fontSize;
}
*reduceFontSize(_fontSize) {
let fontSize = _fontSize;
const availableWidth = this.width - this.maxCharWidth;
const textWidth = this.getTextWidth(this.text, fontSize);
if (textWidth > availableWidth && fontSize > this.options.minFontSize) {
fontSize -= this.options.step;
} else {
yield fontSize;
}
yield* this.reduceFontSize(fontSize);
}
*augmentFontSize(_fontSize) {
let fontSize = _fontSize;
const availableWidth = this.width - this.maxCharWidth;
const textWidth = this.getTextWidth(this.text, fontSize);
if (textWidth < availableWidth && fontSize < this.initialFontsize) {
fontSize += this.options.step;
} else {
yield fontSize;
}
yield* this.augmentFontSize(fontSize);
}
getFontProperty(fontSize) {
return `${this.styles.fontStyle} ${fontSize}px ${this.styles.fontFamily}`;
}
getTextWidth(text, fontSize) {
const canvas =
this.options.canvas ||
(this.options.canvas = document.createElement("canvas"));
const context = canvas.getContext("2d");
context.font = this.getFontProperty(fontSize);
const lines = text.split("\n");
let maxWidth = 0;
for (let i = 0; i < lines.length; i++) {
const metrics = context.measureText(lines[i]);
maxWidth = Math.max(maxWidth, metrics.width);
}
return maxWidth;
}
calculateMaxCharWidth() {
let len = this.chars.length;
while (len--) {
const charWidth = this.getTextWidth(
this.chars[len],
this.adaptedFontSize,
);
if (charWidth > this.maxCharWidth) {
this.maxCharWidth = charWidth / 2;
}
}
}
}
export default AdaptableText;