forked from zachleat/BigText
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bigtext.js
286 lines (248 loc) · 9.38 KB
/
bigtext.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
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/*! BigText - v0.1.5 - 2013-08-24
* https://github.com/zachleat/BigText
* Copyright (c) 2013 @zachleat; Licensed MIT */
;(function(window, $) {
var counter = 0,
$headCache = $('head'),
oldBigText = window.BigText,
oldjQueryMethod = $.fn.bigtext,
BigText = {
DEBUG_MODE: false,
DEFAULT_MIN_FONT_SIZE_PX: null,
DEFAULT_MAX_FONT_SIZE_PX: 528,
GLOBAL_STYLE_ID: 'bigtext-style',
STYLE_ID: 'bigtext-id',
LINE_CLASS_PREFIX: 'bigtext-line',
EXEMPT_CLASS: 'bigtext-exempt',
noConflict: function(restore)
{
if(restore) {
$.fn.bigtext = oldjQueryMethod;
window.BigText = oldBigText;
}
return BigText;
},
test: {
noFractionalFontSize: (function() {
if( !( 'getComputedStyle' in window ) || !( 'body' in document ) ) {
return true;
}
var test = $('<div/>').css({
position: 'absolute',
'font-size': '14.1px'
}).appendTo(document.body).get(0),
computedStyle = window.getComputedStyle( test, null );
return computedStyle ? computedStyle.getPropertyValue( 'font-size' ) === '14px' : true;
})()
},
init: function() {
if(!$('#'+BigText.GLOBAL_STYLE_ID).length) {
$headCache.append(BigText.generateStyleTag(BigText.GLOBAL_STYLE_ID, ['.bigtext * { white-space: nowrap; } .bigtext > * { display: block; }',
'.bigtext .' + BigText.EXEMPT_CLASS + ', .bigtext .' + BigText.EXEMPT_CLASS + ' * { white-space: normal; }']));
}
},
bindResize: function(eventName, resizeFunction) {
if($.throttle) {
// https://github.com/cowboy/jquery-throttle-debounce
$(window).unbind(eventName).bind(eventName, $.throttle(100, resizeFunction));
} else {
if($.fn.smartresize) {
// https://github.com/lrbabe/jquery-smartresize/
eventName = 'smartresize.' + eventName;
}
$(window).unbind(eventName).bind(eventName, resizeFunction);
}
},
getStyleId: function(id)
{
return BigText.STYLE_ID + '-' + id;
},
generateStyleTag: function(id, css)
{
return $('<style>' + css.join('\n') + '</style>').attr('id', id);
},
clearCss: function(id)
{
var styleId = BigText.getStyleId(id);
$('#' + styleId).remove();
},
generateCss: function(id, linesFontSizes, lineWordSpacings, minFontSizes)
{
var css = [];
BigText.clearCss(id);
for(var j=0, k=linesFontSizes.length; j<k; j++) {
css.push('#' + id + ' .' + BigText.LINE_CLASS_PREFIX + j + ' {' +
(minFontSizes[j] ? ' white-space: normal;' : '') +
(linesFontSizes[j] ? ' font-size: ' + linesFontSizes[j] + 'px;' : '') +
(lineWordSpacings[j] ? ' word-spacing: ' + lineWordSpacings[j] + 'px;' : '') +
'}');
}
return BigText.generateStyleTag(BigText.getStyleId(id), css);
},
jQueryMethod: function(options)
{
BigText.init();
options = $.extend({
minfontsize: BigText.DEFAULT_MIN_FONT_SIZE_PX,
maxfontsize: BigText.DEFAULT_MAX_FONT_SIZE_PX,
childSelector: '',
resize: true
}, options || {});
return this.each(function()
{
var $t = $(this).addClass('bigtext'),
maxWidth = $t.width(),
id = $t.attr('id'),
$children = options.childSelector ? $t.find( options.childSelector ) : $t.children();
if(!id) {
id = 'bigtext-id' + (counter++);
$t.attr('id', id);
}
if(options.resize) {
BigText.bindResize('resize.bigtext-event-' + id, function()
{
// TODO only call this if the width has changed.
BigText.jQueryMethod.call($('#' + id), options);
});
}
BigText.clearCss(id);
$children.addClass(function(lineNumber, className)
{
// remove existing line classes.
return [className.replace(new RegExp('\\b' + BigText.LINE_CLASS_PREFIX + '\\d+\\b'), ''),
BigText.LINE_CLASS_PREFIX + lineNumber].join(' ');
});
var sizes = calculateSizes($t, $children, maxWidth, options.maxfontsize, options.minfontsize);
$headCache.append(BigText.generateCss(id, sizes.fontSizes, sizes.wordSpacings, sizes.minFontSizes));
});
}
};
function testLineDimensions($line, maxWidth, property, size, interval, units, previousWidth)
{
var width;
previousWidth = typeof previousWidth == 'number' ? previousWidth : 0;
$line.css(property, size + units);
width = $line.width();
if(width >= maxWidth) {
// console.log(width, ' previous: ' + previousWidth, property + ' at ' + interval, 'prior: ' + (parseFloat(size) - interval), 'new:' + parseFloat(size));
$line.css(property, '');
if(width == maxWidth) {
return {
match: 'exact',
size: parseFloat((parseFloat(size) - 0.1).toFixed(3))
};
}
// Since this is an estimate, we calculate how far over the width we went with the new value.
// If this is word-spacing (our last resort guess) and the over is less than the under, we keep the higher value.
// Otherwise, we revert to the underestimate.
var under = maxWidth - previousWidth,
over = width - maxWidth;
return {
match: 'estimate',
size: parseFloat((parseFloat(size) - (property === 'word-spacing' && previousWidth && ( over < under ) ? 0 : interval)).toFixed(3))
};
}
return width;
}
function calculateSizes($t, $children, maxWidth, maxFontSize, minFontSize)
{
var $c = $t.clone(true)
.addClass('bigtext-cloned')
.css({
fontFamily: $t.css('font-family'),
textTransform: $t.css('text-transform'),
wordSpacing: $t.css('word-spacing'),
letterSpacing: $t.css('letter-spacing'),
position: 'absolute',
left: BigText.DEBUG_MODE ? 0 : -9999,
top: BigText.DEBUG_MODE ? 0 : -9999
}).appendTo(document.body);
// font-size isn't the only thing we can modify, we can also mess with:
// word-spacing and letter-spacing. WebKit does not respect subpixel
// letter-spacing, word-spacing, or font-size.
// TODO try -webkit-transform: scale() as a workaround.
var fontSizes = [],
wordSpacings = [],
minFontSizes = [],
ratios = [];
$children.css('float', 'left').each(function(lineNumber) {
var $line = $(this),
// TODO replace 8, 4 with a proportional size to the calculated font-size.
intervals = BigText.test.noFractionalFontSize ? [8, 4, 1] : [8, 4, 1, 0.1],
lineMax;
if($line.hasClass(BigText.EXEMPT_CLASS)) {
fontSizes.push(null);
ratios.push(null);
minFontSizes.push(false);
return;
}
// TODO we can cache this ratio?
var autoGuessSubtraction = 32, // font size in px
currentFontSize = parseFloat($line.css('font-size')),
ratio = ( $line.width() / currentFontSize ).toFixed(6);
newFontSize = parseInt( maxWidth / ratio, 10 ) - autoGuessSubtraction;
outer: for(var m=0, n=intervals.length; m<n; m++) {
inner: for(var j=1, k=10; j<=k; j++) {
if(newFontSize + j*intervals[m] > maxFontSize) {
newFontSize = maxFontSize;
break outer;
}
lineMax = testLineDimensions($line, maxWidth, 'font-size', newFontSize + j*intervals[m], intervals[m], 'px', lineMax);
if(typeof lineMax !== 'number') {
newFontSize = lineMax.size;
if(lineMax.match == 'exact') {
break outer;
}
break inner;
}
}
}
ratios.push(maxWidth / newFontSize);
if(newFontSize > maxFontSize) {
fontSizes.push(maxFontSize);
minFontSizes.push(false);
} else if(!!minFontSize && newFontSize < minFontSize) {
fontSizes.push(minFontSize);
minFontSizes.push(true);
} else {
fontSizes.push(newFontSize);
minFontSizes.push(false);
}
}).each(function(lineNumber) {
var $line = $(this),
wordSpacing = 0,
interval = 1,
maxWordSpacing;
if($line.hasClass(BigText.EXEMPT_CLASS)) {
wordSpacings.push(null);
return;
}
// must re-use font-size, even though it was removed above.
$line.css('font-size', fontSizes[lineNumber] + 'px');
for(var m=1, n=3; m<n; m+=interval) {
maxWordSpacing = testLineDimensions($line, maxWidth, 'word-spacing', m, interval, 'px', maxWordSpacing);
if(typeof maxWordSpacing !== 'number') {
wordSpacing = maxWordSpacing.size;
break;
}
}
$line.css('font-size', '');
wordSpacings.push(wordSpacing);
}).removeAttr('style');
if( !BigText.DEBUG_MODE ) {
$c.remove();
} else {
$c.css({
'background-color': 'rgba(255,255,255,.4)'
});
}
return {
fontSizes: fontSizes,
wordSpacings: wordSpacings,
ratios: ratios,
minFontSizes: minFontSizes
};
}
$.fn.bigtext = BigText.jQueryMethod;
window.BigText = BigText;
})(this, jQuery);