forked from glitchdotcom/solari-board
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolari.js
More file actions
410 lines (370 loc) · 16.7 KB
/
Copy pathsolari.js
File metadata and controls
410 lines (370 loc) · 16.7 KB
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
/*!
* Solari Board jQuery App
* http://github.com/FogCreek/solari-board
*
* Uses jquery.transit.js:
* http://ricostacruz.com/jquery.transit/
*
* date.js:
* http://www.datejs.com/
*
*
* Copyright © 2013 Fog Creek Software, Inc. All rights reserved.
*
* Released under the MIT license
*
* INSTRUCTIONS:
* The solari board app takes an arbitrary json payload from a post command to target url via jsonp (wrapped in a function call)
* Currently, the solari board assumes a json structure in the following format:
* [
* {'sDate':'today','sTime':'13:30','sDeparture':'foo@example.com','nStatus':1,'nTrack':17, 'fLight':true},
* {'sDate':'yesterday','sTime':'16:00','sDeparture':'bar@example.com','nStatus':2,'nTrack':19, 'fLight':false},
* {'sDate':'July 8th, 2013','sTime':'16:30','sDeparture':'baz@example.com','nStatus':2,'nTrack':23, 'fLight':false}
* ]
*
* The nStatus field is only used if status_override = false.
*/
// some constants and enums
var RATE_VARIANCE = 8; // for determining random animation rate in milliseconds
var RATE_BASE = 8; // for determining random animation rate in milliseconds
var BOARD_ROWS = 8; // total number of rows displayed on the solari board
var SECOND_SECTION_START = 8; // the first row that contains a next due case
var LETTER_HEIGHT = 26; // height of a single letter frame (in pixels) in the letter image
var FIRST_CHAR_CODE = 32; // the first ASCII character that is represented in the letter image
var LAST_CHAR_CODE = 96; // the last ASCII character that is represented in the letter image
var CHAR_FACTOR = 2; // every N character in the letter image is a "real" character
var IMAGE_HEIGHT = 20; // height of a single product or status image frame (in pixels)
var IMAGE_FACTOR = 2; // every N picture in the letter image is a "real" image (i.e., not an in-between frame)
var DEPARTURE_BOXES = 25; // number of letter boxes displayed in the departure column
var TIME_BOXES = 4; // number of letter boxes displayed in the time column
var TRACK_BOXES = 2; // number of letter boxes displayed in the track column
var REFRESH_TIME = 60; //refresh time in seconds
var EMPTY_ROW = {
"sTime": "",
"sDeparture": "",
"nStatus": 0,
"sStatus": "",
"nTrack" : 0
};
//if true, the status column will be handled automatically according to time and date. false will override status with nStatus from payload
var status_override = true;
var URL = "../example/postJsonp.py"
//used to add extra params that change over time. /example_realtime makes use of this
var URL_SUFFIX = "";
var Status = {
"none": 0,
"all_aboard": 1,
"on_time": 2,
"delayed": 3,
"departed": 4
};
var LAST_STATUS = 4;
var NextDueStatus = ["", "soon", "null", "overdue", ""];
var solari_setup_done = 0;
var syncing = false;
var current_board = [];
//an attempt to reduce slowdown from animations
jQuery.fx.interval = 20;
function ToUpper(code) {
if (code > 96 && code < 123) {
code -= 32;
}
return code;
}
//constructs the solariBoard within the given div. If no parameter is given, adds the board to "body"
function addSolariBoard(divSelector) {
if (solari_setup_done === 1) {
return;
}
if (arguments.length === 0) {
$("body").append("<div id=\"solariBoardDiv\" style=\"width:970px;margin:0 auto;overflow:hidden\"></div>");
divSelector = "#solariBoardDiv";
}
//The html structure of the solari board. This implementation is pretty ugly, but it's a simple, single-append solution.
var $solari = $("<div class=\"column solari_grid\">" +
"<a id='show-solari' href=\"index.html\" onclick=\"localStorage['StopSolari']=0\">Show Solari Board</a>" +
"<div id=\"solari\" class=\"panel\">" +
"<div id=\"departures\">" +
"<header class=\"solari-board-header rounded\"> " +
"<div class=\"solari-board-icon\"> </div>" +
"<div class=\"clockContainer\">" +
"<ul class=\"clockList\">" +
"<li id=\"hours\">12</li>" +
"<li id=\"point\">:</li>" +
"<li id=\"min\">00</li>" +
"<li id=\"ampm\"> pm</li>" +
"</ul>" +
"</div>" +
"<div id=\"next-due\">" +
"<p>Next due:</p>" +
"<div class=\"inner low\">" +
"<span class=\"clock\">00:00</span>" +
"<span class=\"today\"></span>" +
"</div>" +
"</div>" +
"</header>" +
"<ul class=\"solari-board-columns rounded\">" +
"<li class=\"time\">Time</li>" +
"<li class=\"departure\">Departure</li>" +
"<li class=\"status\">Status</li>" +
"<li class=\"track\">Track</li>" +
"</ul>" +
"<ul class=\"solari-board-rows rounded\">" +
"</ul>" +
"</div>" +
"<div id=\"last-updated\">Last updated: <span>n/a</span></div>" +
"</div>" +
"</div>" +
"</div>").html();
//add the board html
$(divSelector).append($solari);
//set up clock
setInterval(function () {
var date = new Date();
// Convert to 12 hour format
var hours = date.getHours();
$("#hours").html(hours === 0 ? 12 : (hours > 12 ? hours - 12 : hours));
// Add a leading zero to the minutes value and am/pm
var minutes = date.getMinutes();
$("#min").html((minutes < 10 ? "0" : "") + minutes);
// Set am/pm
$("#ampm").html(hours < 12 ? " am" : " pm");
}, 15000); // every 15 seconds is plenty accurate
// show the solari board.
if (!localStorage['StopSolari'] || localStorage['StopSolari'] === '0') {
$('#solari').show();
$('#show-solari').hide();
} else {
$('#solari').hide();
$('#show-solari').show();
return;
}
$('li.track').click(function () {
updateSolariBoard();
});
// we want people who don't care about the solari board to be able to hide it.
$('#next-due').click(function () {
localStorage['StopSolari'] = '1';
$('#solari').hide();
$('#show-solari').show();
});
// and show it
var $section;
// build the solari board
for (var add_rows = 0; add_rows < BOARD_ROWS; add_rows++) {
// initialize the board with default "empty" board data objects
current_board[add_rows] = EMPTY_ROW;
if ($section === undefined) {
$section = $('#departures .solari-board-rows');
}
// add a row
$section.append('<li class=board-data id=row' + add_rows + '><ul><li class=time></li><li class=departure></li></li><li class=status><div class=iconbox><div class=status-icon></div></div></li><li class="track"></li><li class=alert><span class="circle"></span></li></ul></li>');
// add the letter boxes in the time column
for (var add_time_col = 0; add_time_col < TIME_BOXES; add_time_col++) {
$('#row' + add_rows + ' li.time').append('<div id=time-row' + add_rows + 'box' + add_time_col + ' class=letterbox></div>');
// insert a dot after the second box
if (add_time_col === 1) {
$('#row' + add_rows + ' li.time').append('<div class=dot>.</div>');
}
}
// add the letter boxes in the middle column
for (var add_cols = 0; add_cols < DEPARTURE_BOXES; add_cols++) {
$('#row' + add_rows + ' li.departure').append('<div id=departure-row' + add_rows + 'box' + add_cols + ' class=letterbox></div>');
}
// add the letter boxes in the track column
for (var add_track_col = 0; add_track_col < TRACK_BOXES; add_track_col++) {
$('#row' + add_rows + ' li.track').append('<div id=track-row' + add_rows + 'box' + add_track_col + ' class=letterbox></div>');
}
}
solari_setup_done = 1;
window.setInterval(function (){updateSolariBoard()}, 1000 * REFRESH_TIME);
updateSolariBoard();
}
function NextDue(id, time, offset, add_class) {
$(id + ' .today').html(offset);
$(id + ' .clock').html(time);
$(id + ' .inner').attr('class', 'inner ' + add_class); // reset the applied classes
}
function updateSolariTable(board){
for (var row = 0; row < BOARD_ROWS; row++) {
if ((board[row] === undefined)) {
// make this an empty row
board[row] = EMPTY_ROW;
}
// change the row
UpdateSolariRow(row, current_board[row], board[row]);
}
// update the current_row board
current_board = board;
}
function UpdateSolariRow(row, current_row, new_row) {
var rate = RATE_BASE + Math.random() * RATE_VARIANCE + Math.random() * RATE_VARIANCE + Math.random() * RATE_VARIANCE;
SpinChars(rate, '#time-row' + row, TIME_BOXES, current_row.sTime.replace(":",""), new_row.sTime.replace(":",""));
SpinChars(rate, '#departure-row' + row, DEPARTURE_BOXES, current_row.sDeparture, new_row.sDeparture);
//turn track numbers into strings for display. Ensure they are always two chars long
current_row.sTrack = current_row === EMPTY_ROW ? "" : current_row.nTrack === -1? "--" : current_row.nTrack.toString().length > 1 ? current_row.nTrack.toString() : "0" + current_row.nTrack.toString();
new_row.sTrack = new_row === EMPTY_ROW ? "" : new_row.nTrack === -1? "--" :new_row.nTrack.toString().length > 1 ? new_row.nTrack.toString() : "0" + new_row.nTrack.toString();
SpinChars(rate, '#track-row' + row, TRACK_BOXES, current_row.sTrack, new_row.sTrack);
SpinImage(rate, '#row' + row + ' .status-icon', current_row.nStatus, new_row.nStatus);
//clear and apply light class
$("#row" + row + " span").attr('class', 'circle');
$("#row" + row + " span").addClass(new_row.bLight ? 'circle-on' : 'circle');
}
function SpinChars(rate, selector_prefix, max_boxes, current_text, new_text) {
//populate each box
var num_spins = 0;
for (var box = 0; box < max_boxes; box++) {
// get the to and from character codes for this box
var to_char_code = ToUpper(((new_text.length > box) ? new_text.charCodeAt(box) : 32));
var from_char_code = ToUpper(((current_text.length > box) ? current_text.charCodeAt(box) : 32));
var final_pos = '';
if (from_char_code > to_char_code) {
num_spins = ((LAST_CHAR_CODE - from_char_code) + (to_char_code - FIRST_CHAR_CODE)) * CHAR_FACTOR;
final_pos = ((LETTER_HEIGHT * (to_char_code - FIRST_CHAR_CODE)) * CHAR_FACTOR) * -1;
} else {
num_spins = (to_char_code - from_char_code) * CHAR_FACTOR;
}
var selector = selector_prefix + 'box' + box; // add the box part
SpinIt(selector, num_spins, rate, LETTER_HEIGHT, final_pos);
}
}
function SpinImage(rate, selector, from_pos, to_pos) {
var final_pos = '';
var num_spins = 0;
if (from_pos > to_pos) {
num_spins = (((LAST_STATUS - from_pos) + to_pos) * IMAGE_FACTOR);
final_pos = ((IMAGE_HEIGHT * to_pos) * IMAGE_FACTOR) * -1;
} else {
num_spins = ((to_pos - from_pos) * IMAGE_FACTOR);
}
if (from_pos === 4 && to_pos === 0) {
num_spins = 8;
}
//unless we're not moving at all, make the image go 'round 8 more times that it needs to, otherwise it finishes too fast.
if (num_spins !== 0) {
$('audio#solari-audio')[0].play();
num_spins +=80;
}
SpinIt(selector, num_spins, rate, IMAGE_HEIGHT, final_pos);
}
function SpinIt(selector, num_spins, rate, pixel_distance, final_pos) {
var bpX = $(selector).css('backgroundPosition').split(' ')[0];
var bpY = $(selector).css('backgroundPosition').split(' ')[1];
var updateBpY = function (yDelta) {
bpY = (parseFloat(bpY) + yDelta) + 'px';
return bpX + ' ' + bpY;
};
for (var ii = 0; ii < num_spins; ii++) {
$(selector).transition(
{backgroundPosition: updateBpY(-(pixel_distance * 2))},
{duration: 1, easing: "linear"}
);
$(selector).transition(
{backgroundPosition: updateBpY(1)},
{duration: rate, easing: "linear"}
);
// on the very last iteration, use a call back to set the background position to the "real" position
var f = function () {};
if ((final_pos !== '') && (ii === (num_spins-1))) {
f = function() {
$(selector).css('backgroundPosition', bpX + ' ' + final_pos);
};
}
$(selector).transition({backgroundPosition: updateBpY((pixel_distance - 1))}, 1, f);
}
}
function GetFailBoard() {
var fail_whale = [];
fail_whale[0] = " v v v";
fail_whale[1] = " ! ! v ! v";
fail_whale[2] = " ! .-, ! ! !";
fail_whale[3] = " .--./ / ! _.---.!";
fail_whale[4] = " '-. (__..-\" \\";
fail_whale[5] = " \\ & !";
fail_whale[6] = " ',.__. ,__.-'/";
fail_whale[7] = " '--/_.'----''";
var board = [];
// update each row on the board
for (var row = 0; row < BOARD_ROWS; row++) {
board[row] = {
"sTime": "",
"sDeparture": fail_whale[row],
"nStatus": 0,
"nTrack": 0
};
}
return board;
}
function updateSolariBoard() {
if (syncing) {
return;
}
syncing = true;
$.getJSON(URL + (URL.indexOf("?") === -1 ? '?' : '&') + "callback=?" + URL_SUFFIX, function(new_board) {
syncing = false;
if (new_board === null) {
//the last updated footer won't get refreshed, but if data is null, it probably shouldn't
return;
}
//redraw label if recovering from a fail
$("ul.solari-board-columns li.departure").text("Departure");
if (new_board.length === 0) {
clearBoard();
} else {
//the next due box should display information on the row for which time info is available, which may not be from the first case
var i, time;
for (i=0; i < BOARD_ROWS; i++) {
time = new_board[i].sTime;
if (typeof time !== "undefined" && time !== "")
break;
}
var next_due_row = new_board[i];
if (time) {
var timeDelta = Date.parse(next_due_row.sDate + ", " + time).getTime() - new Date().getTime();
var nOffset = timeDelta > 0 ? Math.floor(timeDelta / (1000 * 60 * 60 * 24)) : Math.ceil(timeDelta / (1000 * 60 * 60 * 24)); //divide by miliseconds per day and round to zero
var sOffset = (nOffset === 0 ? "" : nOffset.toString() + "d"); //if next due is not today, append a "d"
if(status_override) {
var hrsDelta = Number(time.substring(0,2)) - new Date().getHours();
nOffset += timeDelta < 0 ? -1 : 0; // if the time difference is negative, which means we are within 24 hours of due, so reduce day offset by 1
if (nOffset < 0) {
new_board[0].nStatus = 3; // if we've past the due date
} else if (nOffset === 0 && hrsDelta < 2 && hrsDelta >= 0 ) {
new_board[0].nStatus = 1; //due within 2 hours
} else {
new_board[0].nStatus = 2;
}
}
// add the appropriate class based on status. If no data, green.
var status_class = (new_board[0] === EMPTY_ROW ? "later" : NextDueStatus[next_due_row.nStatus])
NextDue("#next-due", time, sOffset, status_class);
} else {
NextDue("#next-due", '00:00', '', '');
}
//now that the nStatus values have been set, update the board
updateSolariTable(new_board);
}
// update last refresh time text
$('#last-updated span').fadeOut("slow", function() {
var now = new Date();
$('#last-updated span').html(now.toLocaleString());
}).fadeIn("slow");
}).error(function () {
syncing = false;
updateSolariTable(GetFailBoard());
NextDue("#next-due", '-FA1L-', '', '');
$("ul.solari-board-columns li.departure").text("FAIL WHALE");
});
}
function clearBoard() {
//stop all animations
$(".time").children().stop(true, true);
$(".departure").children().stop(true, true);
$(".status").children().stop(true, true);
$(".track").children().stop(true, true);
//clear the next due and all rows
NextDue("#next-due", '00:00', '', '');
for (var r = 0; r < BOARD_ROWS; r++) {
UpdateSolariRow(r, current_board[r], EMPTY_ROW);
current_board[r] = EMPTY_ROW;
}
}