forked from leeclarke/DiceCircle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiceCircle.js.bak
448 lines (405 loc) · 14.8 KB
/
diceCircle.js.bak
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
var statusVisible_ = false;
var rollHistory_ = null;
var ROLL_HISTORY = "ROLL_HISTORY";
/**
* Shared state of the app.
* @type {Object.<!string, !string>}
* @private
*/
var state_ = null;
/**
* Describes the shared state of the object.
* @type {Object.<!string, Object.<!string, *>>}
* @private
*/
var metadata_ = null;
/**
* A list of the participants.
* @type {Array.<gapi.hangout.Participant>}
* @private
*/
var participants_ = null;
/**
* The form that contains the status input element.
* @type {Element}
* @private
*/
var statusForm_ = null;
/**
* The element used to input status messages.
* @type {Element}
* @private
*/
var statusInput_ = null;
/**
* The container for the app controls.
* @type {Element}
* @private
*/
var container_ = null;
/**
* Executes the provided function after a minor delay.
* @param {function()} func The function to execute.
*/
function defer(func) {
window.setTimeout(func, 10);
}
/**
* Creates a key for use in the shared state.
* @param {!string} id The user's temporary id.
* @param {!string} key The property to create a key for.
* @return {!string} A new key for use in the shared state.
*/
function makeUserKey(id, key) {
return id + ':' + key;
}
/**
* Makes an RPC call to store the given value(s) in the shared state.
* @param {!(string|Object.<!string, !string>)} keyOrState Either an object
* denoting the desired key value pair(s), or a single string key.
* @param {!string=} opt_value If keyOrState is a string, the associated value.
*/
var saveValue = null;
/**
* Makes an RPC call to remove the given value(s) from the shared state.
* @param {!(string|Array.<!string>)} keyOrListToRemove A single key
* or an array of strings to remove from the shared state.
*/
var removeValue = null;
/**
* Makes an RPC call to add and/or remove the given value(s) from the shared
* state.
* @param {?(string|Object.<!string, !string>)} addState Either an object
* denoting the desired key value pair(s), or a single string key.
* @param {?(string|Object.<!string, !string>)=} opt_removeState A list of keys
* to remove from the shared state.
*/
var submitDelta = null;
(function() {
/**
* Packages the parameters into a delta object for use with submitDelta.
* @param {!(string|Object.<!string, !string>)} Either an object denoting
* the desired key value pair(s), or a single string key.
* @param {!string=} opt_value If keyOrState is a string, the associated
* string value.
*/
var prepareForSave = function(keyOrState, opt_value) {
var state = null;
if (typeof keyOrState === 'string') {
state = {};
state[keyOrState] = opt_value;
} else if (typeof keyOrState === 'object' && null !== keyOrState) {
// Ensure that no prototype-level properties are hitching a ride.
state = {};
for (var key in keyOrState) {
if (keyOrState.hasOwnProperty(key)) {
state[key] = keyOrState[key];
}
}
} else {
throw 'Unexpected argument.';
}
return state;
};
/**
* Packages one or more keys to remove for use with submitDelta.
* @param {!(string|Array.<!string>)} keyOrListToRemove A single key
* or an array of strings to remove from the shared state.
* @return {!Array.<!string>} A list of keys to remove from the shared state.
*/
var prepareForRemove = function(keyOrListToRemove) {
var delta = null;
if (typeof keyOrListToRemove === 'string') {
delta = [keyOrListToRemove];
} else if (typeof keyOrListToRemove.length === 'number' &&
keyOrListToRemove.propertyIsEnumerable('length')) {
// Discard non-string elements.
for (var i = 0, iLen = keyOrListToRemove.length; i < iLen; ++i) {
if (typeof keyOrListToRemove[i] === 'string') {
delta.push(keyOrListToRemove[i]);
}
}
} else {
throw 'Unexpected argument.';
}
return delta;
};
/**
* Makes an RPC call to add and/or remove the given value(s) from the shared
* state.
* @param {?(string|Object.<!string, !string>)} addState Either an object
* denoting the desired key value pair(s), or a single string key.
* @param {?(string|Object.<!string, !string>)=} opt_removeState A list of
* keys to remove from the shared state.
*/
var submitDeltaInternal = function(addState, opt_removeState) {
gapi.hangout.data.submitDelta(addState, opt_removeState);
};
saveValue = function(keyOrState, opt_value) {
var delta = prepareForSave(keyOrState, opt_value);
if (delta) {
submitDeltaInternal(delta);
}
};
removeValue = function(keyOrListToRemove) {
var delta = prepareForRemove(keyOrListToRemove);
if (delta) {
submitDeltaInternal({}, delta);
}
};
submitDelta = function(addState, opt_removeState) {
if ((typeof addState !== 'object' && typeof addState !== 'undefined') ||
(typeof opt_removeState !== 'object' &&
typeof opt_removeState !== 'undefined')) {
throw 'Unexpected value for submitDelta';
}
var toAdd = addState ? prepareForSave(addState) : {};
var toRemove = opt_removeState ? prepareForRemove(opt_removeState) :
undefined;
submitDeltaInternal(toAdd, toRemove);
};
})();
function addNewDieRoll(dieRoll) {
console.log("New Die roll "+dieRoll);
var newRoll = {
"participant":getUserParticipant(),
"dieRoll":dieRoll
};
rollHistory_.rolls.push(newRoll);
saveValue(ROLL_HISTORY, JSON.stringify(rollHistory_));
}
/**
* @return {Participant} Users hangout object.
*/
function getUserParticipant() {
return gapi.hangout.getParticipantById(gapi.hangout.getParticipantId());
}
function getParticipantName(id) {
for(p=0; p< participants_.length ;p++) {
if(participants_[p].id == id) {
return participants_[p].displayName;
}
}
}
/**
* @param {!string} participantId The temporary id of a Participant.
* @return {string} The status of the given Participant.
*/
function getStatusMessage(participantId) {
return getState(makeUserKey(participantId, 'status'));
}
/**
* Sets the status for the current user.
* @param {!string} message The user's new status.
*/
function setStatusMessage(message) {
saveValue(makeUserKey(getUserHangoutId(), 'status'), message);
}
function setRollHistory() {
var histSerialized = getMetadata(ROLL_HISTORY);
if (typeof histSerialized.value !== 'string') {
rollHistory_ = initRollHistory();
} else if(histSerialized.value === "") {
//Was reset, init
rollHistory_ = initRollHistory();
} else {
rollHistory_ = $.parseJSON(histSerialized.value);
}
}
function initRollHistory() {
return {
"rolls":[]
};
}
/**
* Displays the input allowing a user to set his status.
* @param {!Element} linkElement The link that triggered this handler.
*/
function onSetStatus(linkElement) {
statusVisible_ = true;
statusInput_.fadeIn(500);
$(linkElement).parent('p').hide();
$(linkElement).parent('p').parent().append(statusInput_);
statusInput_.val(getStatusMessage(getUserHangoutId()));
// Since faceIn is a black box, focus & select only if the input is already
// visible.
statusInput_.filter(':visible').focus().select();
}
/**
* Sets the user's status message and hides the input element.
*/
function onSubmitStatus() {
if (statusVisible_) {
statusVisible_ = false;
var statusVal = statusInput_.val();
statusVal = statusVal.length < MAX_STATUS_LENGTH ? statusVal :
statusVal.substr(0, MAX_STATUS_LENGTH);
setStatusMessage(statusVal);
statusForm_.append(statusInput_);
statusInput_.hide();
render();
}
}
/**
* Gets the value of opt_stateKey in the shared state, or the entire state
* object if opt_stateKey is null or not supplied.
* @param {?string=} opt_stateKey The key to get from the state object.
* @return {(string|Object.<string,string>)} A state value or the state object.
*/
function getState(opt_stateKey) {
return (typeof opt_stateKey === 'string') ? state_[opt_stateKey] : state_;
}
/**
* Gets the value of opt_metadataKey in the shared state, or the entire
* metadata object if opt_metadataKey is null or not supplied.
* @param {?string=} opt_metadataKey The key to get from the metadata object.
* @return {(Object.<string,*>|Object<string,Object.<string,*>>)} A metadata
* value or the metadata object.
*/
function getMetadata(opt_metadataKey) {
return (typeof opt_metadataKey === 'string') ? metadata_[opt_metadataKey] :
metadata_;
}
/**
* @return {string} The user's ephemeral id.
*/
function getUserHangoutId() {
return gapi.hangout.getParticipantId();
}
/**
* Renders the app.
*/
function render() {
console.dir(rollHistory_);
$("#group").empty();
for(r =0; r<rollHistory_.rolls.length; r++) {
var rollOutput = "";
var rEntry = rollHistory_.rolls[r];
if(getUserParticipant().id === rEntry.participant.id ) {
rollOutput += "<span><div class='roll_group_name_me'>" + rEntry.participant.displayName + ":</div>"
} else {
rollOutput += "<span><div class='roll_group_name'>" + rEntry.participant.displayName + ":</div>"
}
rollOutput += "<span><div class=\"roll_group_source\"><small><strong>Roll:</strong></small> <a href=\"javascript:doRoll('"+rEntry.dieRoll.dice+"');\"><code>"+rEntry.dieRoll.dice+"</code></a></div>";
rollOutput += '<div class="roll_group_result">' + rEntry.dieRoll.result + "</div></span></span><br>";
$("#group").prepend(rollOutput);
}
//$("#group").prop("scrollHeight");
$("#group").prop("scrollTop", 0);
}
/**
* Syncs local copies of shared state with those on the server and renders the
* app to reflect the changes.
* @param {!Object.<!string, !string>} state The shared state.
* @param {!Object.<!string, Object.<!string, *>>} metadata Data describing the
* shared state.
*/
function updateLocalDataState(state, metadata) {
state_ = state;
metadata_ = metadata;
setRollHistory();
render();
}
/**
* Syncs local copy of the participants list with that on the server and renders
* the app to reflect the changes.
* @param {!Array.<gapi.hangout.Participant>} participants The new list of
* participants.
*/
function updateLocalParticipantsData(participants) {
participants_ = participants;
render();
}
function showUser(){
var user = getUserParticipant();
$("#group").html("Name:" + user.displayName + "<BR>id:" + user.id);
}
/**
* Set up the UI
*/
function prepareAppDOM() {
formulaEL= $("<input id='inp_text' type='text' onkeypress='return inp_keydown(event);' /><button id='inp_go' onclick='go();'>Go!</button>");
helpEL = $("<small>Dice to roll: [<a href='javascript:doHelp();'>Help</a>]</small><br />");
inpEL = $("<div id='inp'>").append(helpEL,formulaEL);
resultsEL = $("<div id='results'></div>");
groupEL = $("<div id='group'></div>");
preEL = $("<div id='pre'></div>");
$.each( specialDiceAbbreviations, function( abbr, type ) {
var btn = $('<button id="pre_d'+abbr+'" onclick="doRoll(\'d'+abbr+'\');">d'+abbr+'</button>');
btn.attr('title',type);
if (specialDiceTypes[type].color) {
btn.css('color',specialDiceTypes[type].color.foreground);
btn.css('background-color',specialDiceTypes[type].color.background);
}
preEL.append(btn);
});
$.each( specialDiceCombos, function( expr, types ) {
var abbrs = expr.split('+');
var spans = [];
var text = "";
$.each( abbrs, function( i, abb ) {
var span = $('<span></span>');
span.text(abb);
if (types[i] && specialDiceTypes[types[i]] && specialDiceTypes[types[i]].color) {
span.css('color',specialDiceTypes[types[i]].color.foreground);
span.css('background-color',specialDiceTypes[types[i]].color.background);
}
spans.push(span.html());
});
text = spans.join('+');
var btn = $('<button id="pre_d'+expr+'" onclick="doRoll(\''+expr+'\');">'+text+'</button>');
btn.attr('title',expr);
preEL.append(btn);
});
preEL.append('<button id="pre_d4" onclick="doRoll(\'1d4\');">d4</button><button id="pre_d6" onclick="doRoll(\'1d6\');">d6</button><button id="pre_d8" onclick="doRoll(\'1d8\');">d8</button><button id="pre_d10" onclick="doRoll(\'1d10\');">d10</button><button id="pre_d12" onclick="doRoll(\'1d12\');">d12</button><button id="pre_d20" onclick="doRoll(\'1d20\');">d20</button><button id="pre_d100" onclick="doRoll(\'1d100\');">d100</button><button id="pre_clear" onclick="doClear(); showUser();">Clear</button>');
jsdiceEl = $("<div id='jsdice' class='hidden'>").append(groupEL,resultsEL,inpEL,preEL);
mainEL = $("<div id='main'>").append(jsdiceEl);
var body = $("body").append(mainEL);
}
function reset() {
rollHistory_ = initRollHistory();
saveValue(ROLL_HISTORY, JSON.stringify(rollHistory_));
}
function activateForm() {
$('#jsdice').show();
var ht = ($('#main').height())-100;
// $('#group').height(ht);
// $('#results').height(ht);
$('#inp_text').focus();
}
(function() {
if (gapi && gapi.hangout) {
var initHangout = function(apiInitEvent) {
if (apiInitEvent.isApiReady) {
if(!rollHistory_) {
rollHistory_ = initRollHistory();
saveValue(ROLL_HISTORY, JSON.stringify(rollHistory_));
}
prepareAppDOM();
activateForm();
gapi.hangout.data.onStateChanged.add(function(stateChangeEvent) {
updateLocalDataState(stateChangeEvent.state,
stateChangeEvent.metadata);
});
gapi.hangout.onParticipantsChanged.add(function(partChangeEvent) {
updateLocalParticipantsData(partChangeEvent.participants);
});
if (!state_) {
var state = gapi.hangout.data.getState();
var metadata = gapi.hangout.data.getStateMetadata();
if (state && metadata) {
updateLocalDataState(state, metadata);
}
}
if (!participants_) {
var initParticipants = gapi.hangout.getParticipants();
if (initParticipants) {
updateLocalParticipantsData(initParticipants);
}
}
gapi.hangout.onApiReady.remove(initHangout);
}
};
gapi.hangout.onApiReady.add(initHangout);
}
})();