Repository navigation
Expand file tree
/
Copy pathmouse-speak.js
More file actions
616 lines (509 loc) · 16.4 KB
/
Copy pathmouse-speak.js
File metadata and controls
616 lines (509 loc) · 16.4 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
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
(function(){
/*
www.pubnub.com - PubNub realtime push service in the cloud.
http://www.pubnub.com/blog/mouse-speak - Mouse Speak
PubNub Real Time Push APIs and Notifications Framework
Copyright (c) 2010 Stephen Blum
http://www.google.com/profiles/blum.stephen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
var db = this['localStorage'],
cookie = {
get : function(key) {
if (db) return db.getItem(key);
if (document.cookie.indexOf(key) == -1) return null;
return ((document.cookie||'').match(
RegExp(key+'=([^;]+)')
)||[])[1] || null;
},
set : function( key, value ) {
if (db) return db.setItem( key, value );
document.cookie = key + '=' + value +
'; expires=Thu, 1 Aug 2030 20:00:00 UTC; path=/';
}
};
var bind = PUBNUB.bind
, css = PUBNUB.css
, body = PUBNUB.search('body')[0]
, doc = document.documentElement
, now = function(){return+new Date}
, mice = {}
, channel = 'mouse-speak'
, mousefade = 9000 // Time before user is considered Inactive
, textbox = PUBNUB.create('input')
, focused = 0 // Focused on Textbox?
, lastpos = [] // Last Sent Position
, lasttxt = '' // Last Sent Text
, sentcnt = 0 // Number of Messages Sent
, uuid = cookie.get('uuid') || 0 // User Identification
, wait = 100 // Publish Rate Limit (Time Between Data Push)
, maxmsg = 34 // Max Message Length
, moffset = 10 // Offset of Mouse Position
, timed = 0 // Timeout for Publish Limiter
, lastsent = 0 // Last Sent Timestamp
, nohtml = /[<>]/g;
var Sprite = {
/**
* Adds to screen and creates DOM Object
*/
create : function(sprite) {
sprite.intervals = {
animate : 0,
move : {}
};
sprite.cell.size = Math.floor(sprite.image.width / sprite.cell.count);
sprite.node = PUBNUB.create('div');
sprite.opacity = sprite.opacity || 1.0;
PUBNUB.css( sprite.node, {
opacity : sprite.opacity,
position : 'absolute',
top : sprite.top,
left : sprite.left ,
width : sprite.cell.size,
height : sprite.image.height,
backgroundRepeat: 'no-repeat',
backgroundImage: 'url(' + sprite.image.url + ')'
} );
Sprite.setframe( sprite, 0 );
Sprite.append(sprite.node);
return sprite;
},
ground : PUBNUB.search('body')[0],
append : function(node) {
Sprite.ground.appendChild(node);
},
setframe : function( sprite, cell, offset ) {
var offset = offset || {};
if (typeof offset.top == 'number')
sprite.image.offset.top = offset.top;
if (typeof offset.left == 'number')
sprite.image.offset.left = offset.left;
PUBNUB.css( sprite.node, {
backgroundPosition : '-' +
(sprite.cell.size * cell + sprite.image.offset.left) +
'px -' + sprite.image.offset.top + 'px'
} );
},
/**
* sprite.animate( [[frame, duration], []...] )
* sprite.animate( [[], [], []] )
* sprite.animate( [[0, .2], [1, .4], [2, .5]] )
*/
animate : function( sprite, pattern, loop, callback, position ) {
// Clear Any Other Animation
if (!position) {
position = 0;
Sprite.stop_animate(sprite);
}
// if last frame, and no loop, then leave, else restart
if (position === pattern.length) {
if (loop === 0) return callback && callback();
else {
loop--;
position = 0;
}
}
// Multi format compatibility ([frame, delay]) or (frame)
var frame = pattern[position][0] || pattern[position]
, delay = pattern[position][1] || .1;
sprite.intervals.animate = setTimeout( function() {
// Update Current Frame
Sprite.setframe( sprite, frame );
// Next Frame
Sprite.animate( sprite, pattern, loop, callback, position + 1 );
}, delay * 1000 );
},
/**
* Move and Animate Combined!!!
*
* sprite.animate( [ [left, top, duration, [animate] ], []...] )
* sprite.animate( [[], [], []] )
* sprite.animate( [[10, 10, .2, [ANIMATEPARAMS], loopanimate ], ... )
* sprite.animate( [[10, 10, .2, [[frame,dur], ...], loopanimate ], ... )
*/
movie : function( sprite, pattern, loop, callback, position ) {
// Clear Any Other Animation
if (!position) {
position = 0;
Sprite.stop_all(sprite);
}
// if last frame, and no loop, then leave, else restart
if (position === pattern.length) {
if (loop === 0) return callback && callback();
else {
loop--;
position = 0;
}
}
// Update Animator
if (pattern[position][2]) Sprite.animate(
sprite,
pattern[position][2],
pattern[position][3] || 0
);
// [{top:0,opacity:.5}, 500, 0, 0],
// Update Mover
Sprite.move(
sprite,
pattern[position][0],
pattern[position][1],
function() {
Sprite.movie( sprite, pattern, loop, callback, position + 1 );
}
);
},
/**
* move sprite from one place to another.
*/
move : function( sprite, properties, duration, callback ) {
var start_time = now();
Sprite.stop_all(sprite);
PUBNUB.each( properties, function( property, value ) {
var current_time = start_time
, end_time = start_time + duration
, start_prop = sprite[property] || 0
, distance = value - start_prop
, update = {}
, ikey = property + value;
Sprite.stop_move( sprite, ikey );
sprite.intervals.move[ikey] = setInterval( function() {
current_time = now();
sprite[property] = (
end_time <= current_time
? value
: ( distance * (current_time - start_time)
/ duration + start_prop )
);
update[property] = sprite[property];
PUBNUB.css( sprite.node, update );
if ( end_time <= current_time && sprite.intervals.move ) {
Sprite.stop_move( sprite, ikey );
callback && callback();
}
}, Math.ceil(1000 / sprite.framerate) );
} );
},
/**
* Stop movie
*/
stop_all : function(sprite) {
clearTimeout(sprite.intervals.animate);
PUBNUB.each( sprite.intervals.move, function( ikey ) {
clearInterval(sprite.intervals.move[ikey]);
} );
},
/**
* Stop move.
*/
stop_move : function( sprite, ikey ) {
clearInterval(sprite.intervals.move[ikey]);
},
/**
* Stop animate.
*/
stop_animate : function(sprite) {
clearTimeout(sprite.intervals.animate);
}
};
/*
Get Mouse/Touch Position
------------------------
Return Touch or Mouse Position... :-)
*/
function get_pos(e) {
var posx = 0
, posy = 0;
if (!e) return [0,0];
var tch = e.touches && e.touches[0]
, tchp = 0;
if (tch) {
PUBNUB.each( e.touches, function(touch) {
posx = touch.pageX;
posy = touch.pageY;
// Send Normal Touch on First Touch
if (!tchp) return;
// Must be more touches!
// send({ 'pageX' : posx, 'pageY' : posy, 'uuid' : uuid+tchp++ });
} );
}
else if (e.pageX) {
posx = e.pageX;
posy = e.pageY;
}
else {try{
posx = e.clientX + body.scrollLeft + doc.scrollLeft;
posy = e.clientY + body.scrollTop + doc.scrollTop;
}catch(e){}}
posx += moffset*2;
posy += moffset;
if (posx <= moffset*2) posx = 0;
if (posy <= moffset) posy = 0;
return [posx, posy];
}
/*
Send (Publish)
--------------
Publishes user's state to the group.
Only send what was changed.
*/
function send(e) {
// Leave if no UUID yet.
if (!uuid) return;
// Get Local Timestamp
var right_now = now()
, mouse = mice[uuid];
// Don't continue if too soon (but check back)
if (lastsent + wait > right_now) {
// Come back and check after waiting.
clearTimeout(timed);
timed = setTimeout( function() {send(e)}, wait );
return 1;
}
// Set Last Sent to Right Now.
lastsent = right_now;
// Capture User Input
var pos = get_pos(e)
, txt = get_txt()
//, xuuid = e['uuid']
, msg = { 'uuid' : /*xuuid ||*/ uuid };
if (!mouse) return user_joined(msg);
// Don't send if no change in Position.
if (!(
lastpos[0] == pos[0] &&
lastpos[1] == pos[1] ||
!pos[0] ||
!pos[1]
)) {
// Update Last Position
lastpos[0] = pos[0];
lastpos[1] = pos[1];
msg['pos'] = pos;
}
// Check Last Sent Text
if (lasttxt != txt || !(sentcnt++ % 3)) {
lasttxt = txt;
msg['txt'] = txt || ' ';
cookie.set( 'mtxt', msg['txt'] );
}
// No point sending nothing.
if (!(msg['txt'] || msg['pos'])) return 1;
// Set so we won't get jittery mice.
msg['c'] = (mice[uuid].last||1) + 2;
PUBNUB.publish({
channel : channel,
message : msg
});
msg['force'] = 1;
user_updated(msg);
return 1;
}
// User Joined
function user_joined(message) {
var pos = message['pos'] || [100,100]
, mouse = Sprite.create({
image : {
url : 'http://www.pubnub.com/static/mouse.png',
width : 600,
height : 30,
offset : {
top : 36,
left : 0
}
},
cell : {
count : 1 // horizontal cell count
},
left : pos[1],
top : pos[0],
framerate : 50
});
// Do something when you mouseover.
if (uuid != message['uuid']) bind( 'mouseover', mouse.node, function() {
Sprite.move( mouse, {
'opacity' : 0.5,
'top' : Math.ceil(Math.random()*150),
'left' : Math.ceil(Math.random()*150)
}, wait );
} );
// Set Prettier Text
PUBNUB.css( mouse.node, {
'fontWeight' : 'bold',
'padding' : '5px 0 0 20px',
'fontSize' : '30px',
'textShadow' : 'rgba(0,0,0,0.5) 1px 1px 2px',
// 'box-shadow' : '1px 1px 5px rgba(0,0,0,0.5)',
// 'border-radius' : '5px',
// '-moz-box-shadow' : '1px 1px 5px rgba(0,0,0,0.5)',
// '-moz-border-radius' : '5px',
//'-webkit-box-shadow' : '1px 1px 5px rgba(0,0,0,0.5)',
//'-webkit-border-radius' : '5px',
'-webkit-filter' : 'invert(1)',
//'-webkit-transform' : 'scale(10)',
//'opacity' : 0.0,
//'backgroundColor' : 'rgba(255,255,255,0.8)',
'color' : "#d34"//'#'+(message['uuid']||'000').slice(-6)//'#000'
} );
// Save UUID
PUBNUB.attr( mouse.node, 'uuid', message['uuid'] );
// Save User
mice[message['uuid']] = mouse;
// Update User
user_updated(message);
}
// User has Moved Mouse or Typed
function user_updated(message) {
var pos = message['pos']
, click = message['click']
, txt = message['txt']
, last = message['c']
, force = message['force']
, tuuid = message['uuid']
, mouse = mice[tuuid];
if (!mouse) return user_joined(message);
// Is this a click message?
if (click) return user_click(pos);
// Common to reset value if page reloaded
if (last && (mouse.last||0) - last > 100)
mouse.last = last;
// Self
///if (force) mouse.last = last;
// Prevent Jitter from Early Publish
if (
!force &&
last &&
mouse.last &&
mouse.last > last
) return;
// Set last for the future.
if (last) mouse.last = last;
// Update Text Display
if (txt) mouse.node.innerHTML = txt.replace( nohtml, '' );
// Set Delay to Fade User Out on No Activity.
mouse.timerfade && clearTimeout(mouse.timerfade);
mouse.timerfade = setTimeout( function() {
PUBNUB.css( mouse.node, { 'opacity' : 0.4 } );
clearTimeout(mouse.timerfade);
mouse.timerfade = setTimeout( function() {
PUBNUB.css( mouse.node, { 'display' : 'none' } );
}, mousefade );
}, mousefade );
// Reshow if hidden.
PUBNUB.css( mouse.node, {
'display' : 'block',
'opacity' : 1.0
} );
// Move Player.
if (pos) {
Sprite.move( mouse, {
'top' : pos[1],
'left' : pos[0]
}, wait - 10 );
// Change Direction
if (pos[0] > mouse.left)
Sprite.setframe( mouse, 0, { top : 36 } );
else if (pos[0] < mouse.left)
Sprite.setframe( mouse, 0, { top : 1 } );
}
}
function send_click(e) {
var pos = get_pos(e)
, msg = {
'pos' : pos,
'click' : 1,
'uuid' : uuid
};
if (!(pos[1] && pos[0])) return 1;
PUBNUB.publish({
channel : channel,
message : msg
});
msg['force'] = 1;
user_updated(msg);
}
function user_click(pos) {
var click = PUBNUB.create('div');
if (!(pos[1] && pos[0])) return 1;
// Create Click
PUBNUB.css( click, {
'position' : 'absolute',
'background' : 'transparent url(http://www.pubnub.com/static/mouse-click.png) no-repeat',
'top' : pos[1],
'left' : pos[0],
'width' : 13,
'height' : 13
} );
// Append Click
body.appendChild(click);
return 1;
}
// Receive Mice Friends
PUBNUB.subscribe( { channel : channel }, user_updated );
// Capture Text Journey
function keystroke( e, key ) {setTimeout(function(){
if (',13,27,'.indexOf(','+key+',') !== -1) textbox.value = ' ';
send(e);
},20);return 1}
var ignore_keys = ',18,37,38,39,40,20,17,35,36,33,34,16,9,91,';
function focusize() {focused = 1;return 1}
function bluralize(e) {focused = 0; send_click(e); return 1}
function monopuff(e) {
var key = e.keyCode;
if (ignore_keys.indexOf(','+key+',') !== -1)
return 1;
if (!focused)
textbox.focus();
keystroke( e, key );
return 1
}
function get_txt() {
var val = (textbox.value||'')
, len = val.length;
if (len > maxmsg) {
textbox.value = val = '...' + val.slice( -maxmsg );
}
else if(val.indexOf(init_text) != -1 && len > init_text.length) {
textbox.value = val = val.replace( init_text, '' );
}
return val;
}
// Load UUID and Send First Message
if (!uuid) PUBNUB.uuid(function(id){
// Get UUID
uuid = id;
// Save your UUID
cookie.set( 'uuid', uuid );
// User Landed on Page (First Message)
setTimeout( function(){send({})}, wait );
});
// Add Input Textbox
PUBNUB.css( textbox, {
'position' : 'absolute',
'top' : -10000,
'left' : 0
} );
var init_text = 'TYPE!!!';
textbox.value = cookie.get('mtxt') || init_text;
body.appendChild(textbox);
// Setup Events
bind( 'mousemove', document, send );
bind( 'touchmove', document, send );
bind( 'touchstart', document, send );
bind( 'touchend', document, send );
bind( 'keydown', document, monopuff );
//bind( 'mousedown', document, bluralize );
//bind( 'click', document, bluralize );
// Setup For Any Input Event.
PUBNUB.each( PUBNUB.search('input'), function(input) {
bind( 'focus', input, focusize );
bind( 'blur', input, bluralize );
} );
})()