forked from joaocunha/vunit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vunit.js
261 lines (227 loc) · 9.97 KB
/
vunit.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
/*!
* @license MIT
* @preserve
*
* vUnit: A vanilla JS alternative for vh and vw CSS units.
* https://github.com/joaocunha/v-unit/
*
* @author João Cunha - [email protected] - twitter.com/joaocunha
*/
(function(win, doc, undefined) {
'use strict';
win.vUnit = function (options) {
// Just an alias for easier readability (and to preserve `this` context)
var vunit = this;
// For extending the options
var opts = options || {};
vunit.options = {
// The ID for the appended stylesheet
stylesheetId: opts.stylesheetId || 'v-unit-stylesheet',
// The interval between each check in miliseconds
viewportObserverInterval: opts.viewportObserverInterval || 100,
// The CSS rules to be vUnit'd
CSSMap: opts.CSSMap || null
};
// Stores the viewport dimensions so the observer can check against it and update it.
vunit.viewportSize = {
height: 0,
width: 0
};
/**
* @function init
* Triggers the execution of vUnit and wraps its main logic.
*
* It sets an observer to check if the viewport dimensions changed, running on an interval
* based on the viewportObserverInterval option. If the dimensions have changed, it creates
* an stylesheet, adds the calculated CSS rules to it and append it to the head.
*
* The observer is a cross-device event-less solution to keep track of everything that
* would trigger a resize on the viewport:
*
* - Window resizing on desktop;
* - Orientation changing on mobile;
* - Scrollbars appearing/disappearing on desktop;
* - Navigation bars appearing/disappearing on mobile;
* - Zooming on mobile and desktop;
* - Download bar on desktop;
* - Password saving prompt on desktop;
* - Etc.
*
* @returns {Function|Boolean} The observer function or false if no CSSMap was passed.
*/
vunit.init = function() {
// We need a CSSMap to know what rules to create. Duh!
if (opts.CSSMap) {
// We pass a self-invoking function that returns itself to the setInterval method
// so we can execute the first iteration immediately. This helps preventing FOUC.
return win.setInterval((function viewportObserver() {
if (viewportHasChanged()) {
var stylesheet = createStylesheet();
var CSSRules = createCSSRules();
appendCSSRulesToStylesheet(CSSRules, stylesheet);
appendStylesheetOnHead(stylesheet);
}
return viewportObserver;
})(), vunit.options.viewportObserverInterval);
} else {
// Stops execution if no CSS rules were passed
// TODO: raise an exception
return false;
}
};
/**
* @function viewportHasChanged
* Checks if the viewport dimensions have changed since the last checking.
*
* This checking is very inexpensive, so it allows to regenerate the CSS rules only when
* it's needed.
*
* @returns {Boolean} Wether the dimensions changed or not.
*/
var viewportHasChanged = function() {
var currentViewportSize = calculateViewportSize();
var differentHeight = (currentViewportSize.height !== vunit.viewportSize.height);
var differentWidth = (currentViewportSize.width !== vunit.viewportSize.width);
// Updates the global variable for future checking
vunit.viewportSize = currentViewportSize;
return (differentHeight || differentWidth);
};
/**
* @function createStylesheet
* Creates an empty stylesheet that will hold the v-unit rules.
*
* @returns {HTMLStyleElement} An empty stylesheet element.
*/
var createStylesheet = function() {
var stylesheet = doc.createElement('style');
stylesheet.setAttribute('rel', 'stylesheet');
stylesheet.setAttribute('type', 'text/css');
stylesheet.setAttribute('media', 'screen');
stylesheet.setAttribute('id', vunit.options.stylesheetId);
return stylesheet;
};
/**
* @function createCSSRules
* Create CSS rules based on the viewport dimensions.
*
* It loops through a map of CSS properties and creates rules ranging from 1 to 100 percent
* of its size.
*
* We used to Math.round() the values, but then we can't stack two .vw50 elements side by
* side on odd viewport widths. If we use Math.floor, we end up with a 1px gap. On the other
* hand, if we use pixel decimals (no round or floor), the browsers ajusts the width
* properly.
*
* Example:
* .vw1 {width: 20px;}
* .vw2 {width: 40px;}
* ...
* .vw100 {width: 2000px;}
* .vh1 {height: 5px;}
* .vh2 {height: 10px;}
* ...
* .vh100 {height: 500px;}
*
* @returns {String} The concatenated CSS rules in string format.
*/
var createCSSRules = function() {
var computedHeight = (vunit.viewportSize.height / 100);
var computedWidth = (vunit.viewportSize.width / 100);
var vmin = Math.min(computedWidth, computedHeight);
var vmax = Math.max(computedWidth, computedHeight);
var map = vunit.options.CSSMap;
var CSSRules = '';
var value = 0;
// Loop through all selectors passed on the CSSMap option
for (var selector in map) {
var property = map[selector].property;
// Adds rules from className0 to className100 to the stylesheet
for (var range = 0; range <= 100; range=range+0.01) {
//Round the range to 2 digitss Decimal. Result= 1.00
var rangeString= new String(range.toFixed(2));
//Replace the dot for _ why? for name in this way className1_03
var rangeValue=rangeString.replace('.','_');
// If range is 10.00 let is round for get className1
if(rangeString.indexOf('.00')>0){
rangeValue=Math.round(range);
}
// Checks what to base the value on (viewport width/height or vmin/vmax)
switch (map[selector].reference) {
case 'vw':
value = computedWidth * range;
break;
case 'vh':
value = computedHeight * range;
break;
case 'vmin':
value = vmin * range;
break;
case 'vmax':
value = vmax * range;
break;
}
// Simple templating syntax
var CSSRuleTemplate = '_SELECTOR__RANGE_{_PROPERTY_:_VALUE_px}\n';
CSSRules += CSSRuleTemplate.replace('_SELECTOR_', selector)
.replace('_RANGE_', rangeValue)
.replace('_PROPERTY_', property)
.replace('_VALUE_', value);
} // end 1-100 range loop
} // end CSSMap selectors loop
return CSSRules;
};
/**
* @function appendCSSRulesToStylesheet
* Appends the created CSS rules (string) to the empty stylesheet.
*
* @param {String} CSSRules A string containing all the calculated CSS rules.
* @param {HTMLStyleElement} stylesheet An empty stylesheet object to hold the rules.
*/
var appendCSSRulesToStylesheet = function(CSSRules, stylesheet) {
// IE < 8 checking
if (stylesheet.styleSheet) {
stylesheet.styleSheet.cssText = CSSRules;
} else {
stylesheet.appendChild(doc.createTextNode(CSSRules));
}
};
/**
* @function appendStylesheetOnHead
* Appends the stylesheet to the <head> element once the CSS rules are created.
*
* @param {HTMLStyleElement} stylesheet A populated stylesheet object.
*/
var appendStylesheetOnHead = function(stylesheet) {
// Borrowed head detection from restyle.js - thanks, Andrea!
// https://github.com/WebReflection/restyle/blob/master/src/restyle.js
var head = doc.head || doc.getElementsByTagName('head')[0] || doc.documentElement;
// Grabs the previous stylesheet
var legacyStylesheet = doc.getElementById(vunit.options.stylesheetId);
// Removes the previous stylesheet from the head, if any
if (legacyStylesheet) {
head.removeChild(legacyStylesheet);
}
// Add the new stylesheet to the head
head.appendChild(stylesheet);
};
/**
* @function calculateViewportSize
* Calculates the size of the viewport.
*
* @returns {Object} An object containing the dimensions of the viewport.
*
* Example:
* return {
* width: 768,
* height: 1024
* }
*/
var calculateViewportSize = function() {
var viewportSize = {
height: doc.documentElement.clientHeight,
width: doc.documentElement.clientWidth
};
return viewportSize;
};
};
})(window, document);