-
Notifications
You must be signed in to change notification settings - Fork 29
/
index.js
executable file
·379 lines (330 loc) · 11.6 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
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
'use strict';
var configPageHtml = require('./tmp/config-page.html');
var toSource = require('tosource');
var standardComponents = require('./src/scripts/components');
var deepcopy = require('deepcopy/build/deepcopy.min');
var version = require('./package.json').version;
var messageKeys = require('message_keys');
/**
* @param {Array} config - the Clay config
* @param {function} [customFn] - Custom code to run from the config page. Will run
* with the ClayConfig instance as context
* @param {Object} [options] - Additional options to pass to Clay
* @param {boolean} [options.autoHandleEvents=true] - If false, Clay will not
* automatically handle the 'showConfiguration' and 'webviewclosed' events
* @param {*} [options.userData={}] - Arbitrary data to pass to the config page. Will
* be available as `clayConfig.meta.userData`
* @constructor
*/
function Clay(config, customFn, options) {
var self = this;
if (!Array.isArray(config)) {
throw new Error('config must be an Array');
}
if (customFn && typeof customFn !== 'function') {
throw new Error('customFn must be a function or "null"');
}
options = options || {};
self.config = deepcopy(config);
self.customFn = customFn || function() {};
self.components = {};
self.meta = {
activeWatchInfo: null,
accountToken: '',
watchToken: '',
userData: {}
};
self.version = version;
/**
* Populate the meta with data from the Pebble object. Make sure to run this inside
* either the "showConfiguration" or "ready" event handler
* @return {void}
*/
function _populateMeta() {
self.meta = {
activeWatchInfo: Pebble.getActiveWatchInfo && Pebble.getActiveWatchInfo(),
accountToken: Pebble.getAccountToken(),
watchToken: Pebble.getWatchToken(),
userData: deepcopy(options.userData || {})
};
}
// Let Clay handle all the magic
if (options.autoHandleEvents !== false && typeof Pebble !== 'undefined') {
Pebble.addEventListener('showConfiguration', function() {
_populateMeta();
Pebble.openURL(self.generateUrl());
});
Pebble.addEventListener('webviewclosed', function(e) {
if (!e || !e.response) { return; }
// Send settings to Pebble watchapp
Pebble.sendAppMessage(self.getSettings(e.response), function() {
console.log('Sent config data to Pebble');
}, function(error) {
console.log('Failed to send config data!');
console.log(JSON.stringify(error));
});
});
} else if (typeof Pebble !== 'undefined') {
Pebble.addEventListener('ready', function() {
_populateMeta();
});
}
/**
* If this function returns true then the callback will be executed
* @callback _scanConfig_testFn
* @param {Clay~ConfigItem} item
*/
/**
* @callback _scanConfig_callback
* @param {Clay~ConfigItem} item
*/
/**
* Scan over the config and run the callback if the testFn resolves to true
* @private
* @param {Clay~ConfigItem|Array} item
* @param {_scanConfig_testFn} testFn
* @param {_scanConfig_callback} callback
* @return {void}
*/
function _scanConfig(item, testFn, callback) {
if (Array.isArray(item)) {
item.forEach(function(item) {
_scanConfig(item, testFn, callback);
});
} else if (item.type === 'section') {
_scanConfig(item.items, testFn, callback);
} else if (testFn(item)) {
callback(item);
}
}
// register standard components
_scanConfig(self.config, function(item) {
return standardComponents[item.type];
}, function(item) {
self.registerComponent(standardComponents[item.type]);
});
// validate config against teh use of appKeys
_scanConfig(self.config, function(item) {
return item.appKey;
}, function() {
throw new Error('appKeys are no longer supported. ' +
'Please follow the migration guide to upgrade your project');
});
}
/**
* Register a component to Clay.
* @param {Object} component - the clay component to register
* @param {string} component.name - the name of the component
* @param {string} component.template - HTML template to use for the component
* @param {string|Object} component.manipulator - methods to attach to the component
* @param {function} component.manipulator.set - set manipulator method
* @param {function} component.manipulator.get - get manipulator method
* @param {Object} [component.defaults] - template defaults
* @param {function} [component.initialize] - method to scaffold the component
* @return {boolean} - Returns true if component was registered correctly
*/
Clay.prototype.registerComponent = function(component) {
this.components[component.name] = component;
};
/**
* Generate the Data URI used by the config Page with settings injected
* @return {string}
*/
Clay.prototype.generateUrl = function() {
var settings = {};
var emulator = !Pebble || Pebble.platform === 'pypkjs';
var returnTo = emulator ? '$$$RETURN_TO$$$' : 'pebblejs:https://close#';
try {
settings = JSON.parse(localStorage.getItem('clay-settings')) || {};
} catch (e) {
console.error(e.toString());
}
var compiledHtml = configPageHtml
.replace('$$RETURN_TO$$', returnTo)
.replace('$$CUSTOM_FN$$', toSource(this.customFn))
.replace('$$CONFIG$$', toSource(this.config))
.replace('$$SETTINGS$$', toSource(settings))
.replace('$$COMPONENTS$$', toSource(this.components))
.replace('$$META$$', toSource(this.meta));
// if we are in the emulator then we need to proxy the data via a webpage to
// obtain the return_to.
// @todo calculate this from the Pebble object or something
if (emulator) {
return Clay.encodeDataUri(
compiledHtml,
'https://clay.pebble.com.s3-website-us-west-2.amazonaws.com/#'
);
}
return Clay.encodeDataUri(compiledHtml);
};
/**
* Parse the response from the webviewclosed event data
* @param {string} response
* @param {boolean} [convert=true]
* @returns {Object}
*/
Clay.prototype.getSettings = function(response, convert) {
// Decode and parse config data as JSON
var settings = {};
response = response.match(/^\{/) ? response : decodeURIComponent(response);
try {
settings = JSON.parse(response);
} catch (e) {
throw new Error('The provided response was not valid JSON');
}
// flatten the settings for localStorage
var settingsStorage = {};
Object.keys(settings).forEach(function(key) {
if (typeof settings[key] === 'object' && settings[key]) {
settingsStorage[key] = settings[key].value;
} else {
settingsStorage[key] = settings[key];
}
});
localStorage.setItem('clay-settings', JSON.stringify(settingsStorage));
return convert === false ? settings : Clay.prepareSettingsForAppMessage(settings);
};
/**
* Updates the settings with the given value(s).
*
* @signature `clay.setSettings(key, value)`
* @param {String} key - The property to set.
* @param {*} value - the value assigned to _key_.
* @return {undefined}
*
* @signature `clay.setSettings(settings)`
* @param {Object} settings - an object containing the key/value pairs to be set.
* @return {undefined}
*/
Clay.prototype.setSettings = function(key, value) {
var settingsStorage = {};
try {
settingsStorage = JSON.parse(localStorage.getItem('clay-settings')) || {};
} catch (e) {
console.error(e.toString());
}
if (typeof key === 'object') {
var settings = key;
Object.keys(settings).forEach(function(key) {
settingsStorage[key] = settings[key];
});
} else {
settingsStorage[key] = value;
}
localStorage.setItem('clay-settings', JSON.stringify(settingsStorage));
};
/**
* @param {string} input
* @param {string} [prefix='data:text/html;charset=utf-8,']
* @returns {string}
*/
Clay.encodeDataUri = function(input, prefix) {
prefix = typeof prefix !== 'undefined' ? prefix : 'data:text/html;charset=utf-8,';
return prefix + encodeURIComponent(input);
};
/**
* Converts the val into a type compatible with Pebble.sendAppMessage().
* - Strings will be returned without modification
* - Numbers will be returned without modification
* - Booleans will be converted to a 0 or 1
* - Arrays that contain strings will be returned without modification
* eg: ['one', 'two'] becomes ['one', 'two']
* - Arrays that contain numbers will be returned without modification
* eg: [1, 2] becomes [1, 2]
* - Arrays that contain booleans will be converted to a 0 or 1
* eg: [true, false] becomes [1, 0]
* - Arrays must be single dimensional
* - Objects that have a "value" property will apply the above rules to the type of
* value. If the value is a number or an array of numbers and the optional
* property: "precision" is provided, then the number will be multiplied by 10 to
* the power of precision (value * 10 ^ precision) and then floored.
* Eg: 1.4567 with a precision set to 3 will become 1456
* @param {number|string|boolean|Array|Object} val
* @param {number|string|boolean|Array} val.value
* @param {number|undefined} [val.precision=0]
* @returns {number|string|Array}
*/
Clay.prepareForAppMessage = function(val) {
/**
* moves the decimal place of a number by precision then drop any remaining decimal
* places.
* @param {number} number
* @param {number} precision - number of decimal places to move
* @returns {number}
* @private
*/
function _normalizeToPrecision(number, precision) {
return Math.floor(number * Math.pow(10, precision || 0));
}
var result;
if (Array.isArray(val)) {
result = [];
val.forEach(function(item, index) {
result[index] = Clay.prepareForAppMessage(item);
});
} else if (typeof val === 'object' && val) {
if (typeof val.value === 'number') {
result = _normalizeToPrecision(val.value, val.precision);
} else if (Array.isArray(val.value)) {
result = val.value.map(function(item) {
if (typeof item === 'number') {
return _normalizeToPrecision(item, val.precision);
}
return item;
});
} else {
result = Clay.prepareForAppMessage(val.value);
}
} else if (typeof val === 'boolean') {
result = val ? 1 : 0;
} else {
result = val;
}
return result;
};
/**
* Converts a Clay settings dict into one that is compatible with
* Pebble.sendAppMessage(); It also uses the provided messageKeys to correctly
* assign arrays into individual keys
* @see {prepareForAppMessage}
* @param {Object} settings
* @returns {{}}
*/
Clay.prepareSettingsForAppMessage = function(settings) {
// flatten settings
var flatSettings = {};
Object.keys(settings).forEach(function(key) {
var val = settings[key];
var matches = key.match(/(.+?)(?:\[(\d*)\])?$/);
if (!matches[2]) {
flatSettings[key] = val;
return;
}
var position = parseInt(matches[2], 10);
key = matches[1];
if (typeof flatSettings[key] === 'undefined') {
flatSettings[key] = [];
}
flatSettings[key][position] = val;
});
var result = {};
Object.keys(flatSettings).forEach(function(key) {
var messageKey = messageKeys[key];
var settingArr = Clay.prepareForAppMessage(flatSettings[key]);
settingArr = Array.isArray(settingArr) ? settingArr : [settingArr];
settingArr.forEach(function(setting, index) {
result[messageKey + index] = setting;
});
});
// validate the settings
Object.keys(result).forEach(function(key) {
if (Array.isArray(result[key])) {
throw new Error('Clay does not support 2 dimensional arrays for item ' +
'values. Make sure you are not attempting to use array ' +
'syntax (eg: "myMessageKey[2]") in the messageKey for ' +
'components that return an array, such as a checkboxgroup');
}
});
return result;
};
module.exports = Clay;