forked from jasonkneen/UTiL
/
ui.js
291 lines (239 loc) · 7.83 KB
/
ui.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
287
288
289
290
291
var _ = require((typeof ENV_TEST === 'boolean') ? 'alloy' : 'underscore')._;
/**
* addEventListenerSingle extends the UI Button with a click handler that only executes once
* even though the user taps multiple times. It resets once it has executed the clickhandler.
*
* <Button module="xp.ui" id="btnName" />
* $.btnName.addEventListenerSingle(onlyFiresWhenPreviousIsDone);
*
* addEventListenerOnce will only execure the callback once, and remove it afterwards.
*
* $.btnName.addEventListenerOnce("longpress", onlyFiresOnce);
*
* @param {Object} args
*/
exports.createButton = function (args) {
var $button = Ti.UI.createButton(args);
$button.executed = false;
$button.addEventListenerSingle = function (func) {
if (!_.isFunction(func)) {
Ti.API.error("[XP.UI Button] ERROR: Click handler must be a function");
return;
}
$button.addEventListener('click', function (e) {
if (!e.source.executed) {
e.source.executed = true;
// run once call stack is cleared
_.defer(function () {
func(e);
e.source.executed = false;
});
}
});
};
$button.addEventListenerOnce = function (eventName, func) {
var triggered = false;
if (!_.isFunction(func)) {
Ti.API.error("[XP.UI Button] ERROR: Single Event Listener callback must be a function");
return;
}
function singularCallback(e) {
if (!triggered) {
triggered = true;
// run once call stack is cleared
_.defer(function () {
func(e);
$button.removeEventListener(eventName, singularCallback);
});
}
}
$button.addEventListener(eventName, singularCallback);
};
return $button;
};
/**
* Creates a Ti.UI.View with additional option to use a backgroundImage with
* backgroundSize:cover like CSS does.
*
* @param {Dictionary} args
* @return {Ti.UI.View}
*/
exports.createView = function (args) {
// view using backgroundSize
if (args.backgroundSize && args.backgroundSize === 'cover' && args.backgroundImage && typeof args.backgroundImage === 'string') {
// rename as private property
args._backgroundImage = args.backgroundImage;
delete args.backgroundImage;
// target id available to possibly skip postlayout
if (args.backgroundTarget) {
// rename as private property
args._backgroundTarget = args.backgroundTarget;
delete args.backgroundTarget;
var targetFile = _getTargetFile(args._backgroundImage, args._backgroundTarget);
// target exists
if (targetFile.exists()) {
// use & return
args.backgroundImage = targetFile.nativePath;
return Ti.UI.createView(args);
}
}
var view = Ti.UI.createView(args);
// check for backgroundRotate
if (args.backgroundRotate && args.backgroundRotate === 'true') {
view._backgroundRotate = args.backgroundRotate;
delete args.backgroundRotate;
}
// no need to wait for postlayout if we know target absolute width & height
if (_isAbsolute(args.width) && _isAbsolute(args.height)) {
_setBackgroundImage(view, args.width, args.height);
} else {
view.addEventListener('postlayout', _onPostLayout);
}
return view;
}
// regular view
else {
return Ti.UI.createView(args);
}
};
/**
* Returns the file that would keep the resized backgroundImage.
* @param {String} originalPath
* @param {String} targetId
* @return {Ti.Filesystem.File}
*/
function _getTargetFile(originalPath, targetId, parent) {
var targetFilename = Ti.Utils.sha1(originalPath + '_' + targetId) + originalPath.substr(originalPath.lastIndexOf('.'));
var targetFile = Ti.Filesystem.getFile(parent || Ti.Filesystem.applicationCacheDirectory, targetFilename);
return targetFile;
}
/**
* Generates or loads a resized backgroundImage, respecting the original aspect
* ratio while making sure it covers the whole view.
* @param {Ti.UI.View} view
* @param {Number} targetWidth
* @param {Number} targetHeight
*/
function _setBackgroundImage(view, targetWidth, targetHeight) {
var originalPath = view._backgroundImage;
var targetId = view._backgroundTarget || targetWidth + '_' + targetHeight;
var originalFile,
targetFile = _getTargetFile(originalPath, targetId);
if (originalPath.charAt(0) === '/') {
originalPath = originalPath.substr(1);
}
if (!targetFile.exists()) {
if (originalPath.indexOf('://') !== -1) {
originalFile = _getTargetFile(originalPath, 'tmp', Ti.Filesystem.tempDirectory);
var xhr = Ti.Network.createHTTPClient({
onload: function (e) {
if (!originalFile.write(this.responseData)) {
console.error('[UI] Could not write downloaded file to: ' + originalFile.nativePath);
return;
}
_resizeBackgroundImage(view, targetWidth, targetHeight, originalFile, targetFile);
},
onerror: function (e) {
console.error('[UI] Could not downloaded image: ' + e.error);
}
});
xhr.open('GET', originalPath);
xhr.send();
return;
} else {
originalFile = Ti.Filesystem.getFile(originalPath);
_resizeBackgroundImage(view, targetWidth, targetHeight, originalFile, targetFile);
}
} else {
view.backgroundImage = targetFile.nativePath;
}
}
/**
* Resizes the backgroundImage.
* @param {Ti.UI.View} view
* @param {Number} targetWidth
* @param {Number} targetHeight
* @param {String} originalPath
* @param {Ti.Filesystem.File} targetFile
*/
function _resizeBackgroundImage(view, targetWidth, targetHeight, originalFile, targetFile) {
if (!originalFile.exists()) {
console.error('[UI] backgroundImage not found: ' + originalFile.nativePath);
return;
}
// orginal specs
var originalBlob = originalFile.read();
var originalWidth = originalBlob.width;
var originalHeight = originalBlob.height;
var originalRatio = originalWidth / originalHeight;
// target specs (converted to px)
targetWidth = Ti.UI.convertUnits('' + targetWidth, Ti.UI.UNIT_PX);
targetHeight = Ti.UI.convertUnits('' + targetHeight, Ti.UI.UNIT_PX);
var targetRatio = targetWidth / targetHeight;
var resizeWidth, resizeHeight;
// fill width, overflow height
if (targetRatio > originalRatio) {
resizeWidth = targetWidth;
resizeHeight = Math.ceil(resizeWidth / originalRatio);
}
// fill height, overflow width
else {
resizeHeight = targetHeight;
resizeWidth = Math.ceil(resizeHeight * originalRatio);
}
// resize, if neeeded
if (originalWidth !== resizeWidth || originalHeight !== resizeHeight) {
originalBlob = originalBlob.imageAsResized(resizeWidth, resizeHeight);
}
// crop, if needed
if (resizeWidth !== targetWidth || resizeHeight !== targetHeight) {
originalBlob = originalBlob.imageAsCropped({
width: targetWidth,
height: targetHeight
});
}
targetFile.write(originalBlob);
view.backgroundImage = targetFile.nativePath;
}
/**
* Handles the Ti.UI.View.postlayout event, takes the width and height and
* then sets the backgroundImage.
* @param {Ti.Event} e
*/
function _onPostLayout(e) {
var view = e.source;
var size = view.size;
if (view._backgroundRotate) {
// check for both images have been rendered
if (bothOrientationImagesRendered(view, size)) {
view.removeEventListener('postlayout', _onPostLayout);
}
} else {
// remove after the first time
view.removeEventListener('postlayout', _onPostLayout);
}
// continue now that we know width & height
_setBackgroundImage(view, size.width, size.height);
}
/**
* Check if we have rendered an image for portrait and landscape resolution
* @param {Ti.UI.View} view
* @param {Object} size
* @return {Boolean} result
*/
function bothOrientationImagesRendered(view, size) {
var targetFile = _getTargetFile(view._backgroundImage, size.width + '_' + size.height);
var targetFile2 = _getTargetFile(view._backgroundImage, size.height + '_' + size.width);
// both needed to be rendered
if (targetFile.exists() && targetFile2.exists()) {
return true;
}
return false;
}
/**
* Check is a dimension is absolute.
* @param {mixed} Dimension
*/
function _isAbsolute(dimension) {
return dimension && dimension.toString().match(/^[1-9]+[0-9]*[a-z]*$/);
}