This repository has been archived by the owner on Jun 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
5070 lines (4577 loc) · 158 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
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Name of this application, used in the User-Agent
var APP_NAME = "TinodeWeb/0.15";
var KNOWN_HOSTS = {hosted: "api.tinode.co", local: "localhost:8080"};
// Default host name and port to connect to.
var DEFAULT_HOST = KNOWN_HOSTS.hosted;
// var DEFAULT_HOST = KNOWN_HOSTS.local;
// Sound to play on message received.
var POP_SOUND = new Audio('audio/msg.mp3');
// Unicode symbol used to clear objects
var DEL_CHAR = "\u2421";
// API key. Use https://github.com/tinode/chat/tree/master/keygen to generate your own
var API_KEY = "AQEAAAABAAD_rAp4DJh05a1HAwFT3A6K";
// Minimum time between two keypress notifications, milliseconds.
var KEYPRESS_DELAY = 3*1000;
// Delay before sending a {note} for reciving a message, milliseconds.
var RECEIVED_DELAY = 500;
// Delay before sending a read notification, milliseconds.
var READ_DELAY = 1000;
// The shortest allowed tag length. Matches one on the server.
var MIN_TAG_LENGTH = 4;
// Mediaquery breakpoint between desktop and mobile, in px. Should match the value
// in @meadia (max-size: 640px) in base.css
var MEDIA_BREAKPOINT = 640;
// Size of css 'rem' unit in pixels. Default 1rem = 10pt = 13px.
var REM_SIZE = 13;
// Size of the avatar image
var AVATAR_SIZE = 128;
// Number of chat messages to fetch in one call.
var MESSAGES_PAGE = 24;
// Maximum in-band attachment size = 128K (included directly into the message). Increase
// this limit to a greater value in production, if desired. Also increase max_message_size
// in server config.
var MAX_INBAND_ATTACHMENT_SIZE = 1 << 17;
// Absolute maximum attachment size to be used with the server = 8MB. Increase to
// something like 100MB in production.
var MAX_EXTERN_ATTACHMENT_SIZE = 1 << 23;
// Maximum allowed linear dimension of an inline image in pixels. You may want
// to adjust it to 1600 or 2400 for production.
var MAX_IMAGE_SIZE = 768;
// Supported image MIME types and corresponding file extensions.
var SUPPORTED_IMAGE_FORMATS = ['image/jpeg', 'image/gif', 'image/png', 'image/svg', 'image/svg+xml'];
var MIME_EXTENSIONS = ['jpg', 'gif', 'png', 'svg', 'svg'];
// Tinode is defined in 'tinode.js'.
var Drafty = Tinode.Drafty;
// Helper functions for storing values in localStorage.
// By default localStorage can store only strings, not objects or other types.
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObject = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
// Short representation of time in the past.
function shortDateFormat(then) {
var locale = window.navigator.userLanguage || window.navigator.language;
var now = new Date();
if (then.getFullYear() == now.getFullYear()) {
if (then.getMonth() == now.getMonth() && then.getDate() == now.getDate()) {
return then.toLocaleTimeString(locale, {hour12: false, hour: '2-digit', minute: '2-digit'});
} else {
return then.toLocaleDateString(locale,
{hour12: false, month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit'});
}
}
return then.toLocaleDateString(locale,
{hour12: false, year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit'});
}
// Convert a number of bytes to human-readable format.
function bytesToHumanSize(bytes) {
if (!bytes || bytes == 0) {
return '0 Bytes';
}
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
var bucket = Math.min(Math.floor(Math.log2(bytes) / 10) | 0, sizes.length-1);
var count = bytes / Math.pow(1024, bucket);
var round = bucket > 0 ? (count < 3 ? 2 : (count < 30 ? 1 : 0)) : 0;
return count.toFixed(round) + ' ' + sizes[bucket];
}
// Make a data URL from public.photo
function makeImageUrl(photo) {
return (photo && photo.type && photo.data) ?
'data:image/' + photo.type + ';base64,' + photo.data : null;
}
// Calculate linear dimensions for scaling image down to fit under a certain size.
// Returns an object which contains destination sizes, source sizes, and offsets
// into source (when making square images).
function fitImageSize(width, height, maxWidth, maxHeight, forceSquare) {
if (!width || !height || !maxWidth || !maxHeight) {
return null;
}
if (forceSquare) {
maxWidth = maxHeight = Math.min(maxWidth, maxHeight);
}
var scale = Math.min(
Math.min(width, maxWidth) / width,
Math.min(height, maxHeight) / height
);
var size = {
dstWidth: (width * scale) | 0,
dstHeight: (height * scale) | 0,
};
if (forceSquare) {
// Also calculate parameters for making the image square.
size.dstWidth = size.dstHeight = Math.min(size.dstWidth, size.dstHeight);
size.srcWidth = size.srcHeight = Math.min(width, height);
size.xoffset = ((width - size.srcWidth) / 2) | 0;
size.yoffset = ((height - size.srcWidth) / 2) | 0;
} else {
size.xoffset = size.yoffset = 0;
size.srcWidth = width;
size.srcHeight = height;
}
return size;
}
// Ensure file's extension matches mime content type
function fileNameForMime(fname, mime) {
var idx = SUPPORTED_IMAGE_FORMATS.indexOf(mime);
var ext = MIME_EXTENSIONS[idx];
var at = fname.lastIndexOf('.');
if (at >= 0) {
fname = fname.substring(0, at);
}
return fname + '.' + ext;
}
// Get mime type from data URL header.
function getMimeType(header) {
var mime = /^data:(image\/[-+a-z0-9.]+);base64/.exec(header);
return (mime && mime.length > 1) ? mime[1] : null;
}
// Convert uploaded image into a base64-encoded string possibly scaling
// linear dimensions or constraining to a square.
function imageFileScaledToBase64(file, width, height, forceSquare, onSuccess, onError) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onerror = function(err) {
onError("Image format unrecognized");
}
img.onload = function() {
var dim = fitImageSize(this.width, this.height, width, height, forceSquare);
if (!dim) {
onError("Invalid image");
return;
}
var canvas = document.createElement("canvas");
canvas.width = dim.dstWidth;
canvas.height = dim.dstHeight;
var ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = true;
ctx.drawImage(this, dim.xoffset, dim.yoffset, dim.srcWidth, dim.srcHeight,
0, 0, dim.dstWidth, dim.dstHeight);
var mime = (this.width != dim.dstWidth ||
this.height != dim.dstHeight ||
SUPPORTED_IMAGE_FORMATS.indexOf(file.type) < 0) ? "image/jpeg" : file.type;
var imageBits = canvas.toDataURL(mime);
var parts = imageBits.split(',');
// Get actual image type: 'data:image/png;base64,'
mime = getMimeType(parts[0]);
if (!mime) {
onError("Unsupported image format");
return;
}
// Ensure the image is not too large
var quality = 0.78;
if (mime == "image/jpeg") {
// Reduce size of the jpeg by reducing image quality
while (imageBits.length * 0.75 > MAX_INBAND_ATTACHMENT_SIZE && quality > 0.45) {
imageBits = canvas.toDataURL(mime, quality);
quality *= 0.84;
}
}
if (imageBits.length * 0.75 > MAX_INBAND_ATTACHMENT_SIZE) {
onError("The image size " + bytesToHumanSize(imageBits.length * 0.75) +
" exceeds the " + bytesToHumanSize(MAX_INBAND_ATTACHMENT_SIZE) + " limit.", "err");
return;
}
canvas = null;
onSuccess(imageBits.split(',')[1], mime, dim.dstWidth, dim.dstHeight, fileNameForMime(file.name, mime));
};
img.src = URL.createObjectURL(file);
}
// Convert uploaded image file to base64-encoded string without scaling/converting the image
function imageFileToBase64(file, onSuccess, onError) {
var reader = new FileReader();
reader.addEventListener("load", function() {
var parts = reader.result.split(',');
var mime = getMimeType(parts[0]);
if (!mime) {
onError("Failed to process image file");
return;
}
// Get image size.
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
onSuccess(parts[1], mime, this.width, this.height, fileNameForMime(file.name, mime));
}
img.onerror = function(err) {
onError("Image format not recognized");
}
img.src = URL.createObjectURL(file);
}, false);
reader.readAsDataURL(file);
}
function fileToBase64(file, onSuccess, onError) {
var reader = new FileReader();
reader.addEventListener("load", function() {
onSuccess(file.type, reader.result.split(',')[1], file.name);
});
reader.readAsDataURL(file);
}
// File pasted from the clipboard. It's either an inline image or a file attachment.
// FIXME: handle large files out of band.
function filePasted(event, onImageSuccess, onAttachmentSuccess, onError) {
var items = (event.clipboardData || event.originalEvent.clipboardData || {}).items;
for (var i in items) {
var item = items[i];
if (item.kind === "file") {
var file = item.getAsFile();
if (!file) {
console.log("Failed to get file object from pasted file item", item.kind, item.type);
continue;
}
if (file.type && file.type.split("/")[0] == "image") {
// Handle inline image
if (file.size > MAX_INBAND_ATTACHMENT_SIZE || SUPPORTED_IMAGE_FORMATS.indexOf(file.type) < 0) {
imageFileScaledToBase64(file, MAX_IMAGE_SIZE, MAX_IMAGE_SIZE, false, onImageSuccess, onError);
} else {
imageFileToBase64(file, onImageSuccess, onError);
}
} else {
// Handle file attachment
fileToBase64(file, onAttachmentSuccess, onError)
}
// Indicate that the pasted data contains a file.
return true;
}
}
// No file found.
return false;
}
// Make shortcut icon appear with a green dot + show unread count in title.
function updateFavicon(count) {
var oldIcon = document.getElementById("shortcut-icon");
if (oldIcon) {
var head = document.head || document.getElementsByTagName('head')[0];
var newIcon = document.createElement('link');
newIcon.type = "image/png";
newIcon.id = "shortcut-icon";
newIcon.rel = "shortcut icon";
newIcon.href = "img/logo32x32" + (count > 0 ? 'a' : '') + ".png";
head.removeChild(oldIcon);
head.appendChild(newIcon);
}
document.title = (count > 0 ? '('+count+') ' : '') + "Tinode";
}
// Get 32 bit integer hash value for a string. Ideally it should produce the same value
// as Java's String#hash().
function stringHash(value) {
var hash = 0;
value = "" + value;
for (var i = 0; i < value.length; i++) {
hash = ((hash<<5)-hash) + value.charCodeAt(i);
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
// Helper functions for hash navigation.
// Parse hash as in http://www.example.com/path#hash as if it were
// path and arguments.
function parseUrlHash(hash) {
// Split path from args, path -> parts[0], args->path[1]
var parts = hash.split('?', 2);
var params = {};
var path = [];
if (parts[0]) {
path = parts[0].substr(1).split("/");
}
if (parts[1]) {
parts[1].split("&").forEach(function(part) {
var item = part.split("=");
if (item[0]) {
params[decodeURIComponent(item[0])] = decodeURIComponent(item[1]);
}
});
}
return {path: path, params: params};
}
function composeUrlHash(path, params) {
var url = path.join("/");
var args = [];
for (var key in params) {
if (params.hasOwnProperty(key)) {
args.push(key + "=" + params[key]);
}
}
if (args.length > 0) {
url += "?" + args.join("&");
}
return url;
}
function addUrlParam(hash, key, value) {
var parsed = parseUrlHash(hash);
parsed.params[key] = value;
return composeUrlHash(parsed.path, parsed.params);
}
function removeUrlParam(hash, key) {
var parsed = parseUrlHash(hash);
delete parsed.params[key];
return composeUrlHash(parsed.path, parsed.params);
}
function setUrlSidePanel(hash, sidepanel) {
var parsed = parseUrlHash(hash);
parsed.path[0] = sidepanel;
return composeUrlHash(parsed.path, parsed.params);
}
function setUrlTopic(hash, topic) {
var parsed = parseUrlHash(hash);
parsed.path[1] = topic;
// Close InfoView on topic change.
delete parsed.params.info;
return composeUrlHash(parsed.path, parsed.params);
}
// END of hash navigation helper functions
// Detect server address from the URL
function detectServerAddress() {
var host = DEFAULT_HOST;
if (window.location.protocol === 'file:' || window.location.hostname === 'localhost') {
host = KNOWN_HOSTS.local;
} else if (window.location.hostname) {
host = window.location.hostname + (window.location.port ? ':' + window.location.port : '');
}
return host;
}
// Create VCard which represents topic 'public' info
function vcard(fn, imageDataUrl) {
var card = null;
if ((fn && fn.trim()) || imageDataUrl) {
card = {};
if (fn) {
card.fn = fn.trim();
}
if (imageDataUrl) {
var dataStart = imageDataUrl.indexOf(",");
card.photo = {
data: imageDataUrl.substring(dataStart+1),
type: "jpg"
};
}
}
return card;
}
// Deep-shallow compare two arrays.
function arrayEqual(a, b) {
// Compare lengths first.
if (a.length != b.length) {
return false;
}
// Order of elements is ignored.
a.sort();
b.sort();
for (var i = 0, l = a.length; i < l; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
/* BEGIN Context Menu: popup/dropdown menu */
// Function is used by context menu to set permissions.
function topicPermissionSetter(mode, params, errorHandler) {
var topic = Tinode.getTopic(params.topicName);
if (!topic) {
console.log("Topic not found: " + params.topicName);
return;
}
var am, user;
if (params.user) {
user = topic.subscriber(params.user);
if (!user) {
console.log("Subscriber not found: " + params.topicName + "[" + params.user + "]");
return;
}
am = user.acs.updateGiven(mode).getGiven();
} else {
am = topic.getAccessMode().updateWant(mode).getWant();
}
var instance = this;
topic.setMeta({sub: {user: params.user, mode: am}}).catch(function(err) {
if (errorHandler) {
errorHandler(err.message, "err");
}
});
}
function deleteMessages(all, hard, params, errorHandler) {
var topic = Tinode.getTopic(params.topicName);
if (!topic) {
console.log("Topic not found: " + params.topicName);
return;
}
var promise = all ?
topic.delMessagesAll(hard) :
topic.delMessagesList([params.seq], hard);
promise.catch(function(err) {
if (errorHandler) {
errorHandler(err.message, "err");
}
});
}
// Context menu items.
var ContextMenuItems = {
"topic_info": {title: "Info", handler: null},
"messages_clear": {title: "Clear messages", handler: function(params, errorHandler) {
deleteMessages(true, false, params, errorHandler);
}},
"messages_clear_hard": {title: "Clear for All", handler: function(params, errorHandler) {
deleteMessages(true, true, params, errorHandler);
}},
"message_delete": {title: "Delete", handler: function(params, errorHandler) {
deleteMessages(false, false, params, errorHandler);
}},
"message_delete_hard": {title: "Delete for All", handler: function(params, errorHandler) {
deleteMessages(false, true, params, errorHandler);
}},
"topic_unmute": {title: "Unmute", handler: topicPermissionSetter.bind(this, "+P")},
"topic_mute": {title: "Mute", handler: topicPermissionSetter.bind(this, "-P")},
"topic_unblock": {title: "Unblock", handler: topicPermissionSetter.bind(this, "+J")},
"topic_block": {title: "Block", handler: topicPermissionSetter.bind(this, "-J")},
"topic_delete": {title: "Delete", handler: function(params, errorHandler) {
var topic = Tinode.getTopic(params.topicName);
if (!topic) {
console.log("Topic not found: " + params.topicName);
return;
}
topic.delTopic().catch(function(err) {
if (errorHandler) {
errorHandler(err.message, "err");
}
});
}},
"permissions": {title: "Edit permissions", handler: null},
"member_delete": {title: "Remove", handler: function(params, errorHandler) {
var topic = Tinode.getTopic(params.topicName);
if (!topic || !params.user) {
console.log("Topic or user not found: '" + params.topicName + "', '" + params.user + "'");
return;
}
topic.delSubscription(params.user).catch(function(err) {
if (errorHandler) {
errorHandler(err.message, "err");
}
});
}},
"member_mute": {title: "Mute", handler: topicPermissionSetter.bind(this, "-P")},
"member_unmute": {title: "Unmute", handler: topicPermissionSetter.bind(this, "+P")},
"member_block": {title: "Block", handler: topicPermissionSetter.bind(this, "-J")},
"member_unblock": {title: "Unblock", handler: topicPermissionSetter.bind(this, "+J")},
};
class ContextMenu extends React.Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.handlePageClick = this.handlePageClick.bind(this);
this.handleEscapeKey = this.handleEscapeKey.bind(this);
this.handleClick = this.handleClick.bind(this);
}
componentWillUnmount() {
this.toggle(false);
}
componentWillReceiveProps(nextProps) {
this.toggle(nextProps.visible);
}
toggle(visible) {
if (visible) {
document.addEventListener('mousedown', this.handlePageClick, false);
document.addEventListener('keyup', this.handleEscapeKey, false);
} else {
document.removeEventListener('mousedown', this.handlePageClick, false);
document.removeEventListener('keyup', this.handleEscapeKey, false);
}
}
handlePageClick(e) {
if (ReactDOM.findDOMNode(this).contains(e.target)) {
return;
}
e.preventDefault();
e.stopPropagation();
this.props.hide();
}
handleEscapeKey(e) {
if (e.keyCode === 27) {
this.props.hide();
}
}
handleClick(e) {
e.preventDefault();
e.stopPropagation();
this.props.hide();
var item = this.props.items[e.currentTarget.dataset.id];
item.handler(this.props.params, this.props.onError);
}
render() {
if (!this.props.visible) {
return null;
}
var count = 0;
var instance = this;
var menu = [];
this.props.items.map(function(item) {
if (item && item.title) {
menu.push(
item.title === "-" ?
<li className="separator" key={count} />
:
<li onClick={instance.handleClick} data-id={count} key={count}>{item.title}</li>
);
}
count++;
});
// Ensure that menu is inside the app-container.
var hSize = 12 * REM_SIZE;
var vSize = REM_SIZE * (0.7 + menu.length * 2.5);
var left = (this.props.bounds.right - this.props.clickAt.x < hSize) ?
(this.props.clickAt.x - this.props.bounds.left - hSize) :
(this.props.clickAt.x - this.props.bounds.left);
var top = (this.props.bounds.bottom - this.props.clickAt.y < vSize) ?
(this.props.clickAt.y - this.props.bounds.top - vSize) :
(this.props.clickAt.y - this.props.bounds.top);
var position = {
left: left + "px",
top: top + "px"
};
return (
<ul className="menu" style={position}>
{menu}
</ul>
);
}
}
/* END Popup/dropdown menu */
/* The X menu to be displayed in title bars */
class MenuCancel extends React.PureComponent {
constructor(props) {
super(props);
}
render() {
return (
<a href="javascript:;" onClick={this.props.onCancel}><i className="material-icons">close</i></a>
);
}
}
class LoadSpinner extends React.PureComponent {
render() {
return (this.props.show ?
<div className="load-spinner-box"><div className="loader-spinner"></div></div> : null);
}
}
// Toggle [Title text >] -> [Title text v]
class MoreButton extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
open: props.open
};
this.handleToggle = this.handleToggle.bind(this);
}
handleToggle() {
var open = !this.state.open;
this.setState({open: open});
if (this.props.onToggle) {
this.props.onToggle(open);
}
}
render() {
return (<label className="small" onClick={this.handleToggle}>{this.props.title}...
{this.state.open ? <i className="material-icons">expand_more</i> :
<i className="material-icons">chevron_right</i>}
</label>);
}
}
/* BEGIN Lettertile: Avatar box: either a bitmap or a letter tile or a stock icon. */
class LetterTile extends React.PureComponent {
render() {
var avatar;
if (this.props.avatar === true) {
if (this.props.topic && this.props.title && this.props.title.trim()) {
var letter = this.props.title.trim().charAt(0);
var color = "lettertile dark-color" + (Math.abs(stringHash(this.props.topic)) % 16);
avatar = (<div className={color}><div>{letter}</div></div>)
} else {
avatar = (Tinode.getTopicType(this.props.topic) === "grp") ?
<i className="material-icons">group</i> :
<i className="material-icons">person</i>;
}
} else if (this.props.avatar) {
avatar = <img className="avatar" alt="avatar" src={this.props.avatar} />;
} else {
avatar = null;
}
return avatar;
}
}
/* END Lettertile */
/* BEGIN In-place text editor. Shows text with an icon
* which toggles it into an input field */
class InPlaceEdit extends React.Component {
constructor(props) {
super(props);
this.state = {
active: props.state,
text: props.text || ""
};
this.handeTextChange = this.handeTextChange.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
this.handleStartEditing = this.handleStartEditing.bind(this);
this.handleEditingFinished = this.handleEditingFinished.bind(this);
}
componentWillReceiveProps(nextProps) {
// If text has changed while in read mode, update text and discard changes.
// Ignore update if in edit mode.
if (this.props.text != nextProps.text && !this.state.active) {
this.setState({text: nextProps.text || ""});
}
}
handeTextChange(e) {
this.setState({text: e.target.value});
}
handleKeyDown(e) {
if (e.keyCode === 27) {
// Escape pressed
this.setState({text: this.props.text, active: false});
} else if (e.keyCode === 13) {
// Enter pressed
this.handleEditingFinished();
}
}
handleStartEditing() {
if (!this.props.readOnly) {
ReactDOM.findDOMNode(this).focus();
this.setState({active: true});
}
}
handleEditingFinished() {
this.setState({active: false});
var text = this.state.text.trim();
if ((text || this.props.text) && (text !== this.props.text)) {
this.props.onFinished(text);
}
}
render() {
var spanText = this.props.type === "password" ?
"••••••••" : this.state.text;
var spanClass = "in-place-edit" +
(this.props.readOnly ? " disabled" : "");
if (!spanText) {
spanText = this.props.placeholder;
spanClass += " placeholder";
}
if (spanText.length > 20) {
spanText = spanText.substring(0, 19) + "...";
}
return (
this.state.active ?
<input type={this.props.type || "text"}
value={this.state.text}
placeholder={this.props.placeholder}
onChange={this.handeTextChange}
onKeyDown={this.handleKeyDown}
onBlur={this.handleEditingFinished}
autoFocus />
:
<span className={spanClass} onClick={this.handleStartEditing}>
<span className="content">{spanText}</span>
</span>
);
}
};
/* END InPlaceEdit */
/* BEGIN Combobox for selecting host name */
class HostSelector extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
hostName: props.serverAddress,
changed: false
};
this.handleHostNameChange = this.handleHostNameChange.bind(this);
this.handleEditingFinished = this.handleEditingFinished.bind(this);
}
handleHostNameChange(e) {
this.setState({hostName: e.target.value, changed: true});
}
handleEditingFinished() {
if (this.state.changed) {
this.setState({changed: false});
this.props.onServerAddressChange(this.state.hostName.trim());
}
}
render() {
var hostOptions = [];
for (var key in KNOWN_HOSTS) {
var item = KNOWN_HOSTS[key];
hostOptions.push(
<option key={item} value={item} />
);
}
return (
<div>
<label htmlFor="host-name">Server address:</label>
<input type="search" id="host-name" placeholder={this.props.hostName} list="known-hosts"
value={this.state.hostName} onChange={this.handleHostNameChange}
onBlur={this.handleEditingFinished} required />
<datalist id="known-hosts">
{hostOptions}
</datalist>
</div>);
}
}
/* END Combobox for selecting host name */
/* BEGIN CheckBox: styled checkbox */
class CheckBox extends React.PureComponent {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange() {
this.props.onChange(this.props.name, !this.props.checked);
}
render() {
return (
this.props.onChange ? (
this.props.checked ?
<i className="material-icons blue clickable" onClick={this.handleChange}>check_box</i> :
<i className="material-icons blue clickable" onClick={this.handleChange}>check_box_outline_blank</i>
) : (
this.props.checked ?
<i className="material-icons">check_box</i> :
<i className="material-icons">check_box_outline_blank</i>
)
);
}
}
/* END CheckBox */
/* BEGIN PermissionsEditor: Component for editing permissions */
// <PermissionsEditor mode="JWROD" skip="O" onChange={this.handleCheckboxTest} />
class PermissionsEditor extends React.Component {
constructor(props) {
super(props);
this.state = {
mode: (props.mode || "").replace("N", "")
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleCancel = this.handleCancel.bind(this);
}
handleChange(val) {
var mode = this.state.mode;
var idx = mode.indexOf(val);
if (idx == -1) {
mode += val;
} else {
mode = mode.replace(val, "");
}
this.setState({mode: mode});
}
handleSubmit() {
// Normalize string, otherwise cannot check if mode has changed.
var mode = (this.state.mode || "N").split('').sort().join('');
var before = (this.props.mode || "N").split('').sort().join('')
if (mode !== before) {
this.props.onSubmit(mode);
} else {
this.props.onCancel();
}
}
handleCancel() {
this.props.onCancel();
}
render() {
var all = 'JRWPASDO';
var names = {
'J': 'Join (J)',
'R': 'Read (R)',
'W': 'Write (W)',
'P': 'Get notified (P)',
'A': 'Approve (A)',
'S': 'Share (S)',
'D': 'Delete (D)',
'O': 'Owner (O)'
};
var skip = this.props.skip || "";
var mode = this.state.mode;
var compare = (this.props.compare || "").replace("N", "");
var items = [];
for (var i=0; i<all.length; i++) {
var c = all.charAt(i);
if (skip.indexOf(c) >= 0 && mode.indexOf(c) < 0) {
// Permission is marked as inactive: hide unchecked permissions, disable checked permissions
continue;
}
items.push(
<tr key={c}>
<td>{names[c]}</td>
<td className="checkbox">{skip.indexOf(c) < 0 ?
<CheckBox name={c} checked={(mode.indexOf(c) >= 0)} onChange={this.handleChange}/>
:
<CheckBox name={c} checked={(mode.indexOf(c) >= 0)} />
}</td>{this.props.compare ? <td className="checkbox">
<CheckBox name={c} checked={(compare.indexOf(c) >= 0)}/>
</td> : null}
</tr>
);
}
return (
<div className="panel-form-column">
{this.props.userTitle ?
<ul className="contact-box"><Contact
item={this.props.item}
title={this.props.userTitle}
avatar={makeImageUrl(this.props.userAvatar ? this.props.userAvatar : null)} /></ul> : null}
<label className="small">Permissions</label>
<table className="permission-editor">
{this.props.compare ?
<thead><tr>
<th></th><th>{this.props.modeTitle}</th>
<th>{this.props.compareTitle}</th>
</tr></thead> :
null}
<tbody>
{items}
</tbody></table>
<br />
<div className="dialog-buttons">
<button className="blue" onClick={this.handleSubmit}>Ok</button>
<button className="white" onClick={this.handleCancel}>Cancel</button>
</div>
</div>
);
}
};
/* END PermissionsEditor */
/* BEGIN ChipInput: group membership widget */
class ChipInput extends React.Component {
constructor(props) {
super(props);
this.state = {
placeholder: props.chips ? "" : props.prompt,
sortedChips: ChipInput.sortChips(props.chips, props.required),
chipIndex: ChipInput.indexChips(props.chips),
input: '',
focused: false
};
this.handleTextInput = this.handleTextInput.bind(this);
this.removeChipAt = this.removeChipAt.bind(this);
this.handleChipCancel = this.handleChipCancel.bind(this);
this.handleFocusGained = this.handleFocusGained.bind(this);
this.handleFocusLost = this.handleFocusLost.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
}
componentWillReceiveProps(nextProps) {
this.setState({
sortedChips: ChipInput.sortChips(nextProps.chips, nextProps.required),
chipIndex: ChipInput.indexChips(nextProps.chips)
});
if (nextProps.chips.length > this.props.chips.length) {
// Chip added: clear input.
this.setState({input: ''});
}
}
// Map chip index to user name
static indexChips(chips) {
var index = {};
var count = 0;
chips.map(function(item) {
index[item.user] = count;
count ++;
});
return index;
}
// Have non-removable chips appear before all other chips.
static sortChips(chips, keep) {
var required = [];
var normal = [];
chips.map(function(item) {
if (item.user === keep) {
required.push(item);
} else {
normal.push(item);
}
});
return required.concat(normal);
}